Algorithmic Trading & Indicators
Beginner
Calculate Hull Moving Average (HMA) for Zero-Lag Trend Following in Python
Compute Alan Hull's High-Speed Hull Moving Average (HMA) in Python Pandas, eliminating lag while maintaining exceptional smoothness.
#pandas#numpy
Problem Statement
Simple and Exponential Moving Averages suffer from severe lag during rapid price acceleration. The Hull Moving Average solves lag entirely using weighted WMA math.
Formula / Core Logic
HMA = WMA(2 * WMA(n/2) - WMA(n), sqrt(n))
Installation
pip install pandas numpy
hull-moving-average-hma-zero-lag-python.py
import pandas as pd
import numpy as np
\.def calculate_hma(df, period=16):
def wma(ser, p):
weights = np.arange(1, p + 1)
return ser.rolling(p).apply(lambda x: np.dot(x, weights) / weights.sum(), raw=True)
half_p = int(period / 2)
sqrt_p = int(np.sqrt(period))
wma_half = wma(df['Close'], half_p)
wma_full = wma(df['Close'], period)
diff = (2 * wma_half) - wma_full
hma = wma(diff, sqrt_p)
df['HMA'] = hma
return df
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: Why does HMA have zero lag compared to EMA?
By subtracting a weighted moving average of half period from full period and smoothing by square root, HMA mathematically cancels out lag.