Created
September 1, 2014 20:07
-
-
Save sbenario/23da3ca8466629f2f206 to your computer and use it in GitHub Desktop.
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
import os | |
import requests | |
from datetime import datetime, date | |
def generateReqString(stock, startdate, enddate): | |
#format of startdate/enddate should be 20140201 for Feb 01, 2014. | |
basequery = 'http://ichart.yahoo.com/table.csv?' | |
basequery_ending= '&ignore=.csv' | |
startdate = datetime.strptime(startdate,'%Y%m%d') | |
enddate = datetime.strptime(enddate,'%Y%m%d') | |
sd_year = int(datetime.strftime(startdate, '%Y')) | |
sd_month = int(datetime.strftime(startdate, '%m')) | |
sd_day = int(datetime.strftime(startdate, '%d')) | |
ed_year = int(datetime.strftime(enddate, '%Y')) | |
ed_month = int(datetime.strftime(enddate, '%m')) | |
ed_day = int(datetime.strftime(enddate, '%d')) | |
querystring = basequery + 's=' + stock | |
#encoding start date: | |
# a = month-1 | |
querystring = querystring + '&a=' + str(sd_month - 1) | |
# b= day number | |
querystring = querystring + '&b=' + str(sd_day) | |
# c= year number | |
querystring = querystring + '&c=' + str(sd_year) | |
#encoding end date: | |
# d = month-1 | |
querystring = querystring + '&d=' + str(ed_month - 1) | |
# b= day number | |
querystring = querystring + '&e=' + str(ed_day) | |
# c= year number | |
querystring = querystring + '&f=' + str(ed_year) | |
querystring = querystring + basequery_ending | |
return querystring | |
def pullSingleStock (stock, startdate, enddate): | |
fullreqstring = generateReqString(stock, startdate, enddate) | |
r = requests.get(fullreqstring) | |
if r.ok: | |
#should add check to make sure file doesn't exist also | |
f = open(stock+'.csv', 'w') | |
f.write(r.text) | |
f.close() | |
else: | |
print 'something terrible happened with %s query' % stock | |
print 'status: '+r.status_code | |
#set your stocks to query here: | |
stocks = ['aapl', 'msft', 'ge', 'tsla'] | |
#dates in the format YYYYMMDD | |
startdate = '20010101' | |
enddate = '20140601' | |
for stock in stocks: | |
pullSingleStock(stock, startdate, enddate) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment