Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Hodrick Prescott Filter (HP Filter) Analysis – Python

1 min read

Wikipedia says

The Hodrick–Prescott filter (also known as Hodrick–Prescott decomposition) is a mathematical tool used in macroeconomics, especially in real business cycle theory, to remove the cyclical component of a time series from raw data.

Hodrick Prescott Filter (HP Filter) does Time series decomposition which involves separating a time series into several distinct components(Cycle component and Trend Component). The trend represents the long-term movement or underlying growth of the series, while the cyclical component captures short-term fluctuations around the trend.

The filter involves a smoothing parameter, often denoted as λ (lambda). The choice of λ determines the trade-off between fitting the data closely and capturing fluctuations. A higher λ results in a smoother trend, while a lower λ allows the trend to capture more short-term fluctuations.

And this filter looks like it can be applied to any time-series data, especially with stock prices to understand the underlying trend and the cycle involved in it.

Here is a simple ipython notebook example for Hodrick Prescott Filter Analysis. We use statsmodel library to compute the Hodrick Prescott Filter Components, Matplotlib to plot the data, yFinance to retrieve the stock data from NSEIndia and Pandas to handle the time series data.

import yfinance as yf
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm

# Import TCS data from Yahoo Finance
TCS = yf.download('TCS.NS', start='2020-01-01', end='2023-12-31')
TCS

 Output

	Open	High	Low	Close	Adj Close	Volume
Date						
2020-01-01	2168.000000	2183.899902	2154.000000	2167.600098	2008.583252	1354908
2020-01-02	2179.949951	2179.949951	2149.199951	2157.649902	1999.362549	2380752
2020-01-03	2164.000000	2223.000000	2164.000000	2200.649902	2039.208374	4655761
2020-01-06	2205.000000	2225.949951	2187.899902	2200.449951	2039.022583	3023209
2020-01-07	2200.500000	2214.649902	2183.800049	2205.850098	2044.026733	2429317
...	...	...	...	...	...	...
2023-12-06	3532.600098	3612.850098	3525.149902	3604.100098	3604.100098	1896572
2023-12-07	3605.000000	3630.550049	3591.699951	3614.899902	3614.899902	1967653
2023-12-08	3633.000000	3645.000000	3602.050049	3626.699951	3626.699951	1641155
2023-12-11	3622.899902	3653.000000	3615.000000	3642.899902	3642.899902	1102503
2023-12-12	3638.949951	3698.399902	3631.000000	3669.949951	3669.949951	1666711

Compute and Plot the Hodrick Prescott Filter Components

# Use Statsmodels to compute Hodrick Prescott Filter Components
X = TCS['Close']
cycle, trend = sm.tsa.filters.hpfilter(X, lamb=1600)  # You can adjust the smoothing parameter 'lamb'


# Plot Stock Price, HP Cycle Component & HP Trend Component
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=TCS.index, y=TCS['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=TCS.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=TCS.index, y=cycle, fmt="r-")
plt.title("Stock:TCS - Cycle Component")
plt.ylabel("Cycle")
plt.xlabel("Date")
plt.grid(True)
plt.show()


The above chart shows the Stock TCS price and HP Filter components trend and cycles component. You might have noticed that the trend component is ultra-smooth and very good in forecasting the future of medium TCS price direction. And the Cycle Component extreme values suggest a possible trend reversal. To my view, it should be a better tool for traders and investors to know the underlying trend. Especially HP filter suits both trend followers and mean reversion traders!

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

[Course] Designing a Stock Market Trading Dashboard App using…

Designing a Stock Market App using Python is a hands-on course that guides you through the development of a functional stock market application. Over...
Rajandran R
1 min read

Exploring the Essential Python Libraries for Data Analytics

Python has emerged as a powerhouse due to its versatility, ease of use, and extensive library support. Whether you're manipulating data, visualizing trends, performing...
Rajandran R
3 min read

Integrating Tradingview Lightweight Charts with Yahoo Finance Data –…

Hey traders! If you’re looking for a way to visualize your stock data dynamically and interactively, you’re in for a treat. Today, we’ll explore...
Rajandran R
2 min read

4 Replies to “Hodrick Prescott Filter (HP Filter) Analysis – Python”

  1. I know for a fact that Prescott filter is re-calculating the past bars and so is not reliable due to repainting. So how can it be used for trading?

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More