Skip to content
LeetQuant
E07 Advanced Time Series

E07 · Advanced Time Series · Lesson 4 of 4

Regime-Switching Models

The Hamilton filter for a two-state switching-mean model with a worked numeric step and its likelihood, what regime switching implies for durations and autocorrelation, estimation in statsmodels and its caveats, and a time-varying hedge ratio estimated with a Kalman filter.

18 min

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 St∈{1,2}S_t \in \{1, 2\} follow a Markov chain with transition matrix PP, pij=P(St=j∣St−1=i)p_{ij} = P(S_t = j \mid S_{t-1} = i), and

yt=μSt+σεt,εt∼N(0,1).y_t = \mu_{S_t} + \sigma\varepsilon_t, \qquad \varepsilon_t \sim N(0, 1) .

Write ξt∣t\xi_{t|t} for the vector of filtered probabilities P(St=j∣y1,…,yt)P(S_t = j \mid y_1, \dots, y_t) and ηt\eta_t for the vector of state densities φ(yt;μj,σ2)\varphi(y_t; \mu_j, \sigma^2). The Hamilton filter is the discrete-state analogue of the Kalman filter:

predict:ξt∣t−1=P′ ξt−1∣t−1,likelihood:f(yt∣Ft−1)=1′(ξt∣t−1⊙ηt),update:ξt∣t=ξt∣t−1⊙ηtf(yt∣Ft−1).\begin{aligned} \text{predict:}\quad & \xi_{t|t-1} = P'\,\xi_{t-1|t-1}, \\ \text{likelihood:}\quad & f(y_t \mid \mathcal F_{t-1}) = \mathbf 1'(\xi_{t|t-1} \odot \eta_t), \\ \text{update:}\quad & \xi_{t|t} = \frac{\xi_{t|t-1} \odot \eta_t}{f(y_t \mid \mathcal F_{t-1})} . \end{aligned}

The log-likelihood is ∑tlog⁡f(yt∣Ft−1)\sum_t \log f(y_t \mid \mathcal F_{t-1}), 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 π\pi be the stationary distribution, Δμ=μ1−μ2\Delta\mu = \mu_1 - \mu_2 and λ=p11+p22−1\lambda = p_{11} + p_{22} - 1 (the second eigenvalue of PP).

  • Durations. A stay in regime ii is geometric with mean 1/(1−pii)1/(1 - p_{ii}).
  • Moments. Ey=π1μ1+π2μ2\mathbb E y = \pi_1\mu_1 + \pi_2\mu_2 and Var⁡y=σ2+π1π2 Δμ2\operatorname{Var} y = \sigma^2 + \pi_1\pi_2\,\Delta\mu^2.
  • Autocorrelation. The regime indicator is an AR(1) with coefficient λ\lambda, so Cov⁡(yt,yt+k)=π1π2 Δμ2 λk\operatorname{Cov}(y_t, y_{t+k}) = \pi_1\pi_2\,\Delta\mu^2\,\lambda^k for k≥1k \ge 1. A switching mean makes returns positively autocorrelated (when λ>0\lambda > 0) 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 N(1,42)N(1, 4^2) in a bull regime and N(−2,42)N(-2, 4^2) in a bear regime, with pbull,bull=0.95p_{\text{bull,bull}} = 0.95 and pbear,bear=0.80p_{\text{bear,bear}} = 0.80.

