Pandas – Plotting a stock chart with Pandas in IPython

matplotlibpandas

I'm just getting started with Python/Pandas and put together the following code to plot the S&P 500.

from pandas.io.data import DataReader
# returns a DataFrame
sp500 = DataReader("^GSPC", "yahoo", start=datetime.datetime(1990, 1, 1))
sp500.plot(figsize = (12,8))

It looks like this is plotting the high, low, open, close, adj close, and volume all on one graph. Is there an easy way to plot just the adj close in one graph and the volume right below it like they do on Yahoo and most other financial sites? I'd also be interested in an example of plotting an OHLC candlestick chart.

Best Answer

See here for my answer to a similar question and here for further information regarding mathplotlib's finance candlestick graph.

To get just the adj close from your sp500, you would use something like sp500["Adj Close"] and then pass that to the relevant matplotlib plot command plt.plot(datelist, sp500["Adj Close"] ) where datelist is your list of dates on the x axis.

I believe you can get datelist by referencing sp500.index, see here for more information.

As for your issue with passing it to the plot command, something like

datelist = [date2num(x) for x in sp500.index] where the function date2num is from matplotlib.dates package.

After setting up the relevant subplot, and then call the appropriate fill command to fill_between_alpha the area under the line like the Yahoo graph you linked to.

See here under the Fill Between and Alpha heading for another snippet that shows a filled line graph, with correct date printing.

The initial link has a sample matplotlib snippet which also covers the date format and formatting in more detail.