Python Code to fetch Yahoo historical bar data

Contact us

Python Code to fetch Yahoo historical bar data for stocks. Fetches BAR data for a given symbol for a specified date range and saves that data in a CSV file named for that symbol

See Also:  Scala Source to download historical bar data from yahoo finance

# http://www.jarloo.com/yahoo_finance/ 
# Months are 0..11
 
import httplib
 
# Fetch data from Yahoo server and save to local file
def fetchYahoo(symbol, begYear, begMonth, begDay,  endYear, endMonth, endDay):
  uri = "/table.csv?s=" + symbol + "&d=" + str(endMonth) + "&e=" + str(endDay) + "&f=" + str(endYear) + "&g=d&a=" + str(begMonth) + "&b=" + str(begDay) + "&c=" + str(begYear) + "&ignore=.csv"
  print "uri=" + uri
  conn = httplib.HTTPConnection("ichart.finance.yahoo.com")
  conn.request("GET", uri)
  r1 = conn.getresponse()
  data1 = r1.read()
  #TODO: Add error checking for valid data here
 
  # Save data to CSV File
  #print data1
  fname = symbol + ".csv"
  f = open(fname, "w")
  f.write(data1)
  f.close()
  return data1
 
fetchYahoo("%5EVIX", 1990,00,01, 2013,12,31) # the %5E is URL encoded ^
fetchYahoo("SPY",  1990,00,01, 2014,01,28)

 

Sample Output from SPY.CSV

Date,Open,High,Low,Close,Volume,Adj Close
2014-02-28,185.789993,187.149994,185.050003,186.289993,150842000,176.294754
2014-02-27,184.580002,185.869995,184.369995,185.820007,93880800,175.849985
2014-02-26,185.110001,185.600006,184.330002,184.850006,98677200,174.932028
2014-02-25,185.059998,185.589996,184.229996,184.839996,117085000,174.922555
2014-02-24,184.279999,186.149994,184.199997,184.910004,114063900,174.988806
2014-02-21,184.449997,184.889999,183.800003,183.889999,118116400,174.02353
2014-02-20,183.270004,184.520004,182.600006,184.100006,104998100,174.222269
2014-02-19,183.759995,184.949997,182.869995,183.020004,126524300,173.200213
2014-02-18,184.179993,184.490005,183.649994,184.240005,80460900,174.354757

We Offer Consulting Services

Please contact us if you have a complex problem and need engineering assistance.

joeeatbayesanalytic phone number

Leave a Reply