Objective
The regime-changes lesson introduced Markov switching through a calm–stress volatility model and ran its filter. This lesson goes underneath: the Hamilton filter as a likelihood machine, why regimes in the mean are much harder to detect than regimes in volatility, what a switching model implies for observable statistics, and what goes wrong in estimation. It closes with the other way to handle drifting parameters: let them move continuously and track them with a Kalman filter.
The model and the Hamilton filter
Let follow a Markov chain with transition matrix , , and
Write for the vector of filtered probabilities and for the vector of state densities . The Hamilton filter is the discrete-state analogue of the Kalman filter:
The log-likelihood is , a sum of logs of mixture densities, maximised numerically (or by EM). Smoothed probabilities come from a backward pass (Kim's smoother), and, as before, they use the future.
What the model implies
Let be the stationary distribution, and (the second eigenvalue of ).
- Durations. A stay in regime is geometric with mean .
- Moments. and .
- Autocorrelation. The regime indicator is an AR(1) with coefficient , so for . A switching mean makes returns positively autocorrelated (when ) and the ACF decays geometrically, like an ARMA(1,1). If the measured autocorrelation of returns is near zero, any switching in the mean must be small or short-lived.
That last point is why mean regimes are hard: the regime only shows up in the data through a small shift relative to large noise.
Worked example
one step of the filter with switching means
Monthly returns (in %) are in a bull regime and in a bear regime, with and .
(a) Find the expected durations, the stationary probabilities, the unconditional mean and variance, and the lag-1 autocorrelation. (b) Last month's filtered probability of bear was . This month's return is . Find the predicted and filtered probabilities of bear, and this month's likelihood contribution.
Show solutionHide solution
(a) Durations months (bull) and months (bear). Stationary . Mean . Variance . With , . Persistent regimes with a three-point gap in the mean produce only 6% autocorrelation.
(b) Predict: .
Densities: and . The likelihood ratio is
Update: posterior odds , so .
Likelihood contribution: , so this month adds to the log-likelihood.
Compare the volatility model in the regime-changes lesson, where one large day moved the stress probability from 20% to 86%. Here a month, a 1.75-sigma event, only moves bear from 12.5% to 29%. With equal variances the likelihood ratio grows only linearly in inside the exponent, so the filter needs several bad months in a row to become confident. This is why mean-switching models are slow to call a bear market, and why their regime probabilities are usually a lagging description, not a timing signal.
Estimating it
import numpy as np
import pandas as pd
import statsmodels.api as sm
# Simulate monthly returns (%) from a two-state switching-mean model
rng = np.random.default_rng(7)
P = np.array([[0.95, 0.05], # bull -> bull, bull -> bear
[0.20, 0.80]]) # bear -> bull, bear -> bear
mu, sigma, n = np.array([1.0, -2.0]), 4.0, 600
s = np.zeros(n, dtype=int)
for t in range(1, n):
s[t] = rng.choice(2, p=P[s[t - 1]])
r = mu[s] + rng.normal(0, sigma, n)
mod = sm.tsa.MarkovRegression(pd.Series(r), k_regimes=2, trend="c", switching_variance=False)
res = mod.fit(search_reps=20, disp=False)
print(pd.DataFrame({"estimate": res.params, "s.e.": res.bse}).round(3))
print("expected durations:", np.round(res.expected_durations, 1))
print("months in bear (true):", (s == 1).sum())
Output:
estimate s.e.
p[0->0] 0.838 0.071
p[1->0] 0.042 0.028
const[0] -2.843 0.820
const[1] 1.102 0.308
sigma2 14.525 1.068
expected durations: [ 6.2 23.7]
months in bear (true): 129
Fifty years of monthly data from the true model, and:
- The labels came out swapped. Regime 0 is the bear state here (mean ), because the likelihood is identical under relabelling. Always identify regimes by their estimated parameters, and impose an ordering (e.g. ) when comparing fits across samples or bootstrap draws.
- The bear mean is imprecise: with standard error , against a true . The bull mean () is better because there are nearly four times as many bull months (471 against 129).
- Durations ( and months against 5 and 20) rest on how many regime changes the sample contains, 20 bear episodes here. On real data with three or four recessions, transition probabilities are barely estimated.
Estimation caveats
- Multiple local maxima. The mixture likelihood is multimodal; a single start can converge to a poor solution (e.g. one regime capturing a handful of outliers). Use many random starts (
search_reps) or EM followed by numerical optimisation, and compare log-likelihoods. - Unbounded likelihood with switching variances. If each regime has its own , setting for one observation and sends the likelihood to infinity. Software stops at a local maximum before this, but degenerate fits with a tiny-variance regime are a warning sign; bound the variances or use a prior.
- Testing the number of regimes is non-standard. Under one regime, the transition probabilities are unidentified (nuisance parameters present only under the alternative), so the likelihood-ratio statistic does not have a distribution. Use simulated or bootstrap critical values, or information criteria with caution.
- Real time. Filtered probabilities with parameters estimated on the full sample still contain look-ahead. Re-estimate on an expanding window for any backtest, and expect the regimes to be revised as data arrive.
- Regimes versus continuous drift. If parameters drift slowly rather than jump between a few recurring values, a two-state model forces a false discreteness. The alternative is to let the parameter follow a random walk, which is the next application.
Application: a time-varying hedge ratio
Pairs and hedging models need a beta that changes. Put it in state-space form, as in the first lesson: with random walks, and filter. The variance of the beta's state noise replaces the rolling window length, and the likelihood chooses it.
import numpy as np
def kalman_regression(y, x, q, r):
"""Filter y_t = a_t + b_t x_t + eps_t with (a_t, b_t) random walks.
Returns the filtered states (n x 2) and the log-likelihood."""
theta, P = np.zeros(2), np.eye(2) * 1e6 # vague prior
Q = np.diag(q)
out, ll = np.zeros((len(y), 2)), 0.0
for t in range(len(y)):
P = P + Q # predict (T = I)
z = np.array([1.0, x[t]]) # observation row Z_t
v = y[t] - z @ theta # innovation
f = z @ P @ z + r # its variance
k = P @ z / f # Kalman gain (2-vector)
theta = theta + k * v # update
P = P - np.outer(k, z @ P)
if t >= 2: # skip the diffuse start
ll += -0.5 * (np.log(2 * np.pi * f) + v**2 / f)
out[t] = theta
return out, ll
# Simulated daily returns (%) with a hedge ratio that wanders
rng = np.random.default_rng(3)
n = 1000
x = rng.normal(0, 1.0, n) # hedge instrument
beta = 1.0 + np.cumsum(rng.normal(0, 0.02, n)) # true beta: random walk
y = 0.02 + beta * x + rng.normal(0, 0.5, n) # asset to hedge
# state noise for beta by maximum likelihood over a grid (r fixed for brevity)
grid = [1e-5, 1e-4, 4e-4, 1e-3, 1e-2]
lls = [kalman_regression(y, x, [0.0, qb], 0.25)[1] for qb in grid]
for qb, ll in zip(grid, lls):
print(f"q_beta = {qb:.0e}: log-lik = {ll:.1f}")
best = grid[int(np.argmax(lls))]
est = kalman_regression(y, x, [0.0, best], 0.25)[0][:, 1]
def rolling_beta(w):
b = np.full(n, np.nan)
for t in range(w - 1, n):
b[t] = np.polyfit(x[t - w + 1:t + 1], y[t - w + 1:t + 1], 1)[0]
return b
ok = np.arange(n) >= 120 # compare on the same days
rmse = lambda b: np.sqrt(np.mean((b[ok] - beta[ok]) ** 2))
print(f"Kalman (q_beta = {best:.0e}) RMSE: {rmse(est):.3f}")
for w in [20, 60, 120]:
print(f"rolling {w:3d}-day OLS RMSE: {rmse(rolling_beta(w)):.3f}")
Output:
q_beta = 1e-05: log-lik = -822.3
q_beta = 1e-04: log-lik = -783.3
q_beta = 4e-04: log-lik = -779.0
q_beta = 1e-03: log-lik = -781.2
q_beta = 1e-02: log-lik = -807.4
Kalman (q_beta = 4e-04) RMSE: 0.096
rolling 20-day OLS RMSE: 0.126
rolling 60-day OLS RMSE: 0.108
rolling 120-day OLS RMSE: 0.139
The likelihood picks , the true value (). The filter tracks beta better than each of the rolling windows tried, and the rolling results show the bias–variance trade-off directly: 20 days is noisy, 120 days lags, 60 days happens to be a good compromise, which you would only know by trying (and overfitting) windows. The Kalman filter also weights recent observations by their information: a day with a large moves the beta estimate more, because enters the gain.
Practical points: estimate jointly with (fixed here only for brevity); setting the intercept's state noise to zero keeps the intercept constant; reproduces expanding-window OLS; and a hedge ratio that moves every day creates rebalancing cost, so a slightly smaller than the likelihood optimum is often better after costs. For price-level pairs the same filter tracks the cointegrating coefficient, and the innovation with its variance gives a natural z-score of the spread.
Knowledge check
A two-state chain has and . What are the stationary probability of state 2 and the expected length of a stay in state 2?
Knowledge check
Returns follow a two-state switching-mean model with constant variance, and . At what rate does the autocorrelation of returns decay with the lag?
Knowledge check
You fit a two-regime model with separate means and variances to daily returns. One regime has a variance 100 times smaller than the other and is occupied on only four days. What is the most likely explanation?
Knowledge check
In a Kalman-filter hedge ratio y_t = a_t + b_t x_t + e_t, you set the state noise of b_t to zero and the intercept's state noise to zero. What does the filter compute?
Key takeaways
- The Hamilton filter predicts with , multiplies by the state densities and renormalises; the normalising constant is the likelihood contribution.
- Durations ; variance ; switching means imply autocorrelation decaying like .
- Mean regimes are hard to detect: with equal variances one bad period moves the filter only modestly, so regime calls lag.
- Estimation: label switching, local maxima (use many starts), unbounded likelihoods with switching variances, non-standard tests for the number of regimes, few transitions in real samples, and look-ahead from full-sample parameters.
- For continuously drifting parameters, a Kalman filter with random-walk coefficients beats rolling windows and chooses the adaptation speed by maximum likelihood.
Practice problems
Finished reading?
Answer the 4 knowledge checks to complete this lesson (0 done).