Home /

Blog

Tag archives: pandas

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 ...

Continue reading

Python: Time Series Showing Stock Price with Trading Volume

This is what we'll be looking to produce.

matplotlib

The two main libraries used in producing this are Pandas and Matplotlib.

The top plot shows the stock price of Google over a 5 year time period. The bottom plot shows the trading volume for each day.

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

google = DataReader("GOOG", "yahoo", datetime.datetime(2007, 1, 1), 
    datetime.datetime(2012,1,1))

The variable google is a Pandas Data Frame which is based on R's Data Frame. I'm passing in the stock symbol GOOG, the datasource, yahoo finance, and ...

Continue reading