Last active
October 21, 2016 05:24
-
-
Save lordloh/97f2eb5e6e0c6f1291c54b99dae30e8d to your computer and use it in GitHub Desktop.
Python functions to get historic stock data.
This file contains hidden or 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
# Python functions to get historic stock data. | |
# Use the yql_stock_long_history wrapper. Yahoo does not return data if long requests are made - | |
# For example GOOG form 2001-01-01 to today. The wrapeer breaks the query into multiple 1y queries | |
# and combines the results | |
import json | |
import urllib | |
import time | |
from datetime import datetime, timedelta, date | |
def yql_stock_history(symbol,start_date,end_date): | |
endpoint = "https://query.yahooapis.com/v1/public/yql" | |
env = "store://datatables.org/alltableswithkeys" | |
response_format = "json" | |
query='select * from yahoo.finance.historicaldata where symbol = "'+symbol+'" and startDate = "'+start_date+'" and endDate = "'+end_date+'"' | |
params = {'format':response_format, 'env':env, 'q':query} | |
req_data = urllib.parse.urlencode(params).encode('ascii') | |
try: | |
res = urllib.request.urlopen('https://query.yahooapis.com/v1/public/yql',req_data) | |
data = res.read().decode('utf-8') | |
res.close() | |
except urllib.error.URLError as e: | |
print(e.code) | |
rise(e.code) | |
json_parsed = json.loads(data)['query']['results'] | |
if (json_parsed != None): | |
return json_parsed['quote'] | |
else: | |
return None | |
def yql_stock_long_history(symbol,start_date,end_date): | |
start_d=datetime.strptime(start_date,'%Y-%m-%d') | |
end_d=datetime.strptime(end_date,'%Y-%m-%d') | |
diff=end_d - start_d | |
max_days = 365 | |
if (diff.days < 0): | |
return None | |
elif(diff.days > max_days): | |
data_part = [] | |
s = start_d | |
while((end_d-s).days >= max_days): | |
price_history=yql_stock_history(symbol, str(s), str(s+timedelta(max_days))) | |
s=s+timedelta(days = max_days+1) | |
if (price_history == None): | |
continue | |
data_part.append(price_history) | |
price_data = [b for sublist in data_part for b in sublist] | |
price_history = yql_stock_history(symbol, str(s), str(s+timedelta(max_days))) | |
data_part.append(price_history) | |
price_data = [b for sublist in data_part for b in sublist] | |
return price_data | |
elif(diff.days == 1): | |
return [yql_stock_history(symbol, start_date, end_date)] | |
else: | |
return yql_stock_history(symbol, start_date, end_date) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment