Algorithmic Trading & Indicators Advanced

Calculate Hurst Exponent in Python (Detect Mean-Reverting vs Trending Stocks)

Use the Rescaled Range (R/S) Hurst Exponent test in Python NumPy to classify any stock or index into Mean-Reverting (H < 0.5), Random Walk (H = 0.5), or Trending (H > 0.5).

#numpy#pandas

Problem Statement

Applying trend-following indicators to a mean-reverting stock guarantees losses. The Hurst Exponent mathematically measures the long-term memory of a time series so you deploy the right strategy per ticker.

Formula / Core Logic

Var(tau) ~ tau^(2H) H < 0.45: Mean-Reverting | 0.45 <= H <= 0.55: Geometric Random Walk | H > 0.55: Persistent Trend

Installation

pip install numpy pandas
hurst-exponent-mean-reversion-vs-trend-python.py
import numpy as np

def calculate_hurst_exponent(price_series, max_lag=20):
    lags = range(2, max_lag)
    tau = [np.sqrt(np.std(np.subtract(price_series[lag:], price_series[:-lag]))) for lag in lags]
    poly = np.polyfit(np.log(lags), np.log(tau), 1)
    hurst = poly[0] * 2.0
    regime = 'MEAN_REVERTING' if hurst < 0.45 else ('TRENDING' if hurst > 0.55 else 'RANDOM_WALK')
    return {'Hurst_Exponent': round(hurst, 4), 'Market_Regime': regime}

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: How many data points are needed for a reliable Hurst calculation?

Use at least 250 to 500 candles so the log-log regression across lags has sufficient statistical stability.