Search code examples
python-2.7quandl

Quandl stock API historical data


So Im using the Quandl API for stock data, and I want to get a list of the closing values for the last month. Here is my code:

import quandl
import datetime as dt

quandl.ApiConfig.api_key = '<API_KEY>'


today=dt.date.today()
thirty_days=dt.timedelta(days=30)   

thirty_days_ago=today-thirty_days



my_list=[]

data = quandl.get("WIKI/AAPL", start_date=str(thirty_days_ago), end_date=str(today),column_index=4)
print '================================================='
my_list.append(data)
print my_list

And the output is:

=================================================
[               Close
Date                
2017-04-20  142.4400
2017-04-21  142.2700
2017-04-24  143.6400
2017-04-25  144.5400
2017-04-26  143.6508
2017-04-27  143.7900
2017-04-28  143.6500
2017-05-01  146.6000
2017-05-02  147.5100
2017-05-03  147.0600
2017-05-04  146.5300
2017-05-05  148.9600
2017-05-08  153.0000
2017-05-09  153.9600
2017-05-10  153.2600
2017-05-11  153.9500
2017-05-12  156.1000
2017-05-15  155.7000
2017-05-16  155.4700
2017-05-17  150.2500
2017-05-18  152.5400
2017-05-19  152.9600]

Which is mostly good. However, I can't get this data into something I can plot in a graph. It is in a list, however if I print my_list[0] it prints the entire thing, and if I print my_list[1] it says its out of range. I know the list technically has one element, because there are no commas, I'm just wondering if there is a way I can split it (.split doesn't work) up into each closing price that I can then use in a list. (I.E. [date1,price1,date2,price2,etc])


Solution

  • quandl return as pandas DataFrame object, which can be easily plotted, i.e.:

    import quandl
    import datetime as dt
    import matplotlib.pyplot as plt
    
    today=dt.date.today()
    thirty_days=dt.timedelta(days=30)
    thirty_days_ago=today-thirty_days
    data = quandl.get("WIKI/AAPL", start_date=str(thirty_days_ago), end_date=str(today),column_index=4)
    data.plot();
    plt.show()
    

    If you need, you can change the return value to a numpy array by using:

    data = quandl.get("WIKI/AAPL", returns="numpy")
    

    I don't see the need for a new list, drop it, unless you've some strong reason for it.