Saturday, December 13, 2014

How to get historical stock prices

price_history
In [1]:
import collections 

#two third party libraries.  Install via command line via pip.  
#i.e. "pip install ystockquote" and "pip install pandas"
import ystockquote 
import pandas 
In [2]:
def get_price_history(ticker, start_date, end_date):
        """
        example usage:
        get_price_history('appl','2014-11-01','2014-11-30')
        returns a pandas dataframe

        """
        data = ystockquote.get_historical_prices(ticker, start_date, end_date)
        df = pandas.DataFrame(collections.OrderedDict(sorted(data.items()))).T
        df = df.convert_objects(convert_numeric=True)
        return df
In [3]:
get_price_history('aapl','2014-10-31','2014-11-04')
Out[3]:
Adj Close Close High Low Open Volume
2014-10-31 107.53 108.0 108.04 107.21 108.01 44639300
2014-11-03 108.93 109.4 110.30 108.01 108.22 52282600
2014-11-04 108.13 108.6 109.49 107.72 109.36 41574400
In [4]:
get_price_history('aapl','2014-10-31','2014-11-04')['Adj Close']
Out[4]:
2014-10-31    107.53
2014-11-03    108.93
2014-11-04    108.13
Name: Adj Close, dtype: float64
In [5]:
get_price_history('aapl','2012-10-31','2014-11-04')['Adj Close'].plot()
Out[5]:
<matplotlib.axes.AxesSubplot at 0x1073b4210>

No comments:

Post a Comment