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.
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:
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.
Predict, then update
You want : 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 .
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.
Daily returns (calm σ = 0.7%, stressed σ = 2%), true stressed periods shaded
Estimated chance we're in the stressed regime
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 themFitting 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.
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
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 , stressed . Posterior .
VolWhat's the unconditional daily volatility of these returns? Annualised?Show answer
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 , so the ratio stressed : calm is . Posterior . 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.