15. Filtering
This chapter covers the linear and nonlinear filtering machinery
that filter, estimate, forecast, and the historical
decomposition route into.
15.1. Linear filtration
Filtering with constant parameters can be done efficiently with the algorithms of De Jong et al. (2003), Koopman and Durbin (2000, 2003), and Durbin and Koopman (2012). These procedures cannot be used directly in a regime-switching context.
The main references for the filtration of Markov-switching state-space models are Kim (1999) and Kim and Nelson (2001), which combine the Kalman and Hamilton filters. Similar algorithms appear in the engineering literature (Bar-Shalom et al., 2001, 2004).
RISE uses an extension of the Durbin-Koopman (2012) algorithm.
For a non-stationary model the initial covariance is set by
kf_init_variance: by default the unconditional variance of the
stationary directions and lyapunov_diffuse_factor on the
nonstationary ones; a large scalar approximates a diffuse start;
'exact' gives the exact diffuse (Durbin-Koopman) initialization,
with or without regime switching. It requires the nonstationary
directions to be the same in every regime; otherwise RISE warns and
falls back to the default. The filters that implement it and its
other conditions are in Diffuse initialization.
For efficiency, RISE deviates from Kim-Nelson (2001) when collapsing the regimes. Kim-Nelson collapse the updates; RISE collapses the forecasts. The two procedures yield numerically similar results but the RISE procedure is faster.
A transition matrix may hold exact zeros and ones: a regime the chain
cannot leave, or a probability that a steep function of the data sets
to 0 or 1. A regime that no regime of the period before leads to then
has zero predicted probability, and it contributes nothing to the
likelihood, to the updated probabilities or to the smoothed ones, as
in the limit of a small probability. Until 2026-10-13 imm
stopped there with retcode 305.
15.1.1. Constraints and announced shocks
The filter applies the model as the simulation does. Each period’s
state is \(y_t = g(x_{t-1}, \eta_t)\), the one-step map from
the previous state and the period’s drawn shocks; with
occasionally-binding constraints, \(g\) includes the constraint
engine, which solves the enforcing shocks (the fudge shocks of the
kinks, or the shocks a simul_constraints row names) so that the
constraints hold.
Announced shocks. A shock with a positive
solve_shock_horizonis announced up to that many periods ahead. The announcements are part of a period’s information and need not come true: each period every page moves one period closer and takes a revision, and at first order the filter carries the outstanding pages as states, with their stationary covariance at the start (see How an announcement evolves: pages and revisions). The enforcing shocks are solved, never drawn, and carry no variance.Constraints. Where the map is linear (no enforcement on the way) the update is the Kalman update. Where the enforcement bends it, the filter updates the inputs \((x_{t-1}, \eta_t)\) instead, with the map linearized where the previous iterate landed (an iterated extended Kalman update); where the data contradict the enforcement at the prediction (a rate predicted at its floor and observed above it), the step is taken with the enforcement released. The updated state is \(g\) at the updated inputs, so the filtered series respect the constraints. With one shock and its observable measured without error the update agrees with inverting the model for that shock. Near a kink the update is the one over the branches around it (Near the kinks: kf_kink_density), over the whole window when the enforcers are anticipated (Over an anticipation window). An update that cannot be formed stops the filter with a return code and no likelihood (314, 317, 305 or the constraint engine’s own code); an observed variable held at its bound keeps the Kalman update, and the period is marked. Neither warns: Return codes and marks of the constrained filter lists each code and mark and what it means in estimation.
Regimes. A regime-switching filter predicts the next period once for each regime it may be in, and weights the predictions by the transition probabilities at the current state. Each constrained prediction is taken in the regime of its branch, as the branch’s covariance and update are; the anticipated pages of the constraint engine stay in that regime. Under a switch rule (
simul_regimea function) the rule selects the regime instead.simul_disable_constraints = truefilters the model as if it had no constraints.
15.1.2. Near the kinks: kf_kink_density
The constrained update settles on one branch of the constraints: one pattern of active enforcers, on which the map is linear. Where the posterior straddles a kink (a rate whose floor lies within a few standard deviations of its updated value), every branch around the kink predicts the data, each in its own region of the inputs, and the settled branch alone misses the others. The likelihood of such a period is then not the constrained model’s. Where the mode of the update lies on the kink itself – a rate observed with an error near its floor, or not observed and close to it – the iteration cycles between the two branches with neither consistent with the constraints, and the filter stops with retcode 314.
By default (kf_kink_density = true) the update near
kinks is the one over the branches around them; false keeps the
one-step update, which fails with retcode 314 where it cycles. The predictive
density of the period’s data is
\(N_c\) the density of branch c’s update (the update the constrained step takes on that branch) and \(P_c\) the probability, under that update’s posterior of the inputs \((x_{t-1}, \eta_t)\), that the inputs lie in the region of c: an orthant probability over the kinks near c. For a Gaussian prior of the period it is the exact density. The updated state is the mixture of the branches’ posteriors truncated to their regions and mapped by their branches, summarized by its mean and covariance (an assumed-density filter).
When to use it. A constraint that binds and is observed with an error near its bound, or not observed near it; estimation on such data, where the update without the option fails with 314 or carries a likelihood error in the periods near the kink. On nk3_zlb with the rate missing at its floor (200 samples), 15 samples fail with 314 without the option and none with it.
Any number of kinks. A kink is near when the posterior of a branch puts more than
1e-8of its probability across it. The branches are found with the constraint engine, across each kink near a branch already found, up to 16 (all the combinations of four kinks). A branch whose weight (its density times the probability of its region) is below1e-8times the largest is not searched from. Over an anticipation window the search differs (see Over an anticipation window). The posterior mass of the regions left out is returned askink_dropped_mass: an estimate, extrapolated from the branches next to them, and zero when every branch around the near kinks was found. The probability of a region and the moments within it are deterministic up to three kinks near one branch (to about1e-12); beyond, a lattice rule gives the probability to about1e-6and the moments to about1e-3. With two interacting floors near their kinks at once, the period’s density and updated means match direct integration over the four regions to1e-11.Output.
kink_mixed_updatesmarks the periods whose update mixed the branches;kink_unresolved_updatesthose near a kink where the mixture could not be formed (over one period the update is then the settled branch’s, a code says why; over a multi-period window the filter stops with 314);kink_dropped_massthe mass left out. Likeobserved_at_bound_updatesthey are time series in the filter’s output (see Return codes and marks of the constrained filter).Updated series. Near a kink the updated state is a posterior mean, off the kink: the mean of
R = max(zlb, Rnot)is at leastmax(zlb, mean of Rnot), with equality in the periods updated on one branch. The updated policy rate stays above its floor, and the observed variables keep their data.Cost. Per mixed period, for each branch: one solve of the constraint engine, one set of slopes (computed once per pattern), one Gaussian update and one orthant probability. Up to \(2^m\) branches for m kinks near at once. On small models a filter call whose last period is near one to three kinks takes 2 to 4 times as long as without the option, near four kinks about 30 times (the lattice rule). Over a sample it depends on how many periods mix: 1.4 to 2 times on nk3_zlb, 1.8 times on the reduced HANK test, 9 times on a model whose rate is never observed and stays near its floor.
Anticipated constraints. With a positive
solve_shock_horizonthe constrained step covers a window of several periods, and the update integrates over the branches of the whole window; see Over an anticipation window.What it does not fix. Failures of the constraint engine itself (a forecast it cannot solve, retcode -402), and the smoother. The state is collapsed to one Gaussian each period (its mean and covariance): each period’s density is exact for its Gaussian prior, but the collapse is an approximation. Against a particle filter on heavily censored test models (a censored AR(1), two interacting floors), it moves the log-likelihood of a 60- to 100-period sample by a few tenths, with a mean near zero.
Tutorial: WorkingWithAModel/filtering_near_kinks. Tests:
models/dsge/filtering/constraints/Test_kink_density.m.
15.1.3. Over an anticipation window
With a positive solve_shock_horizon the constraint engine enforces the
constraints over a window: the period and the \(k\) periods after it,
\(k\) the longest horizon of any shock, not only the enforcers’ own.
The period’s map from its inputs \(u_t=(x_{t-1},\eta_t)\), the
previous state (the outstanding announcement pages included) and the
period’s revisions, is then piecewise affine. Each piece, a branch, is an
enforcement pattern: which enforcer is active on which page of the window.
On the region \(\mathcal{R}_a\) of the inputs where the engine returns
pattern a,
\(G_a\) the derivatives of the window’s forecast with the active enforcers holding their rows on every page. The region is a polyhedron: each active enforcer keeps its sign, and each slack row keeps the sign of its switch on each page. With \(n_f\) enforcers there are at most \(2^{n_f(k+1)}\) patterns, some of them empty: for one bound, 4 at horizon 1, 8 at horizon 2, 32 at horizon 4 and 128 at horizon 6.
What the filter computes. With kf_kink_density = true (the default)
the density of the period’s data is the sum over the patterns of the
window, as in one-period steps (Near the kinks: kf_kink_density),
\(p(y_t)=\sum_a N_a(y_t)\,P_a\): \(N_a\)
the Gaussian density of the Kalman update of the linear model
\(y_t = Z g_a(u_t) + v_t\), and \(P_a\) the probability, under that
update’s posterior of the inputs, of the region of a. The probability of a region
and the moments within it are computed on the support of the posterior (an
observable measured without error removes a direction): in closed form for
a region of rank one, otherwise with a fixed lattice rule of 65,536 points,
without an error estimate. The updated state is the mixture of the
posteriors truncated to their regions and mapped by their branches,
collapsed to its mean and covariance, which is the prior of the next
period. For a Gaussian prior the period’s density is exact, up to the error
of the lattice rule and provided every branch with mass is found; from the
second period on the prior is the collapsed one, and the likelihood of a
sample is that of an assumed-density filter.
Over a window the search differs from one-period steps:
From the second period on, every update goes through the constrained step (in the first, only where the constraints show, as in one-period steps), and every kink of the window counts as near: every branch found is searched from and integrated, whatever its weight. In one-period steps a kink is near only beyond
1e-8of the posterior’s probability, and a branch below1e-8times the largest weight is not searched from. On the tutorial’s sample every period mixes.A neighbour is found with the constraint engine at a point just across a kink of a branch already found and inside its other inequalities. When a linear program shows there is no such point, the crossing is empty and the kink has no neighbour: with a short announcement and a longer enforcer window, the pages beyond the announcement move together, their kinks are nested, and crossing a later page while an earlier one holds is empty. The mass of any other neighbour not found is estimated from the branch next to it: the probability, under that branch’s posterior, of the neighbour’s region (the kink crossed, the other inequalities kept). Above
1e-8in total the update is not formed, and the filter stops with 314.At most 64 branches, against 16 in one-period steps. There the search stops at 16 and the mass left out is estimated; over a window, once 64 branches are found, a kink that leads to a pattern not found yet stops the filter with 314. That is possible from horizon 6 with one enforcer (128 patterns) and from horizon 3 with two (256).
An update over the window that cannot be formed stops the filter with 314, whereas a one-period step keeps the settled branch’s density and marks the period:
kink_unresolved_updatesbelongs to one-period steps, andkink_dropped_massis at most1e-8in every period of a window.
What kf_kink_density = false keeps. The update of one branch:
the iterated extended Kalman update stops on the pattern where it settles,
a, and takes its Gaussian density \(N_a\). Both routes call the same
constraint engine with the same enforcers and carry the announcements by
the same law; the option changes the statistical update, not the
enforcement. The density of one branch leaves out two terms,
the first for the share of branch a’s own posterior outside its region (at most zero), the second for the other branches (at least zero), so its error has no fixed sign. Where a parameter moves the shadow rate across its floor, the branch where the iteration settles changes, and the single-branch likelihood can jump; in the sum over the branches the mass moves from one branch to the other continuously. Where the iteration cycles between two branches, it takes the one consistent with the constraints when exactly one is, and stops with 314 otherwise; over a window it never takes a branch that keeps an enforcer active, whose check (each active enforcer holding its row from the right side) has no closed form there. On the tutorial’s sample the single-branch route cycles at horizons 3 and 4 between two branches neither of which is consistent, and stops with 314.
Cost against the horizon. Per period and branch the update takes one solve of the constraint engine, the window’s derivatives (once per pattern), one Gaussian update and the integral of the region, over the 65,536 points above rank one. On the sample of the tutorial (101 periods of the output gap, the demand shock and the enforcer of the bound anticipated k periods; log-likelihoods in natural logs, seconds of one single-threaded run):
k |
patterns |
log-likelihood, on |
seconds |
log-likelihood, off |
seconds |
|---|---|---|---|---|---|
0 |
2 |
-236.40838 |
0.61 |
-236.40838 |
0.23 |
1 |
4 |
59.80410 |
2.6 |
60.25888 |
0.40 |
2 |
8 |
165.62292 |
29 |
166.10085 |
0.35 |
3 |
16 |
208.44547 |
67 |
314 in period 11 |
0.12 |
4 |
32 |
220.59268 |
185 (likelihood only) |
314 in period 18 |
0.16 |
6 |
128 |
314 in period 1 (65th branch) |
7.0 (one period) |
At horizon 0 there is no window, and the update is the one-period update over the branches near the kink (Near the kinks: kf_kink_density); on this sample no period is near one, and both routes agree. The single-branch update stays below a second at every horizon where it runs. What drives the cost of the integration is the number of uncertain announcement pages, not the length of the window: on the first 15 periods, with the demand shock anticipated 2 periods, a likelihood takes 4.3 s with the enforcer’s own horizon at 0 and 4.6 s at 2 (a window of three periods either way); with the demand shock a surprise and the enforcer alone anticipated 2 periods, 1.1 s, the pages beyond the announcement moving together. In estimation every draw pays this cost, and the single-branch route, though cheap, has no likelihood wherever its iteration cycles (on this sample at horizons 3 and 4).
Written with the announcements as explicit states in the model file (the
pages as endogenous variables, the revisions as their shocks), the same
model gives the same likelihood over the first six periods of the
tutorial’s sample: to 1e-9 with the demand shock announced 1 or 2
periods ahead and the enforcer’s window 4, and to 2e-6 with both
anticipated 4 periods.
The updated series agree to 1e-6 in both cases.
Tutorial: WorkingWithAModel/filtering_anticipated_zlb. Tests:
models/dsge/obc/worked_examples/anticipated_shocks_zlb
(TestShortAnnouncementWindow.m, TestCarriedConstraintReference.m,
TestLikelihoodOnlySamples.m) and
models/dsge/filtering/constraints/Test_imm_failure_returns.m.
15.1.4. Return codes and marks of the constrained filter
The constrained filter issues no warning and raises no error when its update fails: an estimation calls the filter thousands of times and cannot act on a warning. An update that cannot be formed stops the filter with a return code. A designed approximation keeps the return code at 0 and marks the period.
What a failure looks like. [f, LL, incr, rc] = filter(m, ...) returns
the code in rc; LL is -abs(estim_penalty) (-1e20 by
default); the period log-likelihoods incr are NaN from the period
that failed on; the marks of the periods before it are not returned.
utils.error.decipher(rc) gives the message. In estimation the draw is
rejected: the samplers, the Hessian at the mode and
log_posterior_kernel give it the value estim_penalty and zero
density, and the mode search ranks it among the points that fail in the
filter (see “Points the model rejects” in
Posterior maximization). A return code says that the
update was not formed, not that the data have zero probability under the
constrained model.
Return code |
When |
What to check |
|---|---|---|
314 |
The update through the constrained step failed: the constraint
engine failed at an iterate or at the anchor of a branch, or its
slopes failed; the iteration did not settle in 20 steps; it cycled
between two branches, without the update over the branches
( |
|
317 |
The update needed a branch whose enforcers barely move the rows they hold: their response is singular to working precision (its smallest singular value below \(\sqrt{\epsilon}\) times the largest), measured across a kink, or gives slopes above \(1/\sqrt{\epsilon}\) times the unconstrained ones; or the prediction refused such a branch and the update did not settle through the constrained step. |
A reduced model whose basis leaves out the enforcers’ responses: keep them (see Model reduction). |
305 |
The innovation covariance of the constrained update, or of the slack branch near a kink, is not positive definite, as in the Kalman update. No other update takes its place. |
Redundant observables, and the variances of the shocks and the measurement errors. |
the constraint engine’s code |
A constrained prediction, or its slopes, failed in the engine: its
code (-402 for a forecast it cannot solve), or 314 for slopes that
fail without one. In the update the same failure gives 314, except
under |
The message of the code; for 706, a longer window
( |
Mark (field of the output) |
Meaning |
|---|---|
|
An observed variable held at its bound (a rate observed at its floor): after releasing the enforcers the iteration came back to a branch that holds a variable the data move, and the data say nothing about the shadow variable behind it. The period keeps the Kalman update, moved back onto the constraints with the least change in the period’s structural shocks, the observed variables at their values. Its likelihood is the Kalman update’s: an approximation. |
|
The update mixed the branches around a kink, over the whole window when the enforcers are anticipated. The period’s density is exact for its Gaussian prior (over a window, up to the error of the lattice rule); the mark is information. |
|
One-period steps only: near a kink the update over the branches could not be formed, and the period keeps the density of the settled branch, an approximation. The value says why: 1 no other branch across the kink, 2 the slopes there failed, 3 its update failed, 4 the two branches do not differ by one enforcer or are not on either side of the kink, 5 near several kinks, a branch that matters could not be formed. |
|
By period, the posterior mass of the regions left out: an estimate in
one-period steps, at most |
|
The iteration cycled between two branches and took the one whose
update is consistent with the constraints, with
|
A field is returned only when some period is marked; each is a time series in the filter’s output, at every filtering level. A marked period has a likelihood, and an estimation uses it without seeing the mark: to check the periods of an estimated model, filter it at the mode and read the fields.
15.1.5. Smoothed series that hold the constraints: kf_constrained_smoother
kf_constrained_smoother [{false}|true]: smoothed series that hold occasionally binding constraints.
For a model with one regime and occasionally binding constraints (max/min kinks,
simul_constraints), with the option on, the smoothed series are the most likely path of the
constrained model given the data: the initial state and shocks with the highest posterior
density, the constraints held by their enforcers period by period, as in the simulation.
They respect the bounds and kinks, and reproduce the exactly observed data.
simulatefrom the smoothed state with the smoothed shocks gives them back.The enforcers’ smoothed values say how hard each constraint binds.
The smoother is the posterior mode, not its mean. Far from the bounds the two coincide. Near a bound the mode can put an unobserved shadow rate exactly at it, where the data are best explained.
Off (the default), the smoothed series are the published linear smoother’s, which can break the bounds and the kinks. Historical results for the former pairwise backend on nk3_zlb, with the rate unobserved at its floor, missed the floor in 2 quarters of 150; a Monte Carlo recorded up to 30 quarters in 150.
Cost. The smoother follows a path over the whole sample; each step is a Kalman filter and smoother pass on the state augmented with the step’s inputs. On a three-equation model with a lower bound it takes 0.6 s against 0.3 s; with the bound’s enforcer anticipated 40 periods, 20 to 30 s against 10 s; on a HANK with 433 enforcer pages, 1223 s against 99 s. The likelihood and the filtered and updated series do not depend on the option.
When to turn it on: when the smoothed series must hold the bounds (shadow rates, smoothed paths that feed a simulation or a policy analysis) and the model is not large.
The field constrained_smoother of the filter’s output reports how it went: status
(converged, maxsteps, failed or refused), the steps, the kink pins, the periods where
an exactly observed variable forced a constraint slack, and the largest gap to the exactly
observed data. A smoother that does not converge, or whose step fails on the way, returns the
last path of the model it reached, with a warning; a converged path that misses the exactly
observed data by more than 1e-6 warns too. Only when it is refused, or fails before reaching a
path, are the smoothed series the published linear smoother’s, again with a warning.
It needs the initial state at the steady state and its covariance the stationary one (the
default), or a big-kappa (kf_init_variance a scalar: then x{0} ~ N(ss, kappa*I)). An exact
diffuse initialization or an initial covariance given by kf_user_init is refused.
Regime-switching models with constraints keep the published switching smoother. Other filters chosen with
kf_user_algo keep their own smoothers. With anticipated enforcers (solve_shock_horizon on
the fudge shocks), a period where an exactly observed constrained variable forces its constraint
slack releases all the enforcer’s pages of that period. With kf_kink_density, the periods the
filter updates over two branches are started from the unconstrained map.
15.1.6. Smoothing under regime switching
The regime-switching filters imm, imm_o, gpbn (any history
length), immn and crskfc share one smoother. It smooths each
pair of linked regime histories (a history this period and one it can
lead to next period) against that pair’s own prediction, and weighs the
pairs with Kim’s posterior weights on the chain of histories. As a
result, an identity that is linear in the model’s variables and that
the model states in every regime holds in the smoothed path, the
probability-weighted average included: a level and its first
difference, for example, stay consistent even when both are
unobserved. A nonlinear identity does not survive the averaging: with
x equal to 1 or 3 with equal probabilities, the average of x^2
is 5, not 4. The average is taken over the series as reported, in
levels for the variables declared log, so a ratio between such
variables (output growth as Y/Y{-1}) need not hold between their
averaged series. The likelihood and the filtered series are not
affected.
crskfc uses this smoother by default (hkkm_smoother = false
keeps its classical one); kim_nelson keeps its own.
The sigma-point filters (switching_cubature_kalman_filter,
switching_unscented_kalman_filter and
switching_divided_difference_filter, the default above the first
order) smooth each regime of a period against each regime of the next,
through the pair’s own prediction and the covariance of the states of
the two periods, and weigh the pairs by their smoothed probabilities
(Kim’s smoother). On a linear model they give the Kalman smoother with
one regime and imm’s smoother with several. The switching inversion
filter smooths its regime probabilities by the same backward recursion;
its states given the regime are the filter’s, which the inversion makes
functions of the data and of the regime.
With gpbn of order 1 (gpb1), which predicts every regime from one
collapsed state, the smoother pairs each regime of a period with each
regime of the next through the pair’s own update of the next period,
and weighs the pairs by their likelihood of the next observation. The
smoothed path keeps the model’s linear identities. On a volatility-switching
test model, gpb1’s smoothed unobservables are 2-3% less accurate than
with the smoother it replaces (which broke the identities), and its
smoothed regime probabilities are more accurate. Higher orders (gpb2,
…) need no such pairing and smooth more accurately.
Under occasionally binding constraints the smoothed series reproduce the observed data, but in binding periods they need not respect the constraints.
15.1.7. Historical decomposition
Warning
Exact only for constant-parameter linear models.
15.1.8. Observables decomposition
Important
Available only for constant-parameter models.
15.2. Conditional forecasting via filtering
Conditional forecasting can be implemented using filtering algorithms. The smoother treats the conditioning values as observations on the forecast horizon and fills in everything else by least squares – no simulation plan is required, which makes this the most convenient route when its assumptions hold.
The assumptions are restrictive: it works only for linear
models, and the conditioning variables must be on the observed
side (declared in @observables). For anything else – hard
conditions on unobserved states, nonlinear solutions, regime
switching, anticipated shocks, soft conditions enforced through
shocks rather than measurement noise – use a simulation plan
through Forecasting and simulation.
15.2.1. Hard conditions
Extend the observation database to cover the forecast horizon.
Numeric entries pin the observed variable at that date; NaN
entries are free. Then call filter:
db = struct();
db.PAI = [pai_history; pai_future_conditions]; % conditioned
db.R = [r_history; nan(H, 1)]; % free
db.DY = [dy_history; nan(H, 1)]; % free
m = set(m, data = db);
[filt, ll, ~, rc, m] = filter(m);
The smoothed series in filt are the conditional forecast for
every endogenous variable and shock. The implied shock path is
the least-squares one that makes the conditioning observations
consistent with the model.
15.2.2. Soft conditions
Relate the conditioning observation X0 to a model variable
X as \(X0_t = X_t + \sigma \varepsilon_t\). The scalar
\(\sigma\) controls the softness of the condition:
\(\sigma \to \infty\) – the condition is irrelevant.
\(\sigma \to 0\) – hard conditions.
\(\sigma\) strictly positive and finite (small enough) – soft conditions.
15.2.3. When to choose this route
Model is linear (constant-parameter or regime-switching).
Conditions are on observed variables.
You want a least-squares decomposition of the implied shock path.
You do not need to control anticipation: the smoother treats the conditioning path as fully observed up to its date, which is closest to “unanticipated until realized” in spirit.
15.2.4. When the route is the wrong tool
Higher-order or strongly nonlinear solutions – the least-squares interpretation breaks down.
Conditions on unobserved states (e.g. natural rate, output gap) – declare them as
@observablesfirst or switch to a simulation plan.You want to choose which shocks the solver may use to enforce a condition (the free shocks of a simulation plan).
You want to mix anticipated and unanticipated shocks in the same scenario.
15.3. Known regime paths and heteroskedastic shocks
When the regimes of a Markov-switching model are known over the
sample – a policy regime with known dates, or a volatile episode
such as a pandemic – the model can be filtered on that path
instead of with regime probabilities. The filter
myKnownRegimesFilter is the exact Kalman filter of the
time-varying system
where \(s_t\) is the given regime of period \(t\) and \(T(s), R(s), c(s)\) are the model’s first-order decision rules in regime \(s\).
15.3.1. The call
The path is passed with the filter, through kf_user_algo; the
same option goes to estimate:
s = ones(1, n); s(161:164) = 2; % s(t): the regime of period t
[f, LogLik] = filter(m, kf_user_algo = {@myKnownRegimesFilter, s});
m_est = estimate(m, estim_priors = priors, ...
kf_user_algo = {@myKnownRegimesFilter, s});
shas one entry per period of the estimation sample.s(t)is the regime of period \(t\): the regime whose solution produces period \(t\) from period \(t-1\) and the shocks of period \(t\) (so the shocks of period \(t\) have the standard deviations of regimes(t)).With several Markov chains, the entries are the composite regimes, the rows of
m.markov_chains.regimes.The initial state and covariance are those of the regime of the first period,
s(1): its steady state and, when its solution is stationary, its unconditional covariance.kf_user_init = {a0, P0}imposes them;kf_init_varianceapplies as for the other filters.The output has the usual fields; the regime probabilities are the 0/1 indicators of
s. Missing observations, measurement errors andkf_presampleare handled as in the other filters. The smoothed shocks are the unit-variance innovations of the model’s equations.
15.3.2. Data simulated on a path
In simulate, the first point of a simulation (with
simul_burn = 0) is the initial condition and carries the first
entry of simul_regime; simulated period \(t\) carries entry
\(t+1\). To simulate \(n\) periods with the regimes s
and filter them with s:
db = simulate(m, simul_regime = [s(1), s], simul_periods = n+1, simul_burn = 0);
% keep the simulated periods 1 to n: points 2 to n+1 of each series
15.3.3. Heteroskedastic shocks
The heteroskedastic filter lets the shocks of given periods have a larger variance, leaving the decision rules and the steady state unchanged. In RISE a standard deviation is a coefficient of a unit-variance shock in the model equations; writing it as a switching parameter of a chain that moves nothing else gives that filter:
@exogenous eg eu
@parameters phi bet kappa rho_g rho_u sig_u vol_tp_1_2 vol_tp_2_1
@parameters(vol,2) sig_g
@model
y = phi*y{+1} + g;
pi = bet*pi{+1} + kappa*y + u;
g = rho_g*g{-1} + sig_g*eg;
u = rho_u*u{-1} + sig_u*eu;
@parameterization
sig_g(vol,1) = 1; sig_g(vol,2) = 8;
vol_tp_1_2 = 0.02; vol_tp_2_1 = 0.5; % needed to solve the model
then filter or estimate with the path of the vol regime as
above. sig_g_vol_2 is an ordinary parameter: fixed, or
estimated with a prior. To estimate a scale instead, write the
shock as scale_g*sig_g*eg with @parameters(vol,2) scale_g.
One regime is needed per distinct set of scales: quarters whose
shocks have different scales need a regime each. The tutorial
Estimation/heteroskedastic_shocks estimates such a model with
and without its volatile episode.
15.3.4. What the agents know
The decision rules are those of agents who know the regime process and forecast future regimes with the transition probabilities. The known path is the econometrician’s information. The two views coincide when the decision rules do not depend on the expected regimes:
At first order, when only standard deviations switch, certainty equivalence makes \(T(s)\) and the steady state the same in every regime and independent of the transition probabilities; only \(R(s)\) scales. Filtering on the path is then exactly the heteroskedastic filter, and the transition probabilities play no role.
At first order, when the volatility chain also moves other parameters (a policy coefficient on the same chain, for instance), \(T(s)\) depends on the regime and on the transition probabilities: the filter conditions on agents who anticipate regime changes.
At second order and above, the risk terms depend on the regime and on its transition probabilities: a Markov-switching volatility is then a volatility the agents anticipate.
15.3.5. Limits
The filter refuses, with an error identifier:
occasionally-binding constraints (
rise:knownRegimes:constraints): it is a Kalman filter. Withsimul_disable_constraints = truethe model is filtered as if it had none;anticipated (news) shocks,
solve_shock_horizon > 0(rise:knownRegimes:anticipatedShocks);solve_order > 1(rise:knownRegimes:order);deterministic exogenous variables (
rise:knownRegimes:exogenous);a path of the wrong length or with regimes out of range (
rise:knownRegimes:path).
The alternative when another chain must be filtered with
probabilities alongside the known one is a
transition probability driven by an observed dummy (see
@transition_functions): with vol_tp_1_2 = 1/(1+exp(-(g*D-c)))
and vol_tp_2_1 = 1/(1+exp(-(c-g*D))), \(D_t = 1\) when period
\(t+1\) is volatile and \(g = 2c\) large but finite (for
instance \(c = 40\)), the default filter reproduces the
known-path likelihood. Its probabilities are never exactly 0 or 1.
15.4. Nonlinear filtering
When a DSGE model is solved with a higher-order perturbation – or otherwise has a nonlinear state-space representation – the regime-switching Kalman/Hamilton filter no longer applies. RISE then uses a sigma-point filter for regime-switching nonlinear state-space models, following Binning and Maih (2015).
15.4.1. When the nonlinear filter is used
filter – and, through it, estimate, forecast with
conditioning, the historical decomposition, … – picks the
algorithm automatically from the solution:
solve_order == 1– the linear regime-switching Kalman/Hamilton filter (a fast constant-parameter variant when there is a single regime, no occasionally-binding constraint, and no real-time information).solve_order >= 2– a nonlinear sigma-point filter (the default is the switching divided-difference filter).
Nonlinear filtering with real-time information is not supported (RISE raises an error).
estimate does not filter a fully observed model whose shock map is
proved affine or triangular: it takes the direct likelihood (see
Direct likelihood of fully observed models). RISE has no particle filter.
15.4.2. Choosing the filter
Three sigma-point filters are available; the divided-difference
filter is the default, the other two are selected by passing them
as the filtering algorithm via kf_user_algo (they all share
the standard filter signature, so they plug in directly):
% default: switching divided-difference filter
[fkst, LogLik] = filter(m);
% switching unscented Kalman filter
[fkst, LogLik] = filter(m, kf_user_algo = 'switching_unscented_kalman_filter');
% switching cubature Kalman filter
[fkst, LogLik] = filter(m, kf_user_algo = 'switching_cubature_kalman_filter');
The same option can be passed to estimate – it changes which
filter computes the likelihood that is maximized.
15.5. Options
The filtering options apply equally to the linear and nonlinear
cases (see also help dsge_model/filter):
Option |
Effect |
|---|---|
|
|
|
Start the regime probabilities at the ergodic distribution of the transition matrix at the steady state; |
|
Near the kinks of occasionally-binding constraints, update over the branches around them, with the exact predictive density of the data for a Gaussian prior, any number of kinks at once ( |
|
Initial state covariance. |
|
User-supplied initial state and covariance, for fine control of the initialization. A third entry is the starting regime distribution; the closed-form likelihood of a fully observed model uses it too. |
|
Number of initial observations to discard before evaluating the likelihood. The filter still runs through them, so the states and regime probabilities that start the likelihood reflect those data: the remedy when the steady state, where the filter starts, is far from the data. Default |
|
Return the Cholesky factor when taking the Householder transformation; primarily used by the divided-difference filter. Default |
|
The filtering algorithm. |
|
Steady-state switch of the linear filter: once the Kalman gain changes by less than this between two periods, after the last missing observation, the gain and the covariances are frozen (constant-parameter models without constraints, on every route). |
|
|
|
Solver and limits of the constraint engine, which the filter uses in every period where a constraint binds. |
15.6. User-defined filter
A filter of your own can be supplied through kf_user_algo –
a function (or function name, or cell {name, extra-args...})
with signature:
[LogLik, Incr, retcode, Filters] = myFilter(init, y, U, z, options)
where init is the initialization struct RISE builds. If the filter
needs information beyond what RISE passes, prefix its name (a
character string) with *: RISE first calls it as
init=myFilter(model_data,init), with the engine’s internal model
data, and passes the init it returns to the main call. See
Extending RISE.
15.7. The available sigma-point filters
15.7.1. Switching divided-difference filter
The default RISE nonlinear filter. Uses divided-difference approximations to propagate the state moments through the nonlinear transition and observation maps. Robust on regime-switching models where the unscented transform’s sigma points can fall outside the admissible parameter region.
15.7.2. Switching unscented Kalman filter
Uses the unscented transform to propagate sigma points through the nonlinear maps. Faster than the divided-difference filter on well-behaved problems; can be less robust on awkward switching specifications.
15.7.3. Switching cubature Kalman filter
Uses a spherical-radial cubature rule to propagate the state moments. A modern alternative to the unscented Kalman filter with similar accuracy and somewhat better numerical behavior at high state dimension.
On a linear Gaussian model the unscented and cubature filters give
the exact likelihood, to rounding. Their sigma points take an exact
square root of the state covariance, also when it is singular (a
state the data pin down). They keep one safeguard: the predicted
covariance has its eigenvalues moved into [1.5e-8, 6.7e7]
(sqrt(eps) and its inverse), so that the covariance of the
forecast errors stays invertible under nonlinear propagation. It
changes nothing when the shocks reach every state. Otherwise it adds
up to 1.5e-8 of variance in a direction they do not reach, or
caps a variance above 6.7e7 (a large kf_init_variance). Until
2026-10-13 the sigma points applied the same floor to the updated
covariance, which left these filters 1.8e-6 off the exact
log-likelihood of a fully observed linear test model.
15.8. Published switching smoother
The production switching backward pass follows the information/disturbance recursion of Hashimzade, Kirsanov, Kirsanova and Maih (2026). It retains the filter calendar, missing-data handling, history orders, exact diffuse initialization and the existing output fields. No alternate backward approximation is automatically selected.
Probability-averaged smoothed levels and growth rates need not be mutually consistent after regime switches. This is a known limitation of the smoothing approximation, not a modification of the model equations or calibration. Exact-history posterior calculations and identical-regime controls remain validation references; the switching approximation is not claimed to match every exact-history posterior moment.
The linear backward pass is also an approximation after a constrained nonlinear filter update. The constrained update can replace the innovation, gain and precision while the backward pass retains the unconditional prediction moments and transition. Its smoothed means can then miss even an exactly observed series. Diagnostics report these residuals; finite output does not establish a path satisfying the nonlinear constraints. The optional constrained mode smoother retains its existing scope and tests.
The sigma-point filters retain their pairwise state smoother. Its conditional means need not equal the information smoother’s means, even in a linear switching model. Likelihoods and regime probabilities remain comparison controls; a single regime and identical-regime examples retain exact references.
15.8.1. Compatibility with stored classical output
A stored legacy run can have used a classical backward pass separately within
each regime. Its conditional state estimates are then not the output of the
published switching information recursion. An explicit crskfc call with its
last argument false retains that classical state pass for comparison. This is
not an automatic replacement for the production smoother.
Transition dates must also be matched: a historical incoming-date probability pass and the corrected outgoing-date pass give different results when the transition matrix varies. The validation controls retain strict comparisons to legacy under its recorded method/date convention, while the production checks retain the published formula, exact controls and correct transition dating.
In the retained time-varying-transition reference cases, this date convention alone changes smoothed regime probabilities by up to about 0.1. Matching the historical date recovers its probabilities to about 1e-8, but does not make the published conditional state means equal to the classical ones. The comparison therefore records both the state method and the probability date explicitly.
15.9. Observable contribution storage
observables_decomposition returns full requested observation weights, then
contributions by observable. For constant state-space matrices, weight
construction processes at most 64 input columns at a time. Forward and backward
linear weight recursions retain their existing meaning, including missing-data
gains; full unrequested intermediate weight matrices are avoided. Applying those
weights uses at most 256 output rows at a time and preserves interleaved variable
ordering. Only floating-point summation order can change. This path does not
change model equations, calibration or the filtering algorithm.
Requested full weights still require storage quadratic in sample length. There
is no streamed or sparse first output. Select only the quantities required;
requesting all of them still stores all returned matrices. Debug calls and calls
with time-varying state-space matrices use the existing construction. This
change makes no claim about regime-switching models. The runnable companion
WorkingWithAModel/observable_contributions_example calls the public method
on a supplied model and data.