3

I want to get daily historical stock prices into a pandas dataframe. I know how to get call the google api using the intraday url of

    api = 'http://finance.google.com/finance/getprices?q=SPY&i=300&p=3d&f=d,o,h,l,c,' 
    price = pd.read_csv(api, skiprows=8, header=None)

But I don't know how to get daily history.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
pmillerhk
  • 171
  • 1
  • 2
  • 12

1 Answers1

2

You can change the intra-day interval and the date range:

The intra-day interval is in seconds and there are 86,400 seconds in a day so you need to change i=300 to i=86,400. Something like following will get daily values and format the date and time:

days_back = 10

api = 'http://finance.google.com/finance/getprices?q=SPY&i=86400&p={0}d&f=d,o,h,l,c,'.format(str(days_back)) 
price = pd.read_csv(api, skiprows=8, header=None, names=["date", "open", "high", "low", "close"])

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in price["date"]]
price["date"] = date_list
price["date"] = price["date"].apply(lambda x: x.strftime('%Y-%m-%d'))

A look at the price DataFrame returns the following:

price

          date    open     high    low   close
0   2018-05-18  266.92  267.325 265.15  266.50
1   2018-05-17  269.50  269.865 267.09  267.68
2   2018-05-16  272.02  272.390 270.22  270.34
3   2018-05-15  272.85  273.150 271.58  272.16
4   2018-05-12  272.98  274.080 272.36  273.34
5   2018-05-11  271.10  271.610 270.03  271.59
6   2018-05-10  272.24  272.760 271.11  271.14
7   2018-05-09  272.01  273.230 271.13  271.94
8   2018-05-08  271.33  272.030 270.93  271.62
Dodge
  • 3,219
  • 3
  • 19
  • 38
  • Thanks W.Dodge ... when I run that I get an error "raise HTTPError(req.full_url, code, msg, hdrs, fp) HTTPError: Service Unavailable" . I doing something wrong? – pmillerhk May 19 '18 at 19:10
  • @pmillerhk I just tested it and did not get an error. Not sure what's causing the error for you – Dodge May 19 '18 at 19:17
  • 1
    Great workaround, although it doesn't work for the amount of days back which is greater than 66 – cool May 19 '18 at 23:59
  • Figured it out ... thanks ! Any ideas how to get further back than 60 days? – pmillerhk May 20 '18 at 12:55
  • @pmillerhk No, I’ll look into that and update if I figure it out. PleSe consider marking this as the accepted answer if it was of use. Thanks – Dodge May 20 '18 at 16:18