(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 0.100.10. This month's return is −6%-6\%. Find the predicted and filtered probabilities of bear, and this month's likelihood contribution.

Show solution

(a) Durations 1/0.05=201/0.05 = 20 months (bull) and 1/0.20=51/0.20 = 5 months (bear). Stationary πbear=0.05/(0.05+0.20)=0.2\pi_{\text{bear}} = 0.05/(0.05 + 0.20) = 0.2. Mean 0.8(1)+0.2(−2)=0.4%0.8(1) + 0.2(-2) = 0.4\%. Variance 16+0.8×0.2×32=17.4416 + 0.8 \times 0.2 \times 3^2 = 17.44. With λ=0.95+0.80−1=0.75\lambda = 0.95 + 0.80 - 1 = 0.75, ρ1=1.44×0.75/17.44≈0.062\rho_1 = 1.44 \times 0.75/17.44 \approx 0.062. Persistent regimes with a three-point gap in the mean produce only 6% autocorrelation.

(b) Predict: P(bear)=0.10×0.80+0.90×0.05=0.125P(\text{bear}) = 0.10 \times 0.80 + 0.90 \times 0.05 = 0.125.

Densities: φ(−6;1,16)=0.02157\varphi(-6; 1, 16) = 0.02157 and φ(−6;−2,16)=0.06049\varphi(-6; -2, 16) = 0.06049. The likelihood ratio is

φ(−6;−2,16)φ(−6;1,16)=exp⁡ ⁣((−6−1)2−(−6+2)22×16)=e33/32≈2.80.\frac{\varphi(-6; -2, 16)}{\varphi(-6; 1, 16)} = \exp\!\Big(\frac{(-6 - 1)^2 - (-6 + 2)^2}{2 \times 16}\Big) = e^{33/32} \approx 2.80 .

Update: posterior odds =(0.125/0.875)×2.80=0.401= (0.125/0.875) \times 2.80 = 0.401, so P(bear∣y)=0.401/1.401≈0.286P(\text{bear} \mid y) = 0.401/1.401 \approx 0.286.

Likelihood contribution: f=0.875×0.02157+0.125×0.06049=0.02643f = 0.875 \times 0.02157 + 0.125 \times 0.06049 = 0.02643, so this month adds log⁡0.02643≈−3.63\log 0.02643 \approx -3.63 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 −6%-6\% month, a 1.75-sigma event, only moves bear from 12.5% to 29%. With equal variances the likelihood ratio grows only linearly in yy 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 −2.84-2.84), because the likelihood is identical under relabelling. Always identify regimes by their estimated parameters, and impose an ordering (e.g. μ1>μ2\mu_1 > \mu_2) when comparing fits across samples or bootstrap draws.
  • The bear mean is imprecise: −2.84-2.84 with standard error 0.820.82, against a true −2-2. The bull mean (1.10±0.311.10 \pm 0.31) is better because there are nearly four times as many bull months (471 against 129).
  • Durations (6.26.2 and 23.723.7 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 σj\sigma_j, setting μ2=yt\mu_2 = y_t for one observation and σ2→0\sigma_2 \to 0 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 χ2\chi^2 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: yt=at+btxt+εty_t = a_t + b_t x_t + \varepsilon_t with (at,bt)(a_t, b_t) 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 qβ=4×10−4q_\beta = 4 \times 10^{-4}, the true value (0.0220.02^2). 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 ∣xt∣|x_t| moves the beta estimate more, because Zt=(1,xt)Z_t = (1, x_t) enters the gain.

Practical points: estimate rr jointly with qq (fixed here only for brevity); setting the intercept's state noise to zero keeps the intercept constant; qβ=0q_\beta = 0 reproduces expanding-window OLS; and a hedge ratio that moves every day creates rebalancing cost, so a slightly smaller qq than the likelihood optimum is often better after costs. For price-level pairs the same filter tracks the cointegrating coefficient, and the innovation vtv_t with its variance FtF_t gives a natural z-score of the spread.

Knowledge check

A two-state chain has p11=0.9p_{11} = 0.9 and p22=0.7p_{22} = 0.7. 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, p11=0.95p_{11} = 0.95 and p22=0.80p_{22} = 0.80. 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 P′P', multiplies by the state densities and renormalises; the normalising constant is the likelihood contribution.
  • Durations 1/(1−pii)1/(1 - p_{ii}); variance σ2+π1π2Δμ2\sigma^2 + \pi_1\pi_2\Delta\mu^2; switching means imply autocorrelation decaying like (p11+p22−1)k(p_{11} + p_{22} - 1)^k.
  • 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).