Saturday, July 17, 2010

yapyfin.py Python Yahoo Finance Client

Yahoo Finance exposes a large amount of historical US equity data via their html api. The python code below downloads the open-high-low-close-adjclose-volume data for British Petroleum (BP) = stock ticker symbol BP, between 1900/01/01 and 2010/07/18, to text file BP.csv

import httplib
httplib.HTTPConnection.debuglevel = 1
import urllib

def enc_quote(ticker, fromY, fromM, fromD, toY, toM, toD):

quote = dict()

quote['s'] = ticker
quote['a'] = fromM
quote['b'] = fromD
quote['c'] = fromY
quote['d'] = toD
quote['e'] = toM
quote['f'] = toY
quote['g'] = "d"

return urllib.urlencode(quote)

url_stem = 'http://ichart.yahoo.com/table.csv?'
quote_tokens = enc_quote('BP', '1900', '01', '01', '2010', '07', '18')
url = url_stem + "&ignore=.csv" + quote_tokens

f = urllib.urlopen(url)
body = f.read()
f.close()

try:
f = open('BP.csv', 'w')
f.write(body)
f.close()
except Exception, err:
print('ERROR: %s\n' % str(err))

No comments:

Post a Comment

comment: