Regime changes: Markov-switching models
Many series alternate between regimes with different dynamics. This lesson formulates Hamilton's hidden-Markov autoregression, derives the Hamilton filter and Kim smoother, estimates switching models by maximum likelihood and EM, and examines duration, identifiability and threshold models.
After this lesson you can
- Formulate and simulate an autoregression with regime-dependent mean and variance.
- Implement the Hamilton filter and Kim smoother in log space.
- Estimate by maximum likelihood and EM with multiple initializations and compare with statsmodels.
- Interpret filtered and smoothed regime probabilities without confusing them in real-time use.
- Compare Markov switching with threshold models and change-point detection according to the problem.
Before you start
- 26Transition matrixStationary distributionAutoregressive modelNonlinear and threshold autoregressionsGARCH model
- 14Forward algorithm (filtering)Forward-backward algorithm (smoothing)Scaling and log-space recursionsBaum-Welch algorithmHidden semi-Markov model
- 12Expectation-maximization algorithmEM monotonicity and convergence
The unobserved state
An economy can alternate between growth and contraction; a market can move from calm days to turbulent periods. We do not directly observe a regime label at every date. A regime-switching model maintains a probability distribution over that state and updates it as data arrive.
In the simulation, the true regime’s color is visible only because we know the generating mechanism. The filtered probability uses information available through that date; the smoothed probability also uses later observations. A smoothed curve can locate an episode better retrospectively, but is not a signal available at the time.
Autoregressions with hidden state
A Markov-switching model assumes a chain with , so each row of sums to one. A useful first-order AR model is
Conditional on and , its density is normal with mean . The coefficient can also be allowed to switch, ; the density still depends on the current state and observed lag. The lab fixes a common to simplify the comparison between EM and maximum likelihood. This family differs from Hamilton’s centered model, where lags are centered by the means of their own regimes:
Here the density depends on . To calculate it exactly, maintain joint probabilities of relevant histories or use an equivalent implementation: a recursion of only states that ignores past regimes is not generally the filter for that model. Parameters, including stability, must be interpreted according to the specific model.
Hamilton filter
For the first specification, let and . The Hamilton filter applies prediction and Bayes’ rule:
The denominator is the predictive density of the observation. Summing its logarithms gives conditional log-likelihood, given an initial distribution and observed lags. To avoid underflow, work with logarithms and logsumexp, normalizing at each step. The filter is the forward algorithm of an HMM when the emission depends on the current state and already observed lags.
Smoothing is not forecasting
In the same family, the Kim smoother can be calculated backwards using
The formula requires positive predictive probabilities in the terms used. It is equivalent to the backward step in this specification; for Hamilton’s centered AR, apply the recursion to expanded states or maintain appropriate joint probabilities. A smoothed regime can appear clearer because it uses later events, not because it was known in real time. Estimating parameters on the full sample also leaks information, even when filtered probabilities are used.
Persistence and duration
If state is entered and , its duration has geometric distribution , for , and mean . If the state is absorbing and its expected duration is infinite. These durations have the memoryless property; a semi-Markov model can allow exit probability to depend on episode age.
For two states with positive off-diagonal transitions, the stationary distribution is
The formula also has an interpretation in some absorbing cases, but if both states are absorbing there is no unique stationary distribution. Episodes not yet finished at the end of a sample are censored; treating them as complete durations biases the comparison.
Estimation and identification
Maximum-likelihood estimation maximizes the filter normalizers. EM alternates smoothed and transition probabilities with parameter updates. The likelihood of an unconstrained Gaussian mixture can grow as a variance collapses onto an observation: impose reasonable constraints, watch for nearly empty regimes and check convergence. Different initializations can reach different solutions; the best found does not certify a global maximum.
Labels are interchangeable: consistently permuting means, variances, initial distribution and transition rows and columns produces the same distribution. Ordering regimes by mean or volatility makes runs easier to compare, but this convention does not prove that labels correspond to true economic categories. The graph shows EM attempts on the same simulated sample.
The likelihood ratio for choosing the number of regimes does not automatically follow a standard : under the null some parameters of the additional regime are unidentified and boundaries can arise. Check stability across subsamples and initializations and consider methods designed for that problem. A SETAR changes rule at an observable threshold; Markov switching uses a recurrent latent state. A change detector can look for breaks without requiring recurrence. Time-varying transition matrices introduce regressors and their own uncertainty.
A regime-switching VAR has more parameters; in a regime-switching GARCH, variance can depend on the entire previous hidden path. A filter retaining only the current state may not be exact: specific methods or declared approximations are needed.
Lab: filter and smoother in log space
We simulate the regime-intercept AR, with different variances and known parameters. We condition on and fix an initial distribution over . The implementation keeps each regime’s densities in logarithms and normalizes at each date.
import numpy as np
from scipy.special import logsumexp
from scipy.optimize import minimize
from itertools import product
from statsmodels.tsa.regime_switching.markov_regression import MarkovRegression
from statsmodels.tsa.regime_switching.markov_autoregression import MarkovAutoregression
def simular_ms(n, P, mu, sigma, phi, pi, rng):
estados = np.empty(n,dtype=int)
y = np.zeros(n+1)
estados[0] = rng.choice(2,p=pi)
for t in range(n):
if t:
estados[t] = rng.choice(2,p=P[estados[t-1]])
s = estados[t]
y[t+1] = mu[s]+phi*y[t]+sigma[s]*rng.normal()
return y,estados
def densidades(y,mu,sigma,phi):
resid = y[1:,None]-phi*y[:-1,None]-np.asarray(mu)[None,:]
return -.5*np.log(2*np.pi)-np.log(sigma)[None,:]-.5*(resid/np.asarray(sigma)[None,:])**2
def forward(log_emision,P,pi):
logP, logpi = np.log(P),np.log(pi)
n,k = log_emision.shape
if k != 2:
raise ValueError("esta implementación usa dos regímenes")
filtradas, predichas = np.empty((n,k)),np.empty((n,k))
log_filtradas = np.empty((n,k))
log_f = None
ll = 0.
for t in range(n):
log_a = logpi if t == 0 else np.logaddexp(log_f[0]+logP[0],log_f[1]+logP[1])
predichas[t] = np.exp(log_a)
conjunto = log_a+log_emision[t]
normalizador = np.logaddexp(conjunto[0],conjunto[1])
log_f = conjunto-normalizador
log_filtradas[t] = log_f
filtradas[t] = np.exp(log_f)
ll += normalizador
return filtradas,predichas,ll,log_filtradas
P = np.array([[.94,.06],[.12,.88]])
pi = np.array([.5,.5])
mu = np.array([-.4,.6])
sigma = np.array([.5,1.2])
phi = .4
y,estado = simular_ms(350,P,mu,sigma,phi,pi,np.random.default_rng(2620))
emision = densidades(y,mu,sigma,phi)
filtradas,predichas,ll,log_filtradas = forward(emision,P,pi)
print("log-verosimilitud y suma de probabilidades:",
ll,np.max(abs(filtradas.sum(axis=1)-1)))
print("primeras probabilidades filtradas:",filtradas[:3])The backward step calculates and joint probabilities of two consecutive states. Message normalization does not alter these probabilities. Our is the distribution of the first observed state. In this specification and version of statsmodels, the known prior is propagated twice before the first density: to compare them we solve , verify that it is a valid distribution and check the first prediction. Its transition matrix is presented by columns. The convention can depend on implementation.
def backward(log_emision,P,log_filtradas):
n,k = log_emision.shape
logP = np.log(P)
atras = np.zeros((n,k))
for t in range(n-2,-1,-1):
términos = logP+log_emision[t+1][None,:]+atras[t+1][None,:]
atras[t] = np.logaddexp(términos[:,0],términos[:,1])
atras[t] -= np.logaddexp(atras[t,0],atras[t,1])
log_s = log_filtradas+atras
log_s -= np.logaddexp(log_s[:,0],log_s[:,1])[:,None]
suaves = np.exp(log_s)
lp = (log_filtradas[:-1,:,None]+logP[None,:,:]+
log_emision[1:,None,:]+atras[1:,None,:])
normalizador = np.logaddexp.reduce(lp.reshape(n-1,k*k),axis=1)
pares = np.exp(lp-normalizador[:,None,None])
return suaves,pares
suaves,pares = backward(emision,P,log_filtradas)
modelo = MarkovRegression(y[1:],k_regimes=2,trend="c",exog=y[:-1,None],
switching_exog=False,switching_variance=True)
pi_previa = np.linalg.solve((P@P).T,pi)
if np.any(pi_previa < 0):
raise ValueError("prior anterior no válido para esta comparación")
modelo.initialize_known(pi_previa)
param_ref = [P[0,0],P[1,0],mu[0],mu[1],phi,sigma[0]**2,sigma[1]**2]
ref = modelo.smooth(param_ref)
print("diferencia de log-verosimilitud:",ll-ref.llf)
print("primer prior propio y de statsmodels:",predichas[0],ref.predicted_marginal_probabilities[0])
print("error máximo filtrado:",np.max(abs(filtradas-ref.filtered_marginal_probabilities)))
print("error máximo suavizado:",np.max(abs(suaves-ref.smoothed_marginal_probabilities)))
print("última filtrada y suavizada:",filtradas[-1],suaves[-1])
extrema = densidades(np.array([0.,1000.,-1000.,0.]),mu,sigma,phi)
ext_fil,_,ext_ll,ext_log = forward(extrema,P,pi)
ext_suaves,_ = backward(extrema,P,ext_log)
print("caso extremo: log L finita y suavizadas normalizadas:",
np.isfinite(ext_ll),np.allclose(ext_suaves.sum(axis=1),1))Lab: EM and maximum likelihood
To show a closed-form M step, we hold fixed and estimate intercepts, variances and transitions. Initial prior is also held fixed: if it is required to be stationary and depend on , that term must be included in M-step optimization. Standard deviations are between 0.1 and 5 and stay probabilities between 0.01 and 0.99; these constraints prevent degenerate solutions in this experiment.
def em(y,phi,pi,P0,mu0,sigma0,pasos=60):
P,mu,sigma = P0.copy(),mu0.copy(),sigma0.copy()
historia = []
resid = y[1:]-phi*y[:-1]
for _ in range(pasos):
logg = densidades(y,mu,sigma,phi)
fil,_,ll,logfil = forward(logg,P,pi)
historia.append(ll)
gam,xi = backward(logg,P,logfil)
pesos = gam.sum(axis=0)
if np.any(pesos < 1e-10):
raise ValueError("régimen sin ocupación")
mu = (gam*resid[:,None]).sum(axis=0)/pesos
var = (gam*(resid[:,None]-mu)**2).sum(axis=0)/pesos
sigma = np.clip(np.sqrt(var),.1,5.)
cuenta = xi.sum(axis=0)
p00 = np.clip(cuenta[0,0]/cuenta[0].sum(),.01,.99)
p11 = np.clip(cuenta[1,1]/cuenta[1].sum(),.01,.99)
P = np.array([[p00,1-p00],[1-p11,p11]])
ll = forward(densidades(y,mu,sigma,phi),P,pi)[2]
historia.append(ll)
return P,mu,sigma,np.array(historia)
inicios = [
(np.array([[.8,.2],[.2,.8]]),np.array([-1.,1.]),np.array([.8,1.5])),
(np.array([[.8,.2],[.2,.8]]),np.array([1.,-1.]),np.array([1.5,.8])),
(np.array([[.6,.4],[.4,.6]]),np.array([-.1,.1]),np.array([1.,1.])),
]
ensayos = [em(y,phi,pi,*ini) for ini in inicios]
for i,(Pt,mt,st,hist) in enumerate(ensayos):
print("inicio, log L final, mínima mejora, medias:",i,hist[-1],
np.diff(hist).min(),mt)
mejor = max(ensayos,key=lambda item:item[3][-1])We optimize the same family with the same and initial prior. Stay probabilities are between 0.01 and 0.99 and standard deviations between 0.1 and 5. We compare with the best EM attempt, not a certified global maximum. The result can change with the seed or constraints.
def empaquetar(P,mu,sigma):
return np.r_[P[0,0],P[1,1],mu,np.log(sigma)]
def desempaquetar(p):
p00,p11 = p[:2]
return np.array([[p00,1-p00],[1-p11,p11]]),p[2:4],np.exp(p[4:6])
def nll(p,y,phi,pi):
P,mu,sigma = desempaquetar(p)
return -forward(densidades(y,mu,sigma,phi),P,pi)[2]
arranque = empaquetar(*mejor[:3])
limites = [(.01,.99),(.01,.99),(None,None),(None,None),
(np.log(.1),np.log(5)),(np.log(.1),np.log(5))]
ajuste = minimize(nll,arranque,args=(y,phi,pi),method="L-BFGS-B",
bounds=limites,options={"maxiter":200})
print("éxito optimización, log L EM y directa:",ajuste.success,mejor[3][-1],-ajuste.fun)
print("parámetros directos P, medias y sigmas:",desempaquetar(ajuste.x))Lab: Hamilton’s centered AR
The following series reproduces the 135 quarterly real GNP growth rates used in the statsmodels MarkovAutoregression test, from 1951-Q2 to 1984-Q4. It is included for offline use. Conditioning on the first four lags leaves 131 observations. The statsmodels documentation explains the replication of Hamilton’s model.
In the centered AR(4), each emission depends on five consecutive states. We enumerate the histories, retaining their probabilities in logarithms. When conditioning on the first four observations we conventionally assign a stationary prior to the state history; we do not claim that it is the posterior of those histories conditional on those observations. This implementation is for two regimes with positive transition matrix and common variance.
rgnp = np.array([2.59316421, 2.20217133, 0.45827562, 0.9687438, -0.24130757, 0.89647478, 2.05393219, 1.73353648, 0.93871289, -0.46477833, -0.80983406, -1.39763689, -0.39886093, 1.1918416, 1.45620048, 2.11808228, 1.08957863, 1.32390273, 0.87296367, -0.19773273, 0.45420215, 0.07221876, 1.1030364, 0.82097489, -0.05795795, 0.58447772, -1.56192672, -2.05041027, 0.53637183, 2.33676839, 2.34014559, 1.2339263, 1.8869648, -0.45920792, 0.84940469, 1.70139849, -0.28756312, 0.09594627, -0.86080289, 1.03447127, 1.23685944, 1.42004502, 2.22410631, 1.30210173, 1.03517699, 0.9253425, -0.16559951, 1.3444382, 1.37500131, 1.73222184, 0.71605635, 2.21032143, 0.85333031, 1.00238776, 0.42725441, 2.14368343, 1.43789184, 1.57959926, 2.27469826, 1.95962656, 0.25992399, 1.01946914, 0.49016398, 0.5636338, 0.5959546, 1.43082857, 0.56230122, 1.15388393, 1.68722844, 0.77438205, -0.09647045, 1.39600146, 0.13646798, 0.55223715, -0.39944872, -0.61671102, -0.08722561, 1.2101835, -0.90729755, 2.64916158, -0.0080694, 0.51111895, -0.00401437, 2.16821432, 1.92586732, 1.03504717, 1.85897219, 2.32004929, 0.25570789, -0.09855274, 0.89073682, -0.55896485, 0.28350255, -1.31155407, -0.88278776, -1.97454941, 1.01275265, 1.68264723, 1.38271284, 1.86073637, 0.4447377, 0.41449001, 0.99202275, 1.36283576, 1.59970522, 1.98845816, -0.25684232, 0.87786949, 3.1095655, 0.85324478, 1.23337317, 0.00314302, -0.09433369, 0.89883322, -0.19036628, 0.99772376, -2.39120054, 0.06649673, 1.26136017, 1.91637838, -0.3348029, 0.44207108, -1.40664911, -1.52129889, 0.29919869, -0.80197448, 0.15204792, 0.98585027, 2.13034606, 1.34397924, 1.61550522, 2.70930099, 1.24461412, 0.50835466, 0.14802167],dtype=float)
def hamilton_centrado(y,mu,phi,sigma,P):
p = len(phi)
caminos = np.array(list(product(range(2),repeat=p+1)),dtype=int)
mapa = {tuple(c):i for i,c in enumerate(caminos)}
pi0 = P[1,0]/(P[0,1]+P[1,0])
pi = np.array([pi0,1-pi0])
logP = np.log(P)
inicial = np.log(pi[caminos[:,0]])
for j in range(p):
inicial += logP[caminos[:,j],caminos[:,j+1]]
previo0 = np.array([mapa[(0,)+tuple(c[:-1])] for c in caminos])
previo1 = np.array([mapa[(1,)+tuple(c[:-1])] for c in caminos])
actual = caminos[:,-1]
ultima = caminos[:,-2]
logf, ll = None, 0.
marginales = []
for t in range(p,len(y)):
if t == p:
logpred = inicial
else:
logpred = np.logaddexp(logf[previo0]+logP[ultima,actual],
logf[previo1]+logP[ultima,actual])
media = mu[actual].copy()
for lag in range(1,p+1):
media += phi[lag-1]*(y[t-lag]-mu[caminos[:,-1-lag]])
logg = -.5*np.log(2*np.pi*sigma**2)-.5*((y[t]-media)/sigma)**2
escala = logsumexp(logpred+logg)
logf = logpred+logg-escala
ll += escala
marginales.append([np.exp(logf[actual==j]).sum() for j in (0,1)])
return ll,np.array(marginales)
par_h = np.array([.754673,.095915,-.358811,1.163516,
np.exp(-.262658)**2,.013486,-.057521,-.246983,-.212923])
Ph = np.array([[par_h[0],1-par_h[0]],[par_h[1],1-par_h[1]]])
mh,arh = par_h[2:4],par_h[5:]
ll_propio,prob_h = hamilton_centrado(rgnp,mh,arh,np.sqrt(par_h[4]),Ph)
ham = MarkovAutoregression(rgnp,k_regimes=2,order=4,switching_ar=False)
res_h = ham.filter(par_h)
print("observaciones totales y condicionadas:",len(rgnp),ham.nobs)
print("log L propio y statsmodels:",ll_propio,res_h.llf)
print("error máximo en probabilidades filtradas:",
np.max(abs(prob_h-res_h.filtered_marginal_probabilities)))The preceding parameters are the reference point from the published statsmodels test, not an estimate we just obtained. The next optimization starts there and attempts to refine the in-sample fit; if it is already close to an optimum, it may barely change. Local convergence does not rule out other maxima.
fit_h = ham.fit(start_params=par_h,em_iter=0,search_reps=0,
maxiter=40,disp=False)
print("convergencia, log L inicial y final:",
fit_h.mle_retvals.get("converged"),res_h.llf,fit_h.llf)
print("medias y persistencias estimadas:",fit_h.params[:4])Lab: return volatility regimes
We use the same S&P 500 closing prices as in the GARCH lesson, not generated data. We fit the simple regime-dependent intercept and variance family with and fixed initial distribution. Results describe this historical sample; estimating parameters over the full period does not construct a trading signal free of leakage.
precios = np.array([2695.810059,2713.060059,2723.989990,2743.149902,2747.709961,2751.290039,2748.229980,2767.560059,2786.239990,2776.419922,2802.560059,2798.030029,2810.300049,2832.969971,2839.129883,2837.540039,2839.250000,2872.870117,2853.530029,2822.429932,2823.810059,2821.979980,2762.129883,2648.939941,2695.139893,2681.659912,2581.000000,2619.550049,2656.000000,2662.939941,2698.629883,2731.199951,2732.219971,2716.260010,2701.330078,2703.959961,2747.300049,2779.600098,2744.280029,2713.830078,2677.669922,2691.250000,2720.939941,2728.120117,2726.800049,2738.969971,2786.570068,2783.020020,2765.310059,2749.479980,2747.330078,2752.010010,2712.919922,2716.939941,2711.929932,2643.689941,2588.260010,2658.550049,2612.620117,2605.000000,2640.870117,2581.879883,2614.449951,2644.689941,2662.840088,2604.469971,2613.159912,2656.870117,2642.189941,2663.989990,2656.300049,2677.840088,2706.389893,2708.639893,2693.129883,2670.139893,2670.290039,2634.560059,2639.399902,2666.939941,2669.909912,2648.050049,2654.800049,2635.669922,2629.729980,2663.419922,2672.629883,2671.919922,2697.790039,2723.070068,2727.719971,2730.129883,2711.449951,2722.459961,2720.129883,2712.969971,2733.010010,2724.439941,2733.290039,2727.760010,2721.330078,2689.860107,2724.010010,2705.270020,2734.620117,2746.870117,2748.800049,2772.350098,2770.370117,2779.030029,2782.000000,2786.850098,2775.629883,2782.489990,2779.659912,2773.750000,2762.590088,2767.320068,2749.760010,2754.879883,2717.070068,2723.060059,2699.629883,2716.310059,2718.370117,2726.709961,2713.219971,2736.610107,2759.820068,2784.169922,2793.840088,2774.020020,2798.290039,2801.310059,2798.429932,2809.550049,2815.620117,2804.489990,2801.830078,2806.979980,2820.399902,2846.070068,2837.439941,2818.820068,2802.600098,2816.290039,2813.360107,2827.219971,2840.350098,2850.399902,2858.449951,2857.699951,2853.580078,2833.280029,2821.929932,2839.959961,2818.370117,2840.689941,2850.129883,2857.050049,2862.959961,2861.820068,2856.979980,2874.689941,2896.739990,2897.520020,2914.040039,2901.129883,2901.520020,2896.719971,2888.600098,2878.050049,2871.679932,2877.129883,2887.889893,2888.919922,2904.179932,2904.979980,2888.800049,2904.310059,2907.949951,2930.750000,2929.669922,2919.370117,2915.560059,2905.969971,2914.000000,2913.979980,2924.590088,2923.429932,2925.510010,2901.610107,2885.570068,2884.429932,2880.340088,2785.679932,2728.370117,2767.129883,2750.790039,2809.919922,2809.209961,2768.780029,2767.780029,2755.879883,2740.689941,2656.100098,2705.570068,2658.689941,2641.250000,2682.629883,2711.739990,2740.370117,2723.060059,2738.310059,2755.449951,2813.889893,2806.830078,2781.010010,2726.219971,2722.179932,2701.580078,2730.199951,2736.270020,2690.729980,2641.889893,2649.929932,2632.560059,2673.449951,2682.169922,2743.790039,2737.800049,2760.169922,2790.370117,2700.060059,2695.949951,2633.080078,2637.719971,2636.780029,2651.070068,2650.540039,2599.949951,2545.939941,2546.159912,2506.959961,2467.419922,2416.620117,2351.100098,2467.699951,2488.830078,2485.739990,2506.850098,2510.030029,2447.889893,2531.939941,2549.689941,2574.409912,2584.959961,2596.639893,2596.260010,2582.610107,2610.300049,2616.100098,2635.959961,2670.709961,2632.899902,2638.699951,2642.330078,2664.760010,2643.850098,2640.000000,2681.050049,2704.100098,2706.530029,2724.870117,2737.699951,2731.610107,2706.050049,2707.879883,2709.800049,2744.729980,2753.030029,2745.729980,2775.600098,2779.760010,2784.699951,2774.879883,2792.669922,2796.110107,2793.899902,2792.379883,2784.489990,2803.689941,2792.810059,2789.649902,2771.449951,2748.929932,2743.070068,2783.300049,2791.520020,2810.919922,2808.479980,2822.479980,2832.939941,2832.570068,2824.229980,2854.879883,2800.709961,2798.360107,2818.459961,2805.370117,2815.439941,2834.399902,2867.189941,2867.239990,2873.399902,2879.389893,2892.739990,2895.770020,2878.199951,2888.209961,2888.320068,2907.409912,2905.580078,2907.060059,2900.449951,2905.030029,2907.969971,2933.679932,2927.250000,2926.169922,2939.879883,2943.030029,2945.830078,2923.729980,2917.520020,2945.639893,2932.469971,2884.050049,2879.419922,2870.719971,2881.399902,2811.870117,2834.409912,2850.959961,2876.320068,2859.530029,2840.229980,2864.360107,2856.270020,2822.239990,2826.060059,2802.389893,2783.020020,2788.860107,2752.060059,2744.449951,2803.270020,2826.149902,2843.489990,2873.340088,2886.729980,2885.719971,2879.840088,2891.639893,2886.979980,2889.669922,2917.750000,2926.459961,2954.179932,2950.459961,2945.350098,2917.379883,2913.780029,2924.919922,2941.760010,2964.330078,2973.010010,2995.820068,2990.409912,2975.949951,2979.629883,2993.070068,2999.909912,3013.770020,3014.300049,3004.040039,2984.419922,2995.110107,2976.610107,2985.030029,3005.469971,3019.560059,3003.669922,3025.860107,3020.969971,3013.179932,2980.379883,2953.560059,2932.050049,2844.739990,2881.770020,2883.979980,2938.090088,2918.649902,2882.699951,2926.320068,2840.600098,2847.600098,2888.679932,2923.649902,2900.510010,2924.429932,2922.949951,2847.110107,2878.379883,2869.159912,2887.939941,2924.580078,2926.459961,2906.270020,2937.780029,2976.000000,2978.709961,2978.429932,2979.389893,3000.929932,3009.570068,3007.389893,2997.959961,3005.699951,3006.729980,3006.790039,2992.070068,2991.780029,2966.600098,2984.870117,2977.620117,2961.790039,2976.739990,2940.250000,2887.610107,2910.629883,2952.010010,2938.790039,2893.060059,2919.399902,2938.129883,2970.270020,2966.149902,2995.679932,2989.689941,2997.949951,2986.199951,3006.719971,2995.989990,3004.520020,3010.290039,3022.550049,3039.419922,3036.889893,3046.770020,3037.560059,3066.909912,3078.270020,3074.620117,3076.780029,3085.179932,3093.080078,3087.010010,3091.840088,3094.040039,3096.629883,3120.459961,3122.030029,3120.179932,3108.459961,3103.540039,3110.290039,3133.639893,3140.520020,3153.629883,3140.979980,3113.870117,3093.199951,3112.760010,3117.429932,3145.909912,3135.959961,3132.520020,3141.629883,3168.570068,3168.800049,3191.449951,3192.520020,3191.139893,3205.370117,3221.219971,3224.010010,3223.379883,3239.909912,3240.020020,3221.290039,3230.780029], dtype=float)
retornos = 100*np.diff(np.log(precios))
inicio_real = (np.array([[.95,.05],[.15,.85]]),
np.array([-.1,.1]),np.array([.5,1.5]))
Pe,me,se,he = em(np.r_[0.,retornos],0.,pi,*inicio_real,pasos=50)
fil_real,_,ll_real,_ = forward(densidades(np.r_[0.,retornos],me,se,0.),Pe,pi)
mod_real = MarkovRegression(retornos,k_regimes=2,trend="c",switching_variance=True)
pi_previa_real = np.linalg.solve((Pe@Pe).T,pi)
if np.any(pi_previa_real < 0):
raise ValueError("prior anterior no válido para esta comparación")
mod_real.initialize_known(pi_previa_real)
ref_real = mod_real.filter([Pe[0,0],Pe[1,0],me[0],me[1],se[0]**2,se[1]**2])
print("observaciones, log L y mejora mínima EM:",len(retornos),ll_real,np.diff(he).min())
print("medias, sigmas y transición:",me,se,Pe)
print("diferencia log L y error de probabilidades frente a statsmodels:",
ll_real-ref_real.llf,np.max(abs(fil_real-ref_real.filtered_marginal_probabilities)))
print("duraciones medias en una rejilla de persistencias:",
[1/(1-p) for p in np.linspace(.5,.9,9)])
print("pesos estacionarios del segundo estado en una rejilla de pares:",
[(1-a)/(2-a-b) for a in (.8,.85,.9) for b in (.7,.75,.8)])Exercises
Step 1 of 3. What is the predictive probability of regime j before observing yₜ?
import numpy as np
from scipy.special import logsumexp
def hamilton_filter(y, mu, sigma, phi, P, pi):
passThe filter combines transitions and observation densities to maintain a belief about the regime. The smoother improves retrospective description using the future; estimation, identification and real-time decisions require additional assumptions and checks.