Skip to content

Instantly share code, notes, and snippets.

@mdellavo
Created October 12, 2010 03:10
Show Gist options
  • Save mdellavo/621608 to your computer and use it in GitHub Desktop.
Save mdellavo/621608 to your computer and use it in GitHub Desktop.
from decimal import Decimal
from csv import DictReader, DictWriter
from datetime import datetime, timedelta
from urllib import urlopen, urlencode
import sys
from pprint import pprint
from itertools import chain
URL = 'http://ichart.yahoo.com/table.csv'
def map_price(symbol, price):
return { 'symbol' : symbol,
'date' : datetime.strptime(price['Date'], '%Y-%m-%d'),
'open' : Decimal(price['Open']),
'close' : Decimal(price['Close']),
'adjusted_close' : Decimal(price['Adj Close']),
'high' : Decimal(price['High']),
'low' : Decimal(price['Low']),
'volume' : int(price['Volume']) }
def historical(symbol, start_date, end_date):
params = { 's' : symbol,
'd' : '%02d' % end_date.day,
'e' : '%02d' % end_date.month,
'f' : str(end_date.year),
'g' : 'd',
'a' : '%02d' % start_date.day,
'b' : '%02d' % start_date.month,
'c' : str(start_date.year),
'ignore' : '.csv' }
url = URL + '?' + urlencode(params)
return ( map_price(symbol, i) for i in DictReader(urlopen(url)) )
if __name__ == '__main__':
end = datetime.now()
start = end + timedelta(days=-365)
symbols = (i.upper() for i in sys.argv[1:])
prices = chain( *(historical(symbol, start, end) for symbol in symbols ))
fields = ('symbol', 'date', 'open', 'close', 'adjusted_close', 'high', 'low', 'volume')
writer = DictWriter(sys.stdout, fields)
writer.writerow(dict( (i,i) for i in fields))
writer.writerows(prices)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment