Quant techniques · regime models

Calm or stressed? Detecting regimes with the Hamilton filter

Risk managers often talk about “regimes”: long calm stretches, then periods when everything moves a lot. You can’t see the regime, only the returns it produces. A hidden Markov model makes that idea precise, and the Hamilton filter turns each new return into an updated probability that you’re in the stressed state. It’s Bayes’ rule, applied once a day.

1st∈{0,1},P(st=j∣st−1=i)=pij,rt∣st∼N(0,σst2)s_t \in \{0, 1\},\quad P(s_t = j \mid s_{t-1} = i) = p_{ij},\quad r_t \mid s_t \sim N(0, \sigma_{s_t}^2) A hidden two-state Markov chain (calm, stressed). Each day’s return is normal with the current regime’s volatility.
2πt∣t−1=P⊤πt−1∣t−1\pi_{t|t-1} = P^\top \pi_{t-1|t-1} Predict: push yesterday’s regime probabilities through the transition matrix.
3πt∣t(j)∝πt∣t−1(j) φ(rt; 0,σj)\pi_{t|t}(j) \propto \pi_{t|t-1}(j)\,\varphi(r_t;\,0,\sigma_j) Update: multiply by how likely today’s return is under each regime, and normalise. That’s Bayes.
4E[duration in i]=11−piiE[\text{duration in } i] = \dfrac{1}{1 - p_{ii}} Regimes last a geometric number of days. p00=0.98p_{00} = 0.98 means calm spells average 50 days.
The model

A hidden coin that changes slowly

Each day the market is in one of two states. In the calm state returns have 0.7% daily vol; in the stressed state, 2%. The state persists: from calm, tomorrow is calm with probability 0.98; from stressed, stressed with probability 0.95. Those numbers set how long each regime lasts on average (50 and 20 days, by the geometric distribution) and how much of the time is spent in each:

P(stressed)=1−p00(1−p00)+(1−p11)=0.020.07≈28.6%P(\text{stressed}) = \frac{1 - p_{00}}{(1 - p_{00}) + (1 - p_{11})} = \frac{0.02}{0.07} \approx 28.6\%

Mixing two normals with different variances gives fat tails: the unconditional kurtosis of these returns is about 6.4, against 3 for a single normal, even though every day is normal given its regime. It’s the same mechanism as in GARCH, but with discrete jumps in volatility instead of smooth changes.

The filter

Predict, then update

You want P(st=stressed∣r1,…,rt)P(s_t = \text{stressed} \mid r_1, \dots, r_t): the regime probability given everything seen so far. Hamilton (1989) showed it follows a two-step recursion.

Predict. Before seeing today’s return, the regime might have switched overnight. If yesterday you were 90% sure it was calm, today’s prior for calm is 0.9×0.98+0.1×0.05=0.8870.9 \times 0.98 + 0.1 \times 0.05 = 0.887.

Update. Then today’s return arrives. A −3% move is very unlikely in the calm regime (4.3 calm standard deviations) but ordinary when stressed (1.5). Bayes’ rule multiplies each prior by the likelihood of the observed return and renormalises. Starting from a 30% prior for stressed, one −3% day pushes it to 99.8%.

That’s why the filter reacts quickly to a switch into stress: one or two big moves are strong evidence. Switching back to calm is slower, since small returns are fairly likely in both regimes and each quiet day is only weak evidence.

P(stay calm)P(stay stressed)

Daily returns (calm σ = 0.7%, stressed σ = 2%), true stressed periods shaded

Estimated chance we're in the stressed regime

truly stressedHamilton filter P(stressed | data so far)20-day rolling vol, scaled (signal when above the dashed line)
–days classified right, filter (P > 50%)
–days classified right, 20-day rolling vol
–filter's average delay spotting a switch (days)
–rolling vol's average delay (days)

The filter (orange) is compared with a simpler rule: call it stressed when 20-day realised vol is above 1.2%. The rolling-vol rule needs many days of data to move, so it lags every switch and keeps flagging stress for weeks after it ends. In the simulations behind this post, the filter classified 92% of days correctly against 79% for rolling vol. Make the regimes less persistent (lower the stay probabilities) and both get worse, because short regimes are hard to tell apart from noise.

import numpy as np
from scipy.stats import norm

