从列表中抓取库存数据

时间:2014-12-04 00:31:11

标签: python python-2.7

我目前正在开发一个非常基本的程序来获取库存数据并将其复制到.csv文件中。不确定如果我正确使用for x in list,因为我只复制了一个股票的数据,而不是列表中每个股票的单独文件。

from datetime import date, timedelta
import urllib
import os

enddate = date.today()
startdate = enddate + timedelta(-30) # last 30 days
stocks = ["^RUT", "NFLX", "YHOO", "AAPL", "GOOG"]
for stock in stocks:
    print stock

STOCK_URL = 'http://ichart.finance.yahoo.com/table.csv'
PARAMS = {
    'a': startdate.month-1,
    'b': startdate.day,
    'c': startdate.year,
    'd': enddate.month-1,
    'e': enddate.day,
    'f': enddate.year,
    'g': 'd',
    'ignore': '.csv'
}

def pulldata(stock, filename):
    print "Retrieving latest data..."
    params = PARAMS.copy()
    params['s'] = stock
    url = "%s?%s" % (STOCK_URL, urllib.urlencode(params))
    return urllib.urlretrieve(url, filename)
try:
    folder = os.stat("My Stock Data/")
except:
    folder = os.mkdir("My Stock Data/")
filename, headers = pulldata(stock, "My Stock Data/" + stock + "-data.csv")
print "Done"

1 个答案:

答案 0 :(得分:1)

这正是您的代码的样子吗?

如果是这样,我希望看到打印出来的股票名称,然后只看到GOOG的数据,然后是" Done"。

尝试抓住for循环,将其向下移动到调用pulldata之前,并缩进该行,使其看起来像

try:
    folder = os.stat("My Stock Data/")
except:
    folder = os.mkdir("My Stock Data/")

for stock in stocks:
    print(stock)
    filename, headers = pulldata(stock, "My Stock Data/" + stock + "-data.csv")

print("Done")