Created
May 19, 2013 18:18
-
-
Save szs8/5608485 to your computer and use it in GitHub Desktop.
Downloading splits and dividends from yahoo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import dateutil | |
from datetime import date, datetime | |
import numpy as np | |
import pandas as pd | |
import requests | |
class YahooException(Exception): | |
pass | |
def get_dividends_splits(sym, start, end): | |
""" | |
Returns a tuple of 2 pandas series representing dividends and | |
splits for the given symbol | |
Yahoo API: | |
http://ichart.finance.yahoo.com/x?a=0&b=1&c=2000&d=11&e=31&f=2013&s=NVDA&y=0&g=v | |
4:1 split = 4 shares for 1 share | |
This function will report that as .25 | |
Params: | |
sym: str, yahoo sym | |
start: datetime.date | |
end: datetime.date """ | |
if not isinstance(start, (datetime, date)): | |
start = dateutil.parser.parse(str(start)) | |
if not isinstance(end, (datetime, date)): | |
end = dateutil.parser.parse(str(end)) | |
payload = {'a':start.month, 'b': start.day, 'c': start.year, | |
'd':end.month, 'e':end.day, 'f':end.year, 's':sym, | |
'g':'v'} | |
r = requests.get('http://ichart.finance.yahoo.com/x', params=payload) | |
if r.status_code != requests.codes.ok: | |
raise YahooException('Could not get data for %s' % (sym,)) | |
data = r.text.split('\n')[1:-5] | |
if len(data) == 0: | |
return pd.DataFrame(), pd.DataFrame() | |
cols = ['action', 'date', 'rate'] | |
df = pd.DataFrame([i.split(',') for i in data ], columns=cols) | |
df['date'] = df.date.apply(lambda x : dateutil.parser.parse(x).date()) | |
div = df.ix[df['action'] == 'DIVIDEND', ['date', 'rate']].set_index('date') | |
div.rate = div.rate.astype(np.float) | |
spl = df.ix[df['action'] == 'SPLIT', ['date', 'rate']].set_index('date') | |
spl.rate = spl.rate.apply(lambda x : np.divide(*map(float, x.split(':')))) | |
spl.rate = 1 / spl.rate | |
return div.reset_index(), spl.reset_index() | |
def get_dividends(sym, start, end): | |
return get_dividends_splits(sym, start, end)[0] | |
def get_splits(sym, start, end): | |
return get_dividends_splits(sym, start, end)[-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment