Skip to content

DSGE & model solution

The classes and functions of the row "DSGE & model solution" of Analytical tools, with what calls return (the results and their methods: forecasts, impulse responses, tests). Import them from pymetrix (from pymetrix import ...) unless a heading names another module. Parameters and return types are in each signature; the text says what each does.

Help topics: Dynare files: measurement errors, generalised priors and macros, The gradient of a model's likelihood, Forward-looking models, Bayesian VARs, State space and the Kalman filter, The particle smoother, The forecast workflow, Solving models, Second- and third-order solutions, Global sensitivity analysis: prior stability mapping, The quarterly projection model (QPM).

How do I: Bring an IRIS or Dynare model across, then check and solve it, Build a QPM forecast for a small open economy.

From a plugin: pymetrix-ha has more for this area.

Classes

FirstOrder dataclass

FirstOrder(growth: Annotated[bool, Widget('checkbox', help='a trending model: linearise around its balanced growth path, not a constant steady state')] = False)

Models with expectations, approximated to first order around the steady state (linearised and solved by QZ).

Every exogenous variable is a shock. Shocks and exogenous paths are anticipated (known from the first simulated period) unless the scenario names them unanticipated; targets can be held with free shocks (exogenize and endogenize). Exact for linear models; for nonlinear ones, accurate near the steady state.

Identification dataclass

Identification(names: tuple[str, ...], at: Mapping[str, float], jacobian: ndarray, rank: int, singular_values: ndarray, sensitivity: ndarray, collinearity: ndarray, closest: tuple[str, ...], lags: int, pairwise: ndarray | None = None, elasticity: bool = False, provenance: Any = None)

Iskrev's identification test at a point: see the module docstring.

problems property

problems: tuple[str, ...]

Parameters that move no moment, or that move them only as others do.

LinearModel dataclass

LinearModel(A0: ndarray, A1: ndarray, A2: ndarray, B: ndarray, variables: tuple[str, ...], shocks: tuple[str, ...], steady: SteadyState, observed: tuple[str, ...] = (), c: ndarray | None = None)

A0 E[x(t+1)] + A1 x(t) + A2 x(t-1) + B e(t) = 0 in deviations from the steady state.

solve

solve(start: LinearSolution | None = None) -> LinearSolution

The unique stable solution x(t) = P x(t-1) + Q e(t) (Blanchard-Kahn checked).

start: a solution of the same model at nearby parameter values (the previous draw of an estimation). The solution is then found by iterating P = -(A0 P + A1)^-1 A2 from it, much cheaper than the generalised Schur form on a large model, and checked: its own roots stable, the model's other roots explosive. If the iteration is slow or a check fails, the Schur form is used, as without start.

roots

roots() -> tuple[ndarray, int]

The generalised eigenvalues of the model's pencil (inf for infinite ones) and the number of predetermined variables: a unique stable solution has exactly that many roots inside the unit circle (Blanchard-Kahn). Found without solving, so they are there to see when the conditions fail.

MeasurementMap dataclass

MeasurementMap(equations: Sequence[str], params: Mapping[str, float] = dict(), errors: Mapping[str, float] = dict(), sources: Mapping[str, str] = dict(), units: Mapping[str, str] = dict(), labels: Mapping[str, str] = dict(), trends: Mapping[str, str] = dict(), trend_base: str | None = None, transforms: Mapping[str, str] = dict(), reported: Sequence[str] = (), error_corr: Mapping[Any, float] = dict())

Observed series as functions of model variables: see the module docstring.

direct classmethod

direct(observables: Sequence[str], errors: Mapping[str, float] | None = None, error_corr: Mapping[Any, float] | None = None) -> MeasurementMap

Model variables observed as they are, in levels: x = x for each.

error_covariance

error_covariance() -> ndarray

The measurement errors' covariance (observables x observables): D C D, D the errors' standard deviations and C their correlations (error_corr), which must be positive semi-definite.

variables

variables() -> frozenset[str]

The model variables the measurements use.

source

source(observable: str) -> str

The data series behind an observed series: its own name, the one in sources, or with a transform, the raw series the transform rebuilds.

data_series

data_series() -> tuple[str, ...]

Every data series the observed series are made from.

observed

observed(data: Any, span: Any = None) -> DataFrame

The observed series in the model's units, made from data: each its data series (sources), or its transform of raw series. A frame on the data's periods (within span).

reported_values

reported_values(data: Any) -> DataFrame

