Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas yahoo finance DataReader

Tags:

python

pandas

I am trying to get the Adj Close prices from Yahoo Finance into a DataFrame. I have all the stocks I want but I am not able to sort on date.

stocks = ['ORCL', 'TSLA', 'IBM','YELP', 'MSFT']
ls_key = 'Adj Close'
start = datetime(2014,1,1)
end = datetime(2014,3,28)    
f = web.DataReader(stocks, 'yahoo',start,end)


cleanData = f.ix[ls_key]
dataFrame = pd.DataFrame(cleanData)

print dataFrame[:5]

I get the following result, which is almost perfect.

              IBM   MSFT   ORCL    TSLA   YELP
Date                                           
2014-01-02  184.52  36.88  37.61  150.10  67.92
2014-01-03  185.62  36.64  37.51  149.56  67.66
2014-01-06  184.99  35.86  37.36  147.00  71.72
2014-01-07  188.68  36.14  37.74  149.36  72.66
2014-01-08  186.95  35.49  37.61  151.28  78.42

However, the Date is not an Item. so when I run:

print dataFrame['Date']

I get the error:

KeyError: u'no item named Date'

Hope anyone can help me adding the Date.

like image 485
nick appel Avatar asked Apr 10 '14 14:04

nick appel


People also ask

Does pandas DataReader support Yahoo?

Indeed, pandas and pandas-datareader have been updated and now we can continue to use the Yahoo API smoothly, hopefully for a long time ahead.

What is PDR in Python?

The Planetary Data Reader (pdr): a Python toolkit for reading planetary data.


2 Answers

import pandas_datareader.data as web
import datetime    

start = datetime.datetime(2013, 1, 1)
end = datetime.datetime(2016, 1, 27)
df = web.DataReader("GOOGL", 'yahoo', start, end)

dates =[]
for x in range(len(df)):
    newdate = str(df.index[x])
    newdate = newdate[0:10]
    dates.append(newdate)

df['dates'] = dates

print df.head()
print df.tail()
like image 189
Dave Paper Avatar answered Sep 19 '22 12:09

Dave Paper


Date is in the index values.

To get it into a column value, you should just use:

dataframe.reset_index(inplace=True,drop=False)

Then you can use

dataframe['Date'] 

because "Date" will now be one of the keys in your columns of the dataframe.

like image 42
J-Eubanks Avatar answered Sep 21 '22 12:09

J-Eubanks