Where does GoogleQuote
come from? Is it from quotes.py ???
If so then your code will already produce CSV files with the header line, the only difference being that the first column is labelled Symbol
rather than Stock
. If you object to that label you can change it like this:
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)
You could use 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))
This will create separate CSV files for each stock for the range of dates inclusive, with header line:
Date,Open,High,Low,Close,Volume
The differences in output between pandas
and your code is:
- Stock not present as first column in CSV. Since each file is named
according to the stock it is not required in the file itself.
- Time column not present. Quotes are for a date so the time may not be relevant.
If you really must have stock and time columns these can be added to the data frame.
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)
Note that the date column is a timestamp, so adding the time column may not be necessary. Instead you could omit addition of the Time column and format the date with:
data.to_csv('{}.csv'.format(stock), index=False, date_format='%F %T')