The reported series (reported) from model paths (a Solution or a dataset of the model's variables).

with_reported

with_reported(frame: DataFrame) -> DataFrame

frame (model variables in levels, by period) with the reported series added: for smoothed histories.

reverse

reverse(observed: DataFrame, data: Any) -> DataFrame

The raw series rebuilt from observed ones (transforms): where observed has a value and the data do not (a forecast, beyond the data), each period the transform is solved for the raw series, given its past and the other series it uses. Columns: the raw series; rows: observed's periods. See the module docstring.

report

report(paths: Any, data: Any = None) -> Any

Model paths in the units of the data: the observed series (apply), the reported ones, and with data and transforms, the raw series rebuilt beyond the data (reverse). A Dataset.

with_errors

with_errors(errors: Mapping[str, float], error_corr: Mapping[Any, float] | None = None) -> MeasurementMap

The same map with these measurement-error sizes, and these correlations of them added (the equations are not parsed again: estimation calls this at every trial value).

trend_values

trend_values(index: Any) -> ndarray

The deterministic trends of the observed series in these periods (periods x observables; zero for series without one): ttrend counts periods from trend_base.

apply

apply(data: Any) -> Any

The observed series implied by model paths (a Solution or any dataset of the model's variables), in the units of the data: evaluated exactly, not linearised.

linearize

linearize(states: Sequence[tuple[str, int]], steady: Mapping[str, float]) -> tuple[ndarray, ndarray]

Z and d such that observed ≈ d + Z (state deviations), around the steady state: each state is a model variable at a lag, (name, lag). Exact when the measurement equations are linear.

summary

summary() -> Table

The measurement equations as a table, as table() gives them: what every result answers.

Posterior dataclass

Posterior(fit: Any, names: tuple[str, ...], draws: ndarray, logpost: ndarray, acceptance: ndarray, scale: ndarray, burn: int, seed: int | None = None, coverage: float = 0.9, _cache: dict = dict(), modes: Any = None, jumps: Any = None, jump: float = 0.0, sampler: str = 'mh', smc: Any = None, nuts: Any = None, random_generator: str = (lambda: get_random_generator())())

Draws from the posterior of a linearised model's parameters: see the module docstring.

provenance property

provenance: Any

The estimate's provenance, with the sampler: draws, chains, burn-in, seed and acceptance.

mcse

mcse(quantiles: Sequence[float] = (0.05, 0.5, 0.95), method: str = 'ess') -> Table

Monte Carlo standard errors of each parameter's posterior mean and quantiles, with the effective sample size: from the chains' autocorrelations (method="ess") or batch means ("batch"); for sequential Monte Carlo, from the particles' effective sample size. Small beside the standard deviation: enough draws.

laplace

laplace() -> float

Log marginal data density by the Laplace approximation at the posterior mode.

marginal_likelihood

marginal_likelihood(truncations: tuple[float, ...] = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9), method: str | None = None) -> float

Log marginal data density: from sequential Monte Carlo's incremental weights when sampled that way, otherwise (or with method="mhm") Geweke's modified harmonic mean, averaged over the truncations.

forecast

forecast(span: tuple[Any, Any], scenario: Any = None, data: Any = None, tunes: Any = None, draws: int = 500, shocks: bool = True, seed: int | None = 0, occbin: bool | None = None, regimes: Any = None, measurement_errors: bool = False) -> Any

Forecasts with parameter uncertainty: the forecast at the posterior mode (fit.forecast), with draws at draws posterior draws spread over the chains. At each, the model is solved and its variables filtered from the data again (their starting values depend on the parameters), and one path of its shocks is drawn (shocks=False: parameter uncertainty alone); observed series through the measurement equations, with measurement errors drawn too when measurement_errors (from each draw's measurement-error covariance; off by default, as before). Solution.fan, quantiles and bands summarise them. occbin: the model's occasionally binding constraints respected at every draw (the OccBin filter's state and OccBin's forecast at that draw's parameters); default: when the model was estimated with the OccBin filter. A model estimated with known-date regimes is solved at each draw with that draw's values of the regimes' parameters (phi_pi@post), filtered through their time-varying rules and forecast through them; regimes adds others in the forecast, as FittedModel.forecast. See pymetrix.models.stochastic.

irf

irf(periods: int = 20, draws: int = 200, coverage: float | None = None) -> Any

Impulse responses to one-standard-deviation shocks at draws draws spread over the chains: the posterior median, with the central coverage band (an IRF).

plot

plot() -> Any

Prior (dashed) and posterior densities of each parameter.

trace

trace() -> Any

The kept draws of each parameter, chain by chain.

Regime dataclass

Regime(start: Any, params: Mapping[str, float] = dict(), equations: Mapping[str, str] = dict(), name: str = '', end: Any = None, expected: bool = True, description: str = '')

Parameter values (params) and equations replaced by name (equations) from period start on: see the module docstring. end: the last period of a temporary regime, after which the regime before it resumes. expected=False: a surprise, unknown until it starts and then believed permanent. description: what it is, for people (a model text's quoted description of the regime).

label property

label: str

The regime's name, or its start when it has none.

Functions

occbin

occbin(obj: Any, shocks: Mapping[str, Any], periods: int = 40, anticipated: bool = False, horizon: int | None = None, shock_names: Sequence[str] | None = None, initial: Mapping[str, float] | None = None, max_iter: int = 100, regimes: Any = None) -> OccBinPath

The piecewise-linear path of obj (a template, a Dynare or IRIS model, or a Model) after shocks ({"ey": {1: -3.0}}: shock ey of -3 in period 1; or a list of values from period 1): see the module docstring. initial gives starting levels (default: the steady state); horizon how far ahead each solution looks. regimes: parameters or equations that change at known periods (Regime(5, {"phi_pi": 2.0}), or text such as "5..8: rho=1"; periods numbered from 1), known in advance (or surprises, expected=False: "5 surprise: rho=1"), combined with the constraints: each period's matrices are those of its known regime and of the constraints' regime (see _Piecewise).

occbin_filter

occbin_filter(obj: Any, data: Any, measurement: Any = None, shock_sd: Mapping[str, float] | None = None, span: Any = None, start: str = 'auto', horizon: int = 40, presample: int = 0, shocks: Sequence[str] | None = None, smoother: str = 'filter', regimes: Any = None, shock_corr: Mapping[Any, float] | None = None) -> OccBinFilter

The OccBin filter and smoother of obj (a template, a Dynare or IRIS model, a fitted model, or a Model with measurement and shocks) on data: see the module docstring. shock_sd gives shock sizes (default: the object's); horizon how far ahead each period's regimes are worked out; presample periods are filtered but left out of the likelihood. smoother: "filter" smooths with the regimes the filter chose; "iterated" works them out again on the smoothed path until they settle, as Dynare 6's OccBin smoother. regimes: known-date regimes in the sample (pymetrix.models.regimes; default: a fitted model's own, or a template's that start by the sample's end), combined with the constraints: each period's matrices are those of its known regime and of the constraints' regime. shock_corr: the shocks' correlations (default: the object's), the filter's shock covariance in full.

parse_regimes

parse_regimes(text: str) -> tuple[Regime, ...]

Regimes written as text, as the dialogs take them: "2009Q1: phi_pi=1.2; 2025Q1..2026Q4: rho=1, phi_pi=0". Each item is a start (or start..end, a temporary regime), a colon and parameter values; items are separated by ; or new lines. surprise after the period makes it a surprise (expected=False): "2026Q1 surprise: phi_pi=2".

particle_filter

particle_filter(solution: Any, data: Any, measurement: Any, shock_sd: Mapping[str, float] | None = None, span: Any = None, particles: int = 2000, seed: int | None = 0, resample: float = 0.5, proposal: str = 'bootstrap', burn: int | None = None, presample: int = 0, quantiles: Sequence[float] = (0.05, 0.5, 0.95), shock_corr: Mapping[Any, float] | None = None, measurement_sd: Mapping[str, float] | None = None, smooth_paths: int = 0, candidates: int | None = 200) -> ParticleFilter

The particle filter of solution (a SecondOrderSolution, or a first-order LinearSolution with shock_sd) on data through measurement (a MeasurementMap, or model variables observed as they are, with measurement_sd): see the module docstring. smooth_paths: paths the particle smoother draws (backward simulation in the shocks, each period's particle among candidates drawn from the filter's, all with None), for smoothed, smoothed_quantiles and smoothed_shocks; 0 (the default) filters only. A ParticleFilter.

read_iris

read_iris(source: str | Path, params: Mapping[str, float] | None = None, guess: Mapping[str, float] | None = None, name: str | None = None, trend_base: str | None = None, growth: bool = False) -> Any

Read an IRIS model file (a path, or the file's text) into a Template: see the module docstring. growth=True for a model whose levels trend (a QPM's 100*log GDP and CPI): its steady state is then a balanced growth path.

read_mod

read_mod(source: str | Path) -> DynareModel

Read a Dynare .mod file (a path, or the file's text).

regime_filter

regime_filter(obj: Any, data: Any, regimes: Any = None, measurement: Any = None, shock_sd: Mapping[str, float] | None = None, span: Any = None, start: str = 'auto', presample: int = 0, shocks: Sequence[str] | None = None) -> RegimeFilter

The Kalman filter and smoother of obj (a fitted model, a template, a Dynare or IRIS model, or a Model with measurement and shocks) on data with known-date regimes (default: a fitted model's own, or a template's that start by the sample's end), the shocks correlated as the object's shock_corr: the smoothed variables, the regime of each period and the log likelihood. See pymetrix.models.regimes.

second_order

second_order(model: Any, shocks: Sequence[str], shock_sd: Mapping[str, float] | None = None, steady: Any = None, guess: Mapping[str, float] | None = None, shock_corr: Mapping[Any, float] | None = None) -> SecondOrderSolution

The second-order solution of model (a Model) with these shocks and sizes (and correlations, shock_corr: the risk terms take the full covariance, as Dynare's Sigma_e): see the module docstring.

stability_mapping

stability_mapping(source: Any, draws: int = 2000, seed: int | None = 0, priors: Mapping[str, Any] | None = None, params: Sequence[str] | None = None, pvalue_ks: float = 0.001) -> StabilityMapping

A prior stability mapping of a model (see pymetrix.models.sensitivity): draws draws of the parameters from their priors (a Dynare model's estimated_params, a model's or template's parameter specs, or priors), each classified as determinate, indeterminate, explosive, without a steady state or without a solution; and the Smirnov test of each parameter, determinate draws against the others. params: the parameters to draw (default: every model parameter with a prior).

third_order

third_order(model: Any, shocks: Sequence[str], shock_sd: Mapping[str, float] | None = None, steady: Any = None, guess: Mapping[str, float] | None = None, shock_corr: Mapping[Any, float] | None = None) -> ThirdOrderSolution

The third-order solution of model (a Model) with these shocks and sizes (and correlations, shock_corr, as Dynare's Sigma_e): see the module docstring.

Results

DynareModel dataclass

DynareModel(endogenous: tuple[str, ...], exogenous: tuple[str, ...], params: dict[str, float], equations: tuple[str, ...], initval: dict[str, float] = dict(), shock_sd: dict[str, float] = dict(), commands: tuple[str, ...] = (), source: str = '', model: Any = None, priors: dict[str, Any] = dict(), estimated: tuple[str, ...] = (), start: dict[str, float] = dict(), bounds: dict[str, tuple[float, float]] = dict(), varobs: tuple[str, ...] = (), options: dict[str, Any] = dict(), loglinear: bool = False, labels: dict[str, str] = dict(), measurement_sd: dict[str, float] = dict(), shock_corr: dict[tuple[str, str], float] = dict(), measurement_corr: dict[tuple[str, str], float] = dict())

A model read from a Dynare file, as a pymetrix Model with its calibration, guesses and shocks.

guess property

guess: dict[str, float]

Steady-state starting values for the model's variables (logs, for a log-linear model).

data

data(path: str | Path | None = None, start: str = '0001Q1') -> Any

The observed series (varobs) from the datafile of estimation(...) (or path): the sample first_obs and nobs select, logged for a log-linear model unless logdata is given. A Dataset with periods numbered from start.

estimate

estimate(data: Any = None, estimate: Any = None, priors: dict[str, Any] | None = None, **kwargs: Any) -> Any

Estimate the model as the file's estimation would: the estimated_params (or estimate) with their priors and bounds, fitted to varobs in data (default: the datafile). A FittedModel: the posterior mode with priors (then .mcmc(...)), maximum likelihood without.

dsge_var

dsge_var(data: Any = None, estimate: Any = None, priors: dict[str, Any] | None = None, lags: int | None = None, lambda_: Any = None, **kwargs: Any) -> Any

A DSGE-VAR as the file's estimation(dsge_var=..., dsge_varlag=...) asks (a FittedDSGEVAR; see pymetrix.models.dsge_var): dsge_var=<value> fixes lambda; dsge_var alone estimates it as the parameter dsge_prior_weight of estimated_params, with its prior; dsge_varlag gives the lags (4 by default). lags and lambda_ override them. The rest as estimate; the filter options do not apply.

mode_file

mode_file(path: str | Path | None = None) -> dict[str, float]

The values in a Dynare mode file (xparam1 in a .mat file; default: the mode_file option, next to the model file), named as estimated: shock sizes as sd_<shock>, in the order of estimated_params.

log_posterior

log_posterior(values: dict[str, float] | None = None, data: Any = None) -> float

The log posterior (log likelihood plus log priors) at these values of the estimated parameters (default: their initial values), as Dynare reports it with mode_compute=0: e.g. log_posterior(mode_file()). The filter's start and presample follow the estimation options; without priors, the log likelihood.

solve

solve(order: int = 1) -> Any

The rational-expectations solution, with every varexo as a shock: first order, or second order with the file's shock sizes (as stoch_simul(order=2)), or third order (as stoch_simul(order=3)).

FittedDSGEVAR dataclass

FittedDSGEVAR(fit: Any, lags: int, lambda_: float, lambda_choice: str, observables: tuple[str, ...], Y_all: ndarray, index: Any, grid: DataFrame | None = None, posterior: Any = None, lambda_prior: Any = None, _cache: dict = dict())

A DSGE-VAR(lambda): the model's parameters at their posterior mode (fit, a FittedModel whose likelihood is the DSGE-VAR's), and after mcmc their posterior draws (posterior); the VAR given them. See pymetrix.models.dsge_var.

lambda_min property

lambda_min: float

The smallest lambda with a proper prior: (k + n) / T.

provenance property

provenance: Any

The mode's provenance, with the sampler's after mcmc.

moments

moments(at: Mapping[str, float] | None = None) -> dict[str, DataFrame]

The model's population moments behind the prior at the mode (or at): G_yy, G_xy and G_xx (uncentred, the constant first).

var_prior

var_prior(at: Mapping[str, float] | None = None) -> tuple[DataFrame, DataFrame]

The prior's centre at the mode (or at): the model's VAR approximation Phi* (regressors x equations) and Sigma*.

var_posterior

var_posterior(at: Mapping[str, float] | None = None, lambda_: float | None = None) -> tuple[DataFrame, DataFrame]

The VAR's posterior given theta at the mode (or at) and lambda (or lambda_): the posterior mean of Phi and Sigma~ (the posterior's scale divided by (1 + lambda) T).

var_draws

var_draws(draws: int = 500, seed: int | None = 0) -> tuple[ndarray, ndarray]

Draws of the VAR's coefficients Phi (draws x k x n, regressors as regressors) and covariance Sigma (draws x n x n): one from the normal-inverse-Wishart posterior given each of draws draws of theta spread over the chains (after mcmc), or given theta at the mode.

irf

irf(periods: int = 20, draws: int = 500, coverage: float = 0.9, seed: int | None = 0) -> Any

Impulse responses of the observables to the model's shocks (one standard deviation), identified by the model's rotation: for each draw of theta (after mcmc; else at the mode) and of the VAR given it, the impact chol(Sigma) Omega(theta) (DS 2004). The median with the central coverage band (an IRF); draws=0: at the posterior mean given theta at the mode, without bands.

dsge_irf

dsge_irf(periods: int = 20, at: Mapping[str, float] | None = None) -> Any

The model's own responses of the observables to its shocks at the mode (or at), to set beside irf.

fevd

fevd(periods: int = 20) -> Any

Forecast-error variance decomposition of the observables by the model's shocks, at the posterior mean of the VAR given theta at the mode, with the model's rotation (an FEVD).

forecast

forecast(span: tuple[Any, Any], data: Any = None, draws: int = 500, coverage: float = 0.9, seed: int | None = 0) -> Any

Forecasts of the observables over span from the VAR's predictive distribution: each draw of (theta, Phi, Sigma) simulates a path with its own shocks, so the bands include parameter uncertainty. From the end of the estimation data, or of data (made into the observables by the measurement equations). Columns: mean, _se, _median and the coverage interval, _lower and _upper (as FittedBVAR.forecast).

mcmc

mcmc(draws: int = 10000, chains: int = 2, burn: int | None = None, scale: float | None = None, seed: int | None = 0, progress: Any = None, workers: int | str | None = 'auto', adapt: bool = True, modes: Any = None, jump: float = 0.05) -> FittedDSGEVAR

The posterior of theta (and lambda, when estimated) by random-walk Metropolis-Hastings from the mode, as FittedModel.mcmc (every parameter needs a prior; modes and jump as there): this DSGE-VAR with its posterior, so that irf, forecast and var_draws integrate over theta.

laplace

laplace() -> float

Log marginal data density p(Y | lambda) by the Laplace approximation at the mode (needs priors).

marginal_likelihood

marginal_likelihood() -> float

Log marginal data density: the modified harmonic mean of the draws after mcmc, else Laplace's.

lambdas

lambdas() -> Table

The log marginal data density at each lambda of the grid (lambda_="grid"), with the likelihood and the mode of theta at each: the hump whose top is lambda-hat.

lambda_plot

lambda_plot() -> Any

The log marginal data density against lambda (the hump), lambda-hat marked.

FittedModel dataclass

FittedModel(model: Any, params: Any, parameters: Any, shock_sd: Mapping[str, float], measurement: Any, solution: Any, system: Any, smoothed: Any, stats: Mapping[str, float], priors: Mapping[str, Any] = dict(), bounds: Mapping[str, tuple[float, float]] = dict(), method: str = 'maximum likelihood', provenance: Any = None, evaluate: Any = None, log_posterior: Any = None, data: Any = None, span: Any = None, regimes: tuple[Any, ...] = (), shock_corr: Mapping[tuple[str, str], float] = dict(), ahead: tuple[Any, ...] = (), nonlinear: Any = None, particle: Any = None)

A linearised model estimated from data: see the module docstring.

forecast

forecast(span: tuple[Any, Any], scenario: Any = None, data: Any = None, tunes: Any = None, draws: int | None = None, seed: int | None = 0, occbin: bool | None = None, tune_sd: Any = None, regimes: Any = None) -> Any

Forecasts from the end of the data: the model's variables start at their Kalman-smoothed values (from data if given, filtered again with the estimated model; otherwise the data it was estimated on), follow the solution under scenario (shock paths, anticipated or not; targets held by free shocks), and the observed series are added in the data's units through the measurement equations. tunes imposes judgement on the filtered variables ({"y": {"2024Q4": -1.0}}; give data with it), exact unless given a standard deviation (tune_sd, or a (value, sd) pair; see StateSpaceSystem.filter). A Solution. With draws, a stochastic simulation too: the estimated shocks drawn in each period of the span (at the estimates: parameters are not drawn), and the observed series of each draw (Solution.fan, quantiles).

occbin: the model's occasionally binding constraints (its max or min) respected, by OccBin from the OccBin-smoothed state (data filtered again with the OccBin filter); default: when the model was estimated with the OccBin filter. Scenarios give shock paths (set, shift), anticipated unless all are named unanticipated, and targets held by free shocks (hold, free: anticipated, without draws), solved for through the piecewise solution; draws are surprises in each period. Solution.provenance.method["binding"] says when each constraint binds.

regimes: parameters or equations that change at known dates in the forecast (Regime objects or text such as "2025Q1..2026Q4: rho=1, phi_pi=0"), after the model's own regimes (those it was estimated with, the last of which holds at the end of the data) and those after the sample it keeps (ahead, a template's); see pymetrix.models.regimes.

smc

smc(particles: int = 2000, steps: int = 2, ess_fraction: float = 0.5, seed: int | None = 0, progress: Any = None, workers: int | str | None = 'auto') -> Any

The posterior distribution by sequential Monte Carlo (a Posterior, as mcmc gives): particles from the prior moved to the posterior through tempered likelihoods, as Dynare 6's (Herbst and Schorfheide 2014), with the log marginal data density from the same run. More robust than Metropolis-Hastings where the posterior has several modes or ridges; every estimated parameter needs a prior. ess_fraction: the share of the particles the weights' conditional effective sample size is kept at in each tempering step (higher: more, smaller steps); target is its old name, deprecated. See pymetrix.models.bayes.smc.

decompose

decompose(start: str = 'first', occbin: bool | None = None) -> Any

The Kalman-smoothed history of the model's variables split into the contributions of each shock and of the starting point (a Decomposition); start as in LinearSolution.decompose. occbin (default: when the model was estimated with the OccBin filter): the OccBin-smoothed history, decomposed with the regimes held at the smoothed ones, the binding regimes' constants a part of their own (OccBinFilter.decompose). A model estimated with known-date regimes is decomposed through their time-varying rules, the regimes' constants a part of their own, "regimes" (RegimeFilter.decompose).

contributions

contributions(horizon: int = 0, data: Any = None, tunes: Any = None, tune_sd: Any = None) -> Any

How much each observed series (and each tune) contributed to the smoothed estimates of the model's variables, and with horizon to the forecast from the end of the data (a Decomposition): what moved the output gap, the GDP release or inflation? data: newer data, filtered with the estimated model.

moments

moments(lags: int = 4, regime: str | None = None) -> Any

Theoretical moments at the estimates, with the estimated shock sizes (Moments). A model estimated with known-date regimes has the moments of one regime at a time: regime names it (its name, or its start), held for good at its own steady state (its own stationary solution); default: the base model, before any regime.

fevd

fevd(periods: int = 20, regime: str | None = None) -> Any

Forecast-error variance decomposition at the estimates (an FEVD); regime as in moments.

mcmc

mcmc(draws: int = 10000, chains: int = 2, burn: int | None = None, scale: float | None = None, seed: int | None = 0, progress: Any = None, workers: int | str | None = 'auto', adapt: bool = True, modes: Any = None, jump: float = 0.05, sampler: str = 'rwmh', target_accept: float = 0.8, max_depth: int = 10, gradient: str = 'auto', metric: str = 'dense') -> Any

The posterior distribution by random-walk Metropolis-Hastings, started around the posterior mode (a Posterior). Every estimated parameter needs a prior. draws are kept per chain after burn (default: as many again, discarded, while the proposal's scale is tuned). workers: how many chains run at once in other processes (default: one per chain when the run is long enough to pay; 1 runs them here, one after another). The draws are the same either way. adapt: halfway through burn-in, the proposal takes the shape of the chain's own draws (see pymetrix.models.bayes). modes: other posterior modes to jump between ({name: value} each, or arrays in params.names order); by default the distinct modes the estimate's starts found (estimate(..., starts=n)), and modes=False for none. jump: the share of steps that propose a jump when there are several modes. sampler="nuts": the No-U-Turn sampler instead, target_accept and max_depth its settings (burn its warmup, workers as above; scale, adapt, modes and jump are Metropolis-Hastings's), with the analytic gradient of the Kalman filter's likelihood where it applies (gradient="auto"; "analytic" insists, "numerical" takes central differences; see pymetrix.models.kalman_score), and metric its mass matrix: "dense" (the default) or "diag" adapted in warmup from the inverse Hessian at the mode, or "mode" that inverse Hessian kept (a short warmup then suffices); see pymetrix.models.bayes_nuts.

gradient

gradient(at: Mapping[str, float] | None = None, method: str = 'analytic') -> DataFrame

The gradient of the log likelihood and of the log posterior in the estimated parameters, at the estimates or at at={name: value} (the others at the estimates): one row per parameter. method="analytic" differentiates the steady state, the solution and the Kalman filter exactly (pymetrix.models.kalman_score; refused where it does not apply); "numerical" takes central differences of the log posterior.

laplace

laplace() -> float

Log marginal data density by the Laplace approximation at the posterior mode (needs priors).

identification

identification(lags: int = 4, at: Any = None, elasticity: bool = False) -> Any

Whether the data's means and autocovariances (to lags) can tell the estimated parameters apart, at the estimates or at other values at={name: value} (an Identification: Iskrev's rank test, with sensitivities, collinearities and each parameter's closest pair). elasticity=True measures each moment's change relative to its size, so that the largest variances do not make every pair of parameters look alike. Model.identification and Template.identification give the same without data.

OccBinFilter dataclass

OccBinFilter(smoothed: Any, filtered: DataFrame, binding: DataFrame, ex_post: DataFrame, loglike: float, constraints: tuple[str, ...], iterations: int, observables: tuple[str, ...] = (), cycles: int = 0, smoother: str = 'filter', smoothed_binding: DataFrame | None = None, smoother_iterations: int = 0, smoother_cycled: bool = False, smoother_kept: int = 0, rules: Any = None, provenance: Any = None)

The OccBin filter's result: see the module docstring.

regimes property

regimes: DataFrame

When each constraint binds in the regimes the smoothed path was computed with: the filter's, or with smoother="iterated" those settled on the smoothed path.

decompose

decompose(orthogonal: bool = True) -> Any

The smoothed path split into the shocks' contributions, as a Decomposition: with the regimes held at those the smoother used, each shock's contribution and the starting point's go through the smoother's time-varying rules x(t) = c(t) + T(t) x(t-1) + R(t) e(t), and the constants c(t) of the binding regimes (where a constraint holds the variable, as a rate at its floor) are a part of their own, "binding constraints"; with known-date regimes, their constants are in that part too. The parts add up to the path exactly. In a model with a constraint the contributions depend on the regimes (the shocks' effects are not additive across regimes): this is the decomposition given the smoothed regimes. When nothing binds it is the linear decomposition. With correlated shocks the parts are of the shocks orthogonalised by the Cholesky factor of their covariance, in the model's order, as impulse responses are (orthogonal=False: of the shocks themselves).

plot

plot(variables: Sequence[str] | str | None = None) -> Any

The smoothed paths, with the periods in which a constraint binds shaded.

OccBinPath dataclass

OccBinPath(frame: DataFrame, deviations: DataFrame, binding: DataFrame, linear: DataFrame, shocks: DataFrame, constraints: tuple[str, ...], iterations: int, anticipated: bool = False, steady: Mapping[str, float] = dict(), provenance: Any = None)

A piecewise-linear path: see the module docstring.

plot

plot(variables: Sequence[str] | str | None = None) -> Any

Each variable with the constraints (solid) and without them (dashed).

ParticleFilter dataclass

ParticleFilter(loglike: float, loglike_path: Series, filtered: Any, quantiles: DataFrame, ess: Series, resampled: Series, particles: int, order: int, proposal: str = 'bootstrap', observables: tuple[str, ...] = (), seed: int | None = None, provenance: Any = None, smoothed: Any = None, smoothed_quantiles: DataFrame | None = None, smoothed_shocks: DataFrame | None = None, smooth_paths: int = 0)

A particle filter's result: see the module docstring.

to_frame

to_frame(view: str | None = None) -> DataFrame

The filtered means, or one of the result's views ("Quantiles", "Diagnostics", ...) as a frame.

RegimeFilter dataclass

RegimeFilter(smoothed: Any, filtered: DataFrame, regime: Series, loglike: float, observables: tuple[str, ...] = (), regimes: tuple[Regime, ...] = (), rules: Any = None)

The Kalman filter and smoother through known-date regimes: see pymetrix.models.regimes.

decompose

decompose(start: str = 'first', orthogonal: bool = True) -> Any

The smoothed path split into the shocks' contributions (a Decomposition) through the regimes' time-varying rules x(t) = k(t) + P(t) x(t-1) + Q(t) e(t): each shock's contribution and the starting point's go through the rules, and the regimes' constants k(t) (a regime with another steady state, or a rule away from its own) are a part of their own, "regimes"; the parts add up to the path. With no regime changing in the sample it is the linear decomposition (and the regimes' part zero). start as in LinearSolution.decompose; with correlated shocks, of the shocks orthogonalised by Cholesky as impulse responses are (orthogonal=False: of the shocks themselves).

SecondOrderSolution dataclass

SecondOrderSolution(variables: tuple[str, ...], endogenous: tuple[str, ...], states: tuple[str, ...], shocks: tuple[str, ...], ghx: ndarray, ghu: ndarray, ghxx: ndarray, ghxu: ndarray, ghuu: ndarray, ghs2: ndarray, sigma: ndarray, steady: Any, first: Any)

A second-order approximation of a model's decision rules: see the module docstring.

provenance cached property

provenance: Any

How it was made: the model's equations and parameter values, the shocks' covariance and the method. Worked out on first use, not stored, since solutions are made at every trial value of an estimation; no data (a model alone), so no sample or fingerprint.

mean

mean() -> Series

The ergodic mean of the pruned second-order process, in levels: the steady state plus the correction for risk (E[x] = (I - ghx_s)^-1 (1/2 ghxx vec(V) + 1/2 ghuu vec(Sigma) + 1/2 ghs2), V the first-order variance of the states).

simulate

simulate(periods: int, seed: int | None = 0, shocks: ndarray | None = None, burn: int = 0) -> DataFrame

A pruned stochastic simulation in levels, from the steady state (shocks: a periods x shocks array to use instead of draws; burn periods dropped first).

irf

irf(periods: int = 20, shock_sd: Mapping[str, float] | None = None) -> Any

Responses to one-standard-deviation shocks (or shock_sd) from the stochastic steady state (where the model rests when shocks are expected but none occur), as differences from staying there; an IRF. Unlike first-order responses they depend on the size and sign of the shock.

rules

rules() -> Table

The decision rules, Dynare style: the constant (half ghs2), then each term, for the model's variables.

particle_filter

particle_filter(data: Any, measurement: Any, span: Any = None, particles: int = 2000, seed: int | None = 0, resample: float = 0.5, proposal: str = 'bootstrap', burn: int | None = None, presample: int = 0, quantiles: Sequence[float] = (0.05, 0.5, 0.95), measurement_sd: Mapping[str, float] | None = None, smooth_paths: int = 0, candidates: int | None = 200) -> Any

The particle filter on data through measurement (each observed series with a measurement error): the log likelihood estimate and the filtered variables, following the pruned rules as simulate does; smooth_paths > 0 adds the particle smoother's paths (a ParticleFilter; see pymetrix.models.particle).

StabilityMapping dataclass

StabilityMapping(names: tuple[str, ...], draws: DataFrame, priors: Mapping[str, Any] = dict(), seed: Any = None, pvalue_ks: float = 0.001, provenance: Any = None)

A prior stability mapping: see the module docstring.

counts property

counts: Series

The number of draws in each class (all classes, zeros included).

shares property

shares: Series

The share of draws in each class.

smirnov property

smirnov: DataFrame

For each parameter: the Smirnov (two-sample Kolmogorov-Smirnov) statistic and p-value of its values in the determinate draws against all the others, the two counts, and whether the p-value is below pvalue_ks.

smirnov_by_class

smirnov_by_class() -> dict[str, DataFrame]

The same test of the determinate draws against each failing class that has draws ({class: table}).

table

table() -> Table

The Smirnov tests, determinate draws against the others.

plot

plot(columns: int = 3) -> Any

Each parameter's cumulative distribution in the determinate draws and in the others, one panel each.

ThirdOrderSolution dataclass

ThirdOrderSolution(variables: tuple[str, ...], endogenous: tuple[str, ...], states: tuple[str, ...], shocks: tuple[str, ...], ghx: ndarray, ghu: ndarray, ghxx: ndarray, ghxu: ndarray, ghuu: ndarray, ghs2: ndarray, ghxxx: ndarray, ghxxu: ndarray, ghxuu: ndarray, ghuuu: ndarray, ghxss: ndarray, ghuss: ndarray, ghsss: ndarray, sigma: ndarray, steady: Any, first: Any, derivatives: tuple[ndarray, ...] = ())

A third-order approximation of a model's decision rules: see the module docstring.

provenance cached property

provenance: Any

How it was made: the model's equations and parameter values, the shocks' covariance and the method. Worked out on first use, not stored, since solutions are made at every trial value of an estimation; no data (a model alone), so no sample or fingerprint.

mean

mean() -> Series

The ergodic mean of the pruned third-order process, in levels. It is the pruned second-order mean: the third-order part has mean zero when shocks are symmetric (Andreasen et al. 2018).

simulate

simulate(periods: int, seed: int | None = 0, shocks: ndarray | None = None, burn: int = 0, pruning: bool = True) -> DataFrame

A stochastic simulation in levels from the steady state (shocks: a periods x shocks array to use instead of draws; burn periods dropped first). Pruned unless pruning=False: the plain third-order rule can explode once shocks are large.

irf

irf(periods: int = 20, shock_sd: Mapping[str, float] | None = None, state: Mapping[str, float] | None = None, draws: int = 0, seed: int | None = 0, pruning: bool = True) -> Any

Responses to one-standard-deviation shocks (or shock_sd), as differences from the path without the shock; an IRF. They start from the stochastic steady state, or from state (levels of some of the states; the others at the stochastic steady state). With draws > 0 they are generalised responses (Koop, Pesaran and Potter 1996): the mean difference over that many draws of the other shocks, the same draws with and without the impulse; with 0, no other shocks occur. Unlike first-order responses they depend on the size and sign of the shock and on the starting point. With pruning, a given start's distance from the steady state is put in the first-order part of the state, and the path without the impulse starts there too.

moments

moments(periods: int = 100000, seed: int | None = 0, burn: int = 1000, pruning: bool = True) -> Table

Moments of the variables from a long simulation (pruned unless pruning=False): mean, standard deviation, skewness, excess kurtosis and first-order autocorrelation; the mean in closed form beside it.

rules

rules() -> Table

The decision rules with uncertainty at the model's shock sizes: the coefficient of each product of states and shocks, the constant (the correction for risk) first; corrections for risk fold into the constant and the linear terms.