Tutorial on Hodrick Prescott Filter Analysis

In [1]:
from nsepy.archives import get_price_history
from datetime import date
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

Import TCS data from NSEindia

In [2]:
S1 = get_price_history(stock = 'TCS', 
                        start = date(2015,1,1), 
                        end = date(2015,11,27))

Use Statsmodels to compute Hodrick Prescott Filter Components

In [3]:
import statsmodels.api as sm
dta = sm.datasets.macrodata.load()
X = S1.Close
cycle, trend = sm.tsa.filters.hpfilter(X,1600)

Plot Stock Price, HP Cycle Component & HP Trend Component

In [4]:
fig_size = plt.rcParams["figure.figsize"]

fig_size[0] = 12
fig_size[1] = 12

plt.subplot(3, 1, 1)
plt.rcParams["figure.figsize"] = fig_size
plt.plot_date(x=S1.index, y=S1.Close, fmt="r-")
plt.title("Stock:TCS - Hodrick Prescott Filter Analysis")
plt.ylabel("Price")
plt.xlabel("Date")
plt.grid(True)
plt.show()

plt.subplot(3, 1, 2)
plt.rcParams["figure.figsize"] = fig_size
plt.plot_date(x=S1.index, y=trend, fmt="r-")
plt.title("Stock:TCS - Trend Component")
plt.ylabel("Trend")
plt.xlabel("Date")
plt.grid(True)
plt.show()

plt.subplot(3, 1, 3)
plt.rcParams["figure.figsize"] = fig_size
plt.plot_date(x=S1.index, y=cycle, fmt="r-")
plt.title("Stock:TCS - Cycle Component")
plt.ylabel("Cycle")
plt.xlabel("Date")
plt.grid(True)
plt.show()