简体   繁体   中英

How would I transfer CSV “words” into Python as strings

So I am quite the beginner in Python, but what I'm trying to do is to download each CSV file for the NYSE. In an excel file I have every symbol. The Yahoo API allows you to download the CSV file by adding the symbol to the base url. My first instinct was to use pandas, but pandas doesn't store strings.

So what I have

import urllib

strs = ["" for x in range(3297)]

#strs makes the blank string array for each symbol

#somehow I need to be able to iterate each symbol into the blank array spots 

while y < 3297:
    strs[y] = "symbol of each company from csv" 
    y = y+1

#loop for downloading each file from the link with strs[y].

while i < 3297:
    N = urllib.URLopener()
    N.retrieve('http://ichart.yahoo.com/table.csv?s='strs[y],'File')
    i = i+1

Perhaps the solution is simpler than what I am doing.

From what I can see in this question you can't see how to connect your list of stock symbols to how you read the data in Pandas. eg 'http://ichart.yahoo.com/table.csv?s='strs[y] is not valid syntax.

Valid syntax for this is

pd.read_csv('http://ichart.yahoo.com/table.csv?s={}'.format(strs[y]))

It would be helpful if you could add a few sample lines from your csv file to the question. Guessing at your structure you would do something like:

import pandas as pd

symbol_df = pd.read_csv('path_to_csv_file')

for stock_symbol in symbol_df.symbol_column_name:
    df = pd.read_csv('http://ichart.yahoo.com/table.csv?s={}'.format(stock_symbol))
    # process your dataframe here

Assuming you take that Excel file w/ the symbols and output as a CSV, you can use Python's built-in CSV reader to parse it:

import csv
base_url = 'http://ichart.yahoo.com/table.csv?s={}'
reader = csv.reader(open('symbols.csv'))
for row in reader:
    symbol = row[0]
    data_csv = urllib.urlopen(base_url.format(symbol)).read()
    # save out to file, or parse with CSV library...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM