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.
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