Hurst Exponent in Python: Trend Persistence vs Mean Reversion, with the Finite-Sample Traps

The Hurst exponent separates trend persistence from mean reversion only if you apply the estimator to returns rather than price levels and compare the result against a finite-sample null. On pure white noise with N=4096, classic R/S reads about 0.55, and DFA on a random-walk level series reads about 1.48.

This post implements two estimators in numpy, measures them on seeded synthetic series, and documents the traps that turn a Hurst reading into a false signal. For mean-reversion speed once you confirm H below 0.5, see the Ornstein-Uhlenbeck half-life post. For stationarity versus memory, see fractional differentiation.


What the Hurst exponent measures

The Hurst exponent H summarizes long-range dependence. H = 0.5 indicates no memory in the increments, H above 0.5 indicates persistence, and H below 0.5 indicates anti-persistence. Lo (1991), Econometrica states that the rescaled-range statistic was first proposed by the hydrologist Harold Edwin Hurst (1951), and Lo then extended it into a test that is robust to short-range dependence.

The statistic is a scalar summary of whether past increments carry information about future increments. It is not a forecast. The Aperiodic Methods notebook describes the Hurst exponent as “a method for measuring the self-similarity of a signal,” which is the right frame for quant work: you are testing for memory, not predicting direction.


The level-vs-returns mistake

Compute the exponent on returns, not on price levels. In our seeded runs, DFA on a random-walk level series returns alpha ≈ 1.479 (sd 0.040), while DFA on its white-noise increments returns alpha ≈ 0.501 (sd 0.018). The level reading describes the stochastic trend, not memory in the increments.

A random-walk price has no memory in its increments by construction. Running DFA on the cumulative sum detects the integration and reads near 1.5. Difference first: use log-returns for equities, and take increments before measuring H on any nonstationary series.


Estimator 1: classic R/S in numpy

The classic rescaled-range estimator splits the series into windows of size n, divides the range of mean-adjusted cumulative deviations by the window standard deviation, and reads H as the slope of log(R/S) against log(n).

import numpy as np

def hurst_rs(x, min_window=8, max_window=None):
    x = np.asarray(x, dtype=float)
    n = len(x)
    if max_window is None:
        max_window = n // 2
    sizes = []
    w = min_window
    while w <= max_window:
        sizes.append(int(w))
        w = int(w * 1.5)
    rs_means, used = [], []
    for sz in sizes:
        n_chunks = n // sz
        if n_chunks < 1:
            continue
        chunked = x[: n_chunks * sz].reshape(n_chunks, sz)
        deviations = np.cumsum(chunked - chunked.mean(axis=1, keepdims=True), axis=1)
        r = deviations.max(axis=1) - deviations.min(axis=1)
        s = chunked.std(axis=1, ddof=0)
        valid = s > 0
        if valid.sum() == 0:
            continue
        rs_means.append(np.mean(r[valid] / s[valid]))
        used.append(sz)
    if len(rs_means) < 2:
        raise ValueError("Not enough window sizes for regression")
    coeffs = np.polyfit(np.log(np.array(used)), np.log(rs_means), 1)
    return float(coeffs[0])

On pure white noise at N=4096, this estimator returns H ≈ 0.549, not 0.5. That gap is the finite-sample bias the next sections address.


Estimator 2: DFA-1 in numpy

Detrended fluctuation analysis integrates the series, splits the profile into boxes of length n, fits a least-squares line in each box, and takes the root-mean-square fluctuation F(n) over all points. The scaling exponent alpha is the slope of log F(n) against log n. Peng et al. (1994), Phys Rev E 49:1685-1689 introduced the method, and Peng et al. (1995), Chaos 5:82-87 applied it to heartbeat series. The PhysioNet DFA documentation gives the same procedure.

def dfa1(x, min_box=8, max_box=None):
    x = np.asarray(x, dtype=float)
    n = len(x)
    if max_box is None:
        max_box = n // 4
    profile = np.cumsum(x - x.mean())
    sizes = []
    b = min_box
    while b <= max_box:
        sizes.append(int(b))
        b = int(b * 1.5)
    f_vals, used = [], []
    for sz in sizes:
        n_boxes = n // sz
        if n_boxes < 1:
            continue
        y = profile[: n_boxes * sz].reshape(n_boxes, sz)
        t = np.arange(sz, dtype=float)
        sq_resid = []
        for i in range(n_boxes):
            coeffs = np.polyfit(t, y[i], 1)
            trend = np.polyval(coeffs, t)
            sq_resid.append((y[i] - trend) ** 2)
        f_vals.append(np.sqrt(np.mean(np.concatenate(sq_resid))))
        used.append(sz)
    if len(f_vals) < 2:
        raise ValueError("Not enough box sizes for regression")
    coeffs = np.polyfit(np.log(np.array(used)), np.log(f_vals), 1)
    return float(coeffs[0])

DFA reads alpha ≈ 0.501 on white noise at N=4096, close to 0.5. The Aperiodic Methods notebook reports that for 1/f signals, when an oscillation is present, DFA under-estimates the expected value, so screen a series for periodic components before reading alpha.


The finite-sample trap: 0.5 is not the null

H = 0.5 is not the right threshold on a finite sample. On seeded iid N(0,1) series (N=4096, 20 seeds), classic R/S returns H = 0.549 (sd 0.017), a clear upward bias, while DFA returns alpha = 0.501 (sd 0.018). If you compare an R/S reading against 0.5, white noise looks like a trend.

A 0.55 reading on noise therefore sets the bar a real trend must clear. At N=4096 the bias is still about 0.05 above the theoretical value. Build the null for your own sample length and estimator before interpreting any number.


The measurement table

Each row uses 20 seeds (0–19) at N=4096. The numbers below are the output of the code in this post, which you can rerun.

Series R/S H (sd) DFA alpha (sd) Theoretical reference
White noise (iid N(0,1)) 0.549 (0.017) 0.501 (0.018) 0.5
Random walk levels (cumsum) 0.992 (0.012) 1.479 (0.040) not 0.5; levels are nonstationary
AR(1), phi = +0.5 0.621 (0.018) 0.590 (0.019) above 0.5 (positive autocorrelation)
AR(1), phi = -0.5 0.483 (0.016) 0.430 (0.017) below 0.5 (negative autocorrelation)

Three readings matter. On white noise, R/S sits 0.05 above 0.5 while DFA sits at 0.5. On random-walk levels, both estimators land far from 0.5, which is why levels are the wrong input. On the AR(1) rows, both estimators order the series correctly: positive autocorrelation reads above 0.5 and negative reads below.

The code that produces the table:

N = 4096
N_SEEDS = 20

def make_white_noise(seed):
    r = np.random.default_rng(seed)
    return r.normal(size=N)

def make_random_walk(seed):
    return np.cumsum(make_white_noise(seed))

def make_ar1(phi, seed):
    r = np.random.default_rng(seed)
    x = np.empty(N)
    x[0] = r.normal()
    for t in range(1, N):
        x[t] = phi * x[t - 1] + r.normal()
    return x

labels = ["white_noise", "random_walk", "ar1_pos", "ar1_neg"]
gens = [make_white_noise, make_random_walk,
        lambda s: make_ar1(0.5, s), lambda s: make_ar1(-0.5, s)]
for label, gen in zip(labels, gens):
    rs_vals, dfa_vals = [], []
    for seed in range(N_SEEDS):
        x = gen(seed)
        rs_vals.append(hurst_rs(x))
        dfa_vals.append(dfa1(x))
    print(f"{label:14s}  R/S={np.mean(rs_vals):.3f} ({np.std(rs_vals):.3f})  "
          f"DFA={np.mean(dfa_vals):.3f} ({np.std(dfa_vals):.3f})")

The shuffled-null check

