Home /

Blog

Calculate Moving Average Using Python

Previously, I've shown you how to plot the price of stock using pandas. This time, let's apply Moving Averages to the plot.

from pandas.io.data import DataReader
import matplotlib.pyplot as plt
import datetime
import pandas as pd

msft = DataReader("MSFT", "yahoo", datetime.datetime(2007, 1, 1),
datetime.datetime(2012,1,1))
msft['30_MA_Open'] = pd.stats.moments.rolling_mean(msft['Open'], 30)
msft['150_MA_Open'] = pd.stats.moments.rolling_mean(msft['Open'], 150)
msft[20:60]

We first create a dataframe using DataReader. Next, we make 2 new columns call 30_MA_Open and 150_MA_Open and use the rolling_mean function. So, now the dataframe contains these values:

To overlay the moving averages on to the plot, we can simply add the like so:

top = plt.subplot2grid((4,4), (0, 0), rowspan=3, colspan=4)
top.plot(msft.index, msft['Open'], label='Open')
top.plot(msft.index, msft['30_MA_Open'], label='30 Day MA')
top.plot(msft.index, msft['150_MA_Open'], label='150 Day MA')
plt.title('Microsoft Opening Stock Price from 2007 - 2012')
plt.legend()

bottom = plt.subplot2grid((4,4), (3,0), rowspan=1, colspan=4)
bottom.bar(msft.index, msft['Volume'])

plt.title('Microsoft Trading Volume')
plt.gcf().set_size_inches(15,8)

Next entry

Previous entry

Similar entries

Pingbacks

Pingbacks are closed.

comments powered by Disqus