我当前的代码能够从Google财经获取历史数据,但缺少标记每列的第一行。 我希望输出如下
股票,日期,时间,开放,高,低,关闭,卷 CCK,2015-12-30,00:00:00,1.05,1.05,0.99,1.00,157800 CCK,2015-12-31,00:00:00,0.98,1.03,0.98,1.02,55300
stocklist=['CCK','MSFT','AA','AAPL']
stocklen=len(stocklist)
for x in range(1,stocklen,1):
q = GoogleQuote(stocklist[x],'2015-12-21')
header = ['Stock','Date','Time','Open','High','Low','Close']
print header
print q
q.write_csv(stocklist[x]+".csv")
with open(stocklist[x]+".csv",'a') as f:
w = csv.writer(f)
w.writerow(['Stock','Date','Time','Open','High','Low','Close'])
然而,输出是最后一行
CCK,2015-12-30,00:00:00,1.05,1.05,0.99,1.00,157800 CCK,2015-12-31,00:00:00,0.98,1.03,0.98,1.02,55300 股票,日期,时间,开放,高,低,关闭,交易量
答案 0 :(得分:0)
GoogleQuote
来自哪里?是来自quotes.py ???
如果是这样,那么您的代码已经生成带有标题行的CSV文件,唯一的区别是第一列标记为Symbol
而不是Stock
。如果您反对该标签,可以像这样更改:
import csv
import datetime
from itertools import repeat
header = ['Stock', 'Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
stocklist=['CCK','MSFT','AA','AAPL']
start = datetime.datetime(2015, 12, 21)
#end = datetime.datetime(2015, 12, 31)
for stock in stocklist:
q = GoogleQuote(stock, start.strftime('%F'))
data = zip(repeat(q.symbol), q.date, q.time, q.open_, q.high, q.low, q.close, q.volume)
with open('{}.csv'.format(stock), 'w') as f:
w = csv.writer(f)
w.writerow(header)
w.writerows(data)
您可以使用pandas
:
import datetime
import pandas.io.data as web
stocklist=['CCK','MSFT','AA','AAPL']
start = datetime.datetime(2015, 12, 21)
end = datetime.datetime(2015, 12, 31)
for stock in stocklist:
data = web.DataReader(stock, 'google', start, end)
data.to_csv('{}.csv'.format(stock))
这将为包含日期范围的每个股票创建单独的CSV文件,标题行为:
Date,Open,High,Low,Close,Volume
pandas
与您的代码之间的输出差异为:
如果你真的必须有库存和时间列,可以将这些列添加到数据框中。
for stock in stocklist:
data = web.DataReader(stock, 'google', start, end)
data.insert(0, 'Time', [ts.time() for ts in data.index])
data.reset_index(inplace=True) # make Date a proper column
data.insert(0, 'Stock', stock)
data.to_csv('{}.csv'.format(stock), index=False)
请注意,日期列是时间戳,因此可能不需要添加时间列。相反,您可以省略添加时间列并使用以下内容格式化日期:
data.to_csv('{}.csv'.format(stock), index=False, date_format='%F %T')