Shuffling the series destroys temporal order while keeping the marginal distribution, so the shuffled estimate is the estimator’s reading on an iid series of the same length. Repeat the shuffle many times and compare your observed H with the resulting band.

def shuffled_null(x, estimator, n_perm=200, seed=42):
    rng = np.random.default_rng(seed)
    null_vals = [estimator(rng.permutation(x)) for _ in range(n_perm)]
    arr = np.array(null_vals)
    return float(np.percentile(arr, 2.5)), float(np.median(arr)), float(np.percentile(arr, 97.5))

x_ar1_neg = make_ar1(-0.5, seed=7)
for name, est in [("DFA", dfa1), ("R/S", hurst_rs)]:
    h_obs = est(x_ar1_neg)
    lo, med, hi = shuffled_null(x_ar1_neg, est, n_perm=200, seed=42)
    print(f"{name} on AR(1) phi=-0.5 seed=7: H={h_obs:.3f} | "
          f"shuffled null 2.5/50/97.5 = [{lo:.3f}, {med:.3f}, {hi:.3f}]")

On the seed-7 series, the printed output is:

  • DFA: H = 0.435, shuffled null [0.448, 0.498, 0.547]. The reading falls just below the 2.5th percentile of the null.
  • R/S: H = 0.498, shuffled null [0.504, 0.547, 0.584]. The reading falls below the null, and the null itself sits near 0.55.

The two nulls differ because each estimator has its own finite-sample bias. R/S’s null centers near 0.55, while DFA’s centers near 0.50. Calibrate each estimator against its own null. This check tests against iid noise only, so it does not account for real serial structure beyond what the permutation destroys.


Why Lo’s modified R/S is not a free fix

Lo (1991), Econometrica proposed a modified R/S test that is robust to short-range dependence. Applied to daily and monthly stock return indexes, it found no evidence of long-range dependence once short-range dependence was accounted for.

Teverovsky, Taqqu and Willinger (1999) examined the statistic and report that as the truncation lag q increases, the test statistic has a strong bias toward accepting the null of no long-range dependence, even for purely long-range-dependent data. Treat q as a parameter to report and test across values, not a setting to tune until the result looks right.


When to use which estimator

Compute both on returns. Use classic R/S only with a shuffled null and a long series, because its finite-sample bias is large. Use DFA for nonstationary series, and screen for periodic components because they bias the DFA reading. Treat Lo’s modified R/S with caution given the truncation-lag result above.

The nolds package and the hurst PyPI package both provide Hurst-style estimators. Verify the exact API from each project’s README before quoting a signature in production code.


FAQ

Should I compute the Hurst exponent on prices or returns?

On returns. In our seeded runs, DFA on a random-walk level series returns alpha ≈ 1.479, while the same estimator on its white-noise increments returns ≈ 0.501. Levels are nonstationary, so the reading describes the stochastic trend, not memory in the increments.

Probably not. Classic R/S on pure iid noise at N=4096 returns H = 0.549 (sd 0.017) in our measurements, a small-sample upward bias. Shuffle the returns, recompute H many times, and call persistence only if your reading sits above that null band.

Is Lo’s modified R/S the safe default?

No. Lo (1991) built it to be robust to short-range dependence. Teverovsky, Taqqu and Willinger (1999) show its truncation-lag bias toward accepting no long-range dependence as q grows, so report q and test sensitivity to it.


How This Post Was Built

Every number comes from the code in this post, run on seeded synthetic series (N=4096, 20 seeds, numpy only, no network calls). The citations are Lo (1991), Teverovsky et al. (1999), Peng et al. (1994, 1995), and the PhysioNet DFA documentation. This post is based on the cited papers and on synthetic series; we did not run the method on live market data.


The Bottom Line

The Hurst exponent is informative but fragile. Compute it on returns, not levels. Read R/S against its own shuffled null, since its bias sits near 0.55 on iid noise at N=4096. Use DFA for nonstationary series, and check for periodic components before trusting alpha.

← Back to all posts