def hamilton_filter(r, sigma=(0.007, 0.02), p00=0.98, p11=0.95):
    """P(stressed regime | returns up to t) for a two-state Gaussian Markov-switching model."""
    P = np.array([[p00, 1 - p00], [1 - p11, p11]])
    pi = np.array([1 - p11, 1 - p00]) / (2 - p00 - p11)          # start from the stationary distribution
    out, loglik = np.empty(len(r)), 0.0
    for t, x in enumerate(r):
        prior = pi @ P if t else pi                               # predict
        joint = prior * norm.pdf(x, 0, sigma)                     # update
        loglik += np.log(joint.sum())
        pi = joint / joint.sum()
        out[t] = pi[1]
    return out, loglik                                            # maximise loglik over the parameters to fit them
In practice

Fitting and using it

The parameters (vols, transition probabilities, possibly regime means) are usually unknown. The filter also produces the likelihood of the data as a by-product, the product of the normalising constants, so you can fit the model by maximum likelihood, or by the EM algorithm (Baum–Welch). The statsmodels package has MarkovRegression for this.

Uses include scaling risk down when the stressed probability is high, switching between strategy parameters by regime, and stress-testing with regime-conditional covariance matrices.

Where people slip in interviews

  • Using smoothed probabilities in a backtest. The smoother uses future returns to revise past regimes. It’s great for describing history and is look-ahead bias in a trading rule. Use the filtered probability.
  • Forgetting the predict step. Without it the filter ignores persistence and jumps around with every day’s return.
  • Label switching. When fitting, nothing in the likelihood says which state is “calm”. Fix a convention, e.g. state 0 has the lower vol.
  • Too many regimes. Every extra state adds parameters and overfits quickly. Two or three are usually plenty.
Practice

Try these before you open the answer

Warm-upp₀₀ = 0.98 and p₁₁ = 0.95. How long does each regime last on average, and what fraction of days are stressed?
Show answer

Calm: 1/0.02 = 50 days. Stressed: 1/0.05 = 20 days. Stressed fraction: 0.02/(0.02 + 0.05) ≈ 28.6%, which is also 20/(50 + 20).

PredictYesterday P(stressed) = 0.1. With the transitions above, what's today's prior P(stressed) before seeing the return?
Show answer
0.1×0.95+0.9×0.02=0.095+0.018=0.1130.1 \times 0.95 + 0.9 \times 0.02 = 0.095 + 0.018 = 0.113
UpdatePrior P(stressed) = 0.3. Today's return is −3%. With calm σ = 0.7% and stressed σ = 2%, what's the posterior?
Show answer

Likelihoods: calm φ(4.29)/0.7≈5.9×10−5\varphi(4.29)/0.7 \approx 5.9 \times 10^{-5}, stressed φ(1.5)/2≈0.065\varphi(1.5)/2 \approx 0.065. Posterior =0.3×0.0650.3×0.065+0.7×5.9×10−5≈0.998= \frac{0.3 \times 0.065}{0.3 \times 0.065 + 0.7 \times 5.9 \times 10^{-5}} \approx 0.998.

VolWhat's the unconditional daily volatility of these returns? Annualised?
Show answer

57(0.007)2+27(0.02)2≈1.22%\sqrt{\tfrac57(0.007)^2 + \tfrac27(0.02)^2} \approx 1.22\% a day, about 19.4% a year.

Quiet dayPrior P(stressed) = 0.5. Today's return is exactly 0. What's the posterior?
Show answer

The likelihood at 0 is φ(0)/σ\varphi(0)/\sigma, so the ratio stressed : calm is (1/2):(1/0.7)=0.35(1/2) : (1/0.7) = 0.35. Posterior =0.35/(1+0.35)≈0.26= 0.35/(1 + 0.35) \approx 0.26. A flat day is evidence for calm, but only moderate evidence.

StretchWhy does the filter usually detect a switch into stress faster than a switch out of it?
Show answer

The likelihood ratio of a big move is extreme (a 3% day is thousands of times likelier in the stressed state), so one or two big days are decisive. Small moves are only mildly likelier in the calm state (ratio at most 2/0.7 ≈ 2.9 per day), so the evidence for calm builds up slowly, over several quiet days.

The accuracy figures come from simulated regime-switching series; the worked numbers were computed with scipy. The figure simulates and filters 500 days in your browser.