27. Forecasting and simulation
Once a model is solved, the two main entry points for forward-looking
analysis are simulate and forecast. Both return
structs of ts time-series objects keyed by endogenous-variable
name and respect the model’s regime structure when there is one.
For deterministic scenarios, perfect_foresight is the
third entry point.
All three consume the same simulation plan – the universal mechanism for choosing initial conditions, pinning endogenous variables, activating shocks, announcing anticipated shocks, or imposing algebraic constraints. This chapter is the reference for the three consumers. It assumes you have read Simulation plans; the constructions used below are all from that chapter.
27.1. simulate
simulate propagates the perturbation solution forward
through a plan. With no plan it draws an unconditional path:
sim = simulate(m, simul_periods = 200);
plot(sim.PAI, sim.Y);
With a plan, every choice on that path is the plan’s: pinned
shocks stay pinned, NaN shocks are backed out, pinned
endogenous variables hit their conditioning values, anticipated
shocks act through the perturbation solution’s anticipation
horizon:
sp = simplan(m, [rq(2020,1), rq(2030,4)], 1, 'shockInit', 'zero');
sp = append(sp, 'EETA', rq(2020,2), 2.0);
sim = simulate(m, simul_historical_data = sp);
For a single-regime constant-parameter model, sim is a struct
of ts keyed by endogenous-variable name. For a
regime-switching model the output structure depends on
simul_to_time_series (see below).
27.1.1. Starting from history
A plain database of history, with the last date of that history in
simul_history_end_date, starts the simulation at that date:
sim = simulate(m, simul_historical_data = db, ...
simul_history_end_date = rq(2019,4), simul_periods = 12);
simulate builds the plan simplan.from_history(m, db, rq(2019,4),
12) itself, as forecast does: the initial conditions are the data
at that date, the lags come from the dates before it, and the data after
it are not used. The shocks are drawn when simul_shock_uncertainty
is true (the constraint-enforcing shocks excepted) and are at their
steady state otherwise. For a first-order model with anticipated shocks
and data that carry an observable of the model, the pages of the
announcements at that date are those the filter updates from the data,
each parameterization with its own, and the shocks drawn are revisions
of these pages (see How an announcement evolves: pages and revisions). The regime at that date is the database’s
regime series when it has one, else the regime the filter finds most
likely there given the data, each parameterization with its own filter. A
parameterization whose filter fails returns its retcode and no path. The
regime is drawn from the initial distribution only when the data carry no
observable of the model. Conditions over the horizon belong in a plan
(append), built with simplan.from_history directly.
A database that starts at simul_history_end_date is a conditioning
database: its first date gives the initial conditions and its later
dates condition the simulation, as without the option. A date before the
data (RISE:simulate:historyEndBeforeData), after them
(RISE:simplan:historyEndOutsideData) or of another frequency
(RISE:simulate:historyEndFrequency) is an error, and so is a
database with several pages (RISE:simulate:historyEndWithPages),
whose conditions a plan generated from the history would not read.
27.1.2. Common options
Option |
Effect |
|---|---|
|
Number of periods to simulate. Empty (the default) means |
|
Burn-in periods simulated before the returned ones and discarded, so that the path does not start at the steady state. Default |
|
When |
|
When |
|
Initial conditions and / or a conditioning path. Accepts a struct of |
|
Last date of the history segment (the point from which the simulation continues forward). With a plain database whose history runs past its first date, the simulation jumps off at this date from a plan generated out of the history (see “Starting from history”). Inferred from the plan when one is passed. |
|
Pin the regime path. Pass an integer for a constant regime, a vector for a fixed path, or a function handle for a state-dependent switch rule. A plan may fix regimes too ( |
|
When |
|
Output shape – see below. Default |
simulate draws from MATLAB’s global random stream. To reproduce a
simulation, call rng(seed) immediately before simulate: the same
seed gives the same draws on the same MATLAB setup.
A simulation plan in simul_historical_data sets the start, the
horizon, the initial conditions and the regimes, for simulate,
forecast and perfect_foresight alike. simul_periods,
simul_history_end_date or simul_burn passed in the same call with
another value than the plan’s is an error
(RISE:simulation:planConflict). A value the plan agrees with is
accepted.
27.1.3. Output shape
By default (simul_to_time_series = true) the output is a struct
of ts keyed by variable name. For switching models with multiple
parameterizations or solution branches, the underlying numeric
representation has extra dimensions for parameterization and
regime path; the ts object carries them in its pages.
When you need the raw numeric arrays – for instance to feed into a
hand-rolled diagnostic – set simul_to_time_series = false:
[raw,states,retcode]=simulate(m,simul_periods=200,simul_to_time_series=false);
The outputs are the same three as by default; only the first changes
form. raw is then a cell of two elements. raw{1} is the
numeric array, time by variable by anticipation page by solution.
raw{2} labels it: a 4-by-2 cell whose second column gives the
start date, the names of the columns of raw{1} (the endogenous
variables, then the shocks, the regime, the state of each Markov
chain and the transition probabilities), the number of anticipation
pages and the number of solutions – what is needed to rebuild the
ts. states is the regime path, as below.
Note
Even with simul_to_time_series = true, regime-switching
simulations can in some configurations return a numeric matrix
rather than a ts struct (an artifact of the underlying
solution shape). Confirm with isstruct(sim) before reaching
for sim.varname; if you got a matrix, the columns are the
variables in the order returned by get(m, 'endo_list').
27.1.4. Measurement errors
When the model has measurement errors (stderr_<observable>
parameters), simulate draws them too and returns each observable
as a complex series: the real part is the model’s value, the imaginary
part the measurement error. The data an econometrician would see is
their sum:
db = simulate(m, simul_periods = 200);
x = double(db.x);
x_model = real(x); % the model's variable
x_error = imag(x); % the measurement error
x_data = x_model + x_error; % what is observed
The other variables have a zero imaginary part. To filter or estimate on
simulated data, pass the sum as the data: filter and estimate
refuse complex data with the error rise:data:complex, which names the
series.
27.1.5. Returning the regime path
simulate returns the realized composite-regime sequence
as its second output:
[sim, states] = simulate(m, simul_periods = 200);
states is a vector of integer regime IDs over the simulation
horizon. Plot it to see when each regime was active.
27.2. Theoretical and sample moments
The second moments of the first-order solution are available in
closed form, through the Lyapunov equation, from
theoretical_autocovariances and the
theoretical_autocorrelations wrapper. Both take the model and
options; the number of lags is an option (autocov_ar and
autocorr_ar, default 5):
[Acov,retcode]=theoretical_autocovariances(m,autocov_ar=10);
Acorr=theoretical_autocorrelations(m,autocorr_ar=10);
Acov is a cell with one element per regime; Acov{i}(:,:,1)
is the variance and Acov{i}(:,:,k+1) the autocovariance at lag
k, with the variables in the order of get(m, 'endo_list')
(autocov_list selects a subset). Under regime switching the
element of regime i is the autocovariance the model would have
if regime i prevailed throughout; autocov_aggregate = true
returns instead a single element, the unconditional autocovariances
of the switching process, which average over the regime paths.
These moments use the first-order solution only. At higher order,
simulate a long (pruned) path and compute sample moments from the
ts (mean, var, cov, corrcoef are overloaded on
ts); at order 1 the two agree up to Monte Carlo error.
The variance-decomposition routine is documented in the legacy chapter Master stoch simul and remains canonical for the modern toolbox.
27.3. Pruned simulations (higher order)
RISE solves and simulates regime-switching DSGE models up to
fifth-order perturbation. At order \(\geq 2\) a straight
perturbation simulation is not guaranteed to be bounded: the
policy is a polynomial in the state, and iterating it forward lets the
higher-order terms feed on themselves, so an unlucky shock sequence can
send the state off to inf. Pruning (Andreasen, Fernández-Villaverde
and Rubio-Ramírez, 2018, generalized here to regime switching) removes
those spurious higher-order terms at simulation time without changing
the policy function, keeping the path bounded and the implied moments
well defined.
Pruning is controlled by the simul_pruned option, honored by
simulate, irf, forecast and any path that iterates the
solution forward:
sim = simulate(m, simul_periods = 200, simul_pruned = true);
simul_pruned accepts:
false(default) — no pruning;true— prune with the built-in automatic scheme (one_step_pruning_automatic);the name of a pruning routine (
'one_step_pruning'or'one_step_pruning_automatic'), or a function handle, to select a specific scheme.
Pruning applies only at order \(\geq 2\) (at order 1 the recursion is already linear and bounded) and is implemented up to order 5.
Note
Pruning changes the object you simulate: the pruned recursion is a stabilized companion of the policy, not the policy itself. It is the right tool for moments and long simulations at high order, but it is a modeling choice — an order-\(\geq 2\) path that explodes without pruning is often telling you that perturbation is being pushed outside its region of validity, where a global method (Taylor projection, Extending RISE through paradigms) may be the better answer. See Solution accuracy for how pruning interacts with the accuracy measures.
A simulation stops at the first step whose values are not finite or are
complex: an exploding unpruned path, or a paradigm step that failed (an
OccBin step without a verified binding pattern returns NaN). simulate
then returns no database, with return code 704 (SIMUL_INVALID), and its
diagnosis (the warning rise:diagnose:simulation) says in which period
and for which variables the path died. irf returns no responses, with
the same code. Neither returns paths of non-finite numbers, so check the
return code before using the result:
[db, ~, retcode] = simulate(m, simul_periods = 200);
if retcode
disp(decipher(retcode))
end
27.4. forecast
forecast produces forward paths from the end of history,
with or without conditions and with or without shock uncertainty.
The unconditional case is the trivial one:
fkst = forecast(m, ...
simul_periods = 12, ...
simul_shock_uncertainty = true);
The conditional case is where forecast earns its keep. The
conditioning is supplied through a simulation plan passed in simul_historical_data:
sp = simplan(m, [rq(2020,1), rq(2030,4)], 1, 'shockInit', 'zero');
sp = append(sp, 'ER', cond_dates, NaN); % activate
sp = append(sp, 'PAI', cond_dates, PAI_target); % condition
fkst = forecast(m, simul_historical_data = sp);
The plan alone carries the conditioning – the conditioned
variables and the freed shocks are read from it, so no separate
list of conditioned variables is needed. It also sets the start and
the horizon, here from 2020Q1 to 2030Q4, so the call gives neither
simul_history_end_date nor simul_periods.
Two knobs matter at the consumer side:
Anticipated vs unanticipated – per-condition, encoded in the plan’s pages. Page
1is contemporaneous (unanticipated); pagekis announced \(k-1\) periods ahead. The perturbation solution honors the announcement horizon as long asanticipationHorizoncovered it at plan construction.Surprises vs no surprises –
simul_shock_uncertainty. Left empty (the default) orfalse,forecastdraws no shocks and uses the plan’s shocks as they are.truedraws the shocks the plan does not set: those noappendorfree_shocksgave a value and no'shockInit'set at construction, the constraint-enforcing shocks excepted. The plan above, built with'shockInit', 'zero', sets every shock, sotruedraws nothing from it; build the plan without'shockInit'to leave its other shocks to the draws. A forecast from a plain database (or the estimation data) runs on the plansimplan.from_historygenerates, whose shocks are drawn undertrueas well, the constraint-enforcing shocks excepted.
27.4.1. Start, horizon and regimes
Without a plan, forecast starts after simul_history_end_date,
the last date of history. Left empty, that date is the last one at
which the data (simul_historical_data, else the estimation data)
observe a variable of the model. The output starts at that date and
runs simul_periods periods further, 12 when simul_periods is
empty. To start earlier, give the last date of history:
fkst = forecast(m, simul_historical_data = db, ...
simul_history_end_date = rq(2019,4));
The initial conditions and the lags are read from the data at that
date, through the plan simplan.from_history builds, and the data
after it are not used. Without data or a plan, the forecast starts
from the steady state. A forecast has no burn-in: simul_burn
above 0 is an error (RISE:forecast:burnIn).
In a switching model, the forecast starts in the plan’s regime, else
in the one of a regime series of the data, else in the regime the
filter finds most likely at the last date of history, each
parameterization with its own filter. A parameterization whose filter
fails returns its retcode, with no forecast. When the data carry no
observable of the model, the starting regime must come from a
regime series, a numeric simul_regime or a plan: otherwise
forecast stops with RISE:forecast:noStartingRegime. Over the
horizon, forecast holds the regime it starts in at every date the
plan leaves free, so a forecast without shock uncertainty is one
deterministic path. simul_stochastic_regimes = true draws the
regimes from the transition probabilities instead.
27.4.2. Hard and soft conditions
A hard condition pins a variable to a specific value at a specific date. The counting rule (see Simulation plans), at least as many free shocks as conditions at each date, is necessary for a plan to be solvable, not sufficient: the free shocks must also move the conditioned variables independently of one another, and the conditions must be reachable. Check the return code.
A soft condition restricts a variable to a band [lo hi]
appended to the plan (see Simulation plans for the band
syntax and free_shocks). Because the conditioned variable is
moved through the freed shock(s), the model assigns it a predictive
distribution at the conditioning date – a normal
\(N(a,\sigma^2)\) whose mean \(a\) is the deterministic
forecast (the freed shocks at zero, the shocks the plan fixes at
their values) and whose standard deviation \(\sigma\) comes from
the freed shocks’ impulse responses. Both are conditioned on the
other hard conditions of the plan, which the freed shocks must meet
as well. That normal law is exact when the transition is affine in the
shocks (a linear model, or a first-order solution, in one regime). For a
solution of order two or more, or a model with regime switching, the
predictive distribution is not normal, and the law used is a local Gaussian
approximation: the deterministic path with the responses to unit impulses on
it, which does not integrate the curvature or the uncertainty about the
regimes. The band truncates that distribution. Several bands
truncate the joint distribution of their variables, with the
correlations the model gives them: they are drawn together (by a
Gibbs sampler), not one at a time, and bands that the freed shocks
cannot meet at once are refused
(rise:soft_density:incompatibleBands). A band far in a tail is
drawn as accurately as one near the forecast. The
simul_soft_conditioning option chooses what is returned:
'density'(the default once a band is present) runssimul_nsimplans – each a draw from the truncated distribution, pinned and solved as a hard condition – and returns the propagated ensemble.fanchartthen collapses it (below).'mean'returns a single path, the conditional mean (the mean of that ensemble).
Where the band sits relative to the forecast \(a\) is what
matters. A band that straddles \(a\) is mildly truncated and
roughly symmetric. An off-center band clips one tail, so the
distribution is asymmetric and its mean, its median and the hard
pin at the midpoint are three different numbers. A one-sided
band – a floor [lo NaN] – gives a strongly skewed,
zero-lower-bound-style pile-up at the bound. A hard pin discards
this; the soft condition keeps the model’s view of where in the
band the variable is likely to sit:
sp = simplan(m, [rq(2020,1), rq(2023,1)], 1, 'shockInit', 'zero');
sp = free_shocks(sp, 'EPS_D', rq(2020,2)); % free the channel
sp = append(sp, {'Y', rq(2020,2), [0.10 0.70]}); % an off-center band
fkst = forecast(m, simul_historical_data = sp, ...
simul_soft_conditioning = 'density', ...
simul_nsim = 2000);
Setting simul_soft_conditioning = 'mean' instead returns the
single conditional-mean path for the same plan.
27.4.3. The option surface
Option |
Effect |
|---|---|
|
Number of forecasting steps. Empty (the default) means |
|
Last date of history; the forecast starts after it. Empty (the default) means the last date at which the data observe a variable of the model. A simulation plan sets its own start. |
|
Draw the shocks over the forecast horizon. Empty (the default) means no shocks. With a simulation plan, |
|
Draw the regimes over the forecast horizon. Empty (the default) or |
|
How a band |
|
Number of draws/plans in |
|
When |
|
The history-plus-conditioning database. May be a |
27.5. perfect_foresight
perfect_foresight solves the full nonlinear model as a
boundary-value problem over the plan’s horizon. The plan supplies
the boundary data; the solver returns a deterministic path
consistent with every condition in the plan and with the model
equations at every period, without the perturbation
approximation:
pfs = perfect_foresight(m, simul_historical_data = sp);
The shocks come from the plan only: perfect_foresight draws no
random shocks unless simul_shock_uncertainty is true, which
draws the shocks the plan does not set (without a plan, the shocks of
the horizon). Without a plan, simul_periods sets the horizon; empty
(the default) means 100 periods.
Because perfect_foresight and simulate consume the
same plan, a side-by-side comparison is the canonical check on
the approximation error of the perturbation solution: when the
two outputs agree, the deviation is small enough that the
nonlinearity does not matter for the scenario; when they diverge,
the nonlinear path is the accurate one and the perturbation path
is the local approximation.
Occasionally-binding constraints are honored exactly by
perfect_foresight; see
Occasionally-binding constraints
for the deterministic-OBC patterns.
27.6. Fan charts
A forecast that carries multiple draws – the 'density' soft
conditioning above, or stochastic forecasts drawn with
simul_shock_uncertainty = true – is collapsed into central
tendency and probability bands by fanchart and
plot_fanchart:
fkst = forecast(m, simul_historical_data = sp, ...
simul_soft_conditioning = 'density', ...
simul_nsim = 1000);
out = fanchart(fkst.PAI, [30 50 68 90]);
plot_fanchart(out, [244 122 66]/255);
The percentages are the central probability mass enclosed by each band. The plotting tools live in the legacy chapter Plotting tools and apply unchanged to the modern toolbox.
27.7. Relative-entropy tilting
Relative-entropy tilting is a fourth mechanism, distinct from
the plan-based routes above: it does not produce a new forecast
path; it reweights an existing forecast ensemble (e.g. forecasts
drawn with forecast(..., simul_shock_uncertainty = true))
so that its moments satisfy a user-specified constraint.
The algorithm and its option surface are documented in the legacy chapter Conditional forecasting Using Relative Entropy. Use it when you already have an unconditional ensemble and want to constrain its moments (e.g. “the mean inflation forecast over the next 8 quarters equals 2%”) rather than its paths.
27.8. Smoother-based conditional forecasts
For linear models with conditions on observed variables, the
Kalman smoother imputes the conditioning path directly from the
data, without a simulation plan – treat the conditioning values
as observations on the forecast horizon, mark every other
observable as NaN for those dates, and run filter.
The output is the smoothed path for every endogenous variable.
This route is based on least squares and inherits its tradeoffs. It is documented in Filtering; use it when the conditions are observed-side and the model is linear. For anything else – hard endogenous constraints on unobserved states, nonlinear solutions, regime switching, anticipated shocks, soft conditions – use a simulation plan.
27.9. See also
Simulation plans – the construction reference (this chapter is its consumer side).
Filtering – the smoother-based alternative for linear observed-side conditioning.
Deterministic and quasi-deterministic solutions – the deterministic context in full.
Occasionally-binding constraints – scenarios with OBC.
Solution accuracy – how pruning interacts with the Euler-error accuracy measures.
Surprises and announcements – when an impulse response hits (
irf_shock_date) and whether agents act on its announcement (irf_anticipate).Impulse responses from an observed history – impulse responses that start from a dated history (
irf_initial_conditions), every lag read at its own date.Regimes in generalized responses – the starting and impact regimes of a generalized response, and how its two paths get their regimes (
irf_girf_regime_uncertainty).Legacy Master stoch simul – variance decomposition and the impulse-response surface (
irf_type,irf_periods,irf_shock_sign, generalized IRFs, anticipation horizons).Legacy Resimulation and counterfactuals – the
rise.engine.resim_bridgesurface for Viterbi / FFBS regime histories, counterfactual shock kills, Shapley shock decomposition.Legacy Plotting tools –
quick_irfs,fanchart,plot_fanchart, and the multi-panel layouts.