Skip to content

Large models & policy simulation

The classes and functions of the row "Large models & policy simulation" 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: Forward-looking models, Solving models, State space and the Kalman filter, Monetary policy rule benchmarks, The quarterly projection model (QPM).

How do I: Solve a large backward-looking model, Bring an EViews model across, then check and solve it.

Classes

Fallback dataclass

Fallback(*attempts: Any, solvers: Any = ())

Period-by-period solvers tried in order: a period the first cannot solve is solved again by the next, from the same starting values, and so on; periods the first solves are as it solves them.

Fallback(GaussSeidel(), GaussSeidel(damping=0.5, max_iter=400), Newton(line_search=True)) keeps Gauss-Seidel's speed where it converges and retries only the periods where it does not. Solution.convergence names the solver that solved each period (its solver column) and counts every attempt's iterations; when all fail, the error lists each attempt with its worst equation. With ordering="blocks" the solvers are tried block by block.

GaussSeidel dataclass

GaussSeidel(tol: Annotated[float, Widget('number', min=1e-15, max=0.01, advanced=True, help='largest equation residual accepted')] = 1e-10, max_iter: Annotated[int, Widget('number', min=1, max=100000, advanced=True, help='iterations allowed in each period')] = 500, damping: Annotated[float, Widget('number', min=0.05, max=1, step=0.05, help='share of each update applied (below 1 can help convergence)')] = 1.0, convergence: Annotated[Convergence, Widget('choice', advanced=True, help="stop on the largest residual (in the equations' units), on the scaled step |x_new - x_old| / (1 + |x_old|), or on both")] = 'residual')

Update each equation's own variable in turn. Cannot handle target/free swaps.

Each sweep takes the equations in order and moves each one's own variable towards satisfying it (a Newton step in that variable alone), using the latest values of the others, until every residual is below the tolerance. It needs no full Jacobian and suits large models whose equations are mostly recursive, but it can converge slowly or not at all when the simultaneous feedback is strong; damping below 1 often helps, at the cost of more iterations, and Newton is the alternative. Every equation must depend on its own variable. convergence="step" stops when a sweep's scaled step, the largest |x_new - x_old| / (1 + |x_old|), is below the tolerance, whatever the equations' units ("both" requires both tests).

Link(name: str, variable: str, weights: Any)

A variable each entity takes from the others: see the module docstring.

matrix

matrix(entities: Sequence[Any]) -> ndarray

The weights as an entities x entities array: row i gives entity i's link from each entity.

Model dataclass

Model(equations: Sequence[Equation | FittedEquation], roles: Mapping[str, Role] | None = None, over: str | None = None, params: Mapping[str, float] | Any = None, links: Sequence[Any] = (), specs: Sequence[Param] = ())

parameters property

parameters: Any

The model's parameters (a ParameterSet): estimated coefficients, named by equation, and calibrated ones.

with_parameters

with_parameters(values: Mapping[str, float]) -> Model

The same model at other parameter values, sharing everything that does not depend on them: the compiled equations, their derivatives, and the structure the steady state and linearisation work out. What estimation and Metropolis-Hastings use at each trial value, instead of building the model again from its equations.

compile

compile() -> Any

The model as a ModelSystem: equations as residuals with symbolic parameters, every variable with its role, the parameters with their values and status, and the lead and lag structure.

spec

spec(name: str) -> Param | None

The metadata of a parameter, or of a shock size or measurement error (sd_...), if any was given. A regime's value (phi_pi@post, see pymetrix.models.regimes) has its own spec if given, else its parameter's.

check

check(data: Dataset | None = None, span: tuple[Any, Any] | None = None, shocks: Sequence[str] = (), steady: bool | None = None, guess: Mapping[str, float] | None = None, scenario: Scenario | None = None, growth: bool = False) -> Any

Diagnostics before solving (a ModelCheck): equations and their targets, solvability of simultaneous blocks, parameters, timing, shocks, and with data and span, whether the data cover the solution, and the inputs each equation lacks in each period (ModelCheck.missing, as missing_inputs gives it, under scenario if one is given). For models with leads (or steady=True), also the steady state and the Blanchard-Kahn conditions; growth=True looks for a balanced growth path (steady_state(growth=True)).

missing_inputs

missing_inputs(data: Dataset, span: tuple[Any, Any], scenario: Scenario | None = None) -> DataFrame

The inputs each equation lacks in each period of span, before solving: a table with one row per period, equation and input (period, equation, input, the input written as x[-1]), empty when every equation can be evaluated. Inputs are the exogenous series and, with their lags, the endogenous ones before the span (the starting values); the endogenous values the solve determines in the span are not inputs, nor are leads past it (the terminal condition gives them). scenario is applied first: its set and shifted paths, fixed and held variables (whose equations are not solved where they are fixed; a fixed variable without a value is reported against its equation), partial fixes (Scenario(partial=...)) and free variables.

from_file classmethod

from_file(path: str | Path, **options: Any) -> Model

Read a model file into a Model, by its extension: .mod (Dynare, read_mod), .model (IRIS, read_iris), .prg (an EViews program, read_eviews) or .xml (an FRB/US-style model file, read_eviews_xml). options go to the reader (e.g. params= for IRIS and EViews, mce= for XML). The reader's own result (a Template or DynareModel) also keeps the shocks, their sizes and the measurement: call the reader directly when those are needed.

blocks

blocks() -> list[Block]

Recursive and simultaneous blocks, in solution order (Tarjan's algorithm).

steady_state

steady_state(exogenous: Mapping[str, float] | None = None, guess: Mapping[str, float] | None = None, growth: bool = False, fix: Mapping[str, float] | None = None) -> Any

The steady state: every variable constant over time, exogenous variables at exogenous (missing ones at zero, as for shocks). guess gives starting values. growth=True finds a balanced growth path instead (levels and growth rates; see pymetrix.models.growth); fix sets levels the model does not pin down.

calibrate

calibrate(targets: Mapping[str, float], free: Sequence[str], growth: bool = False, exogenous: Mapping[str, float] | None = None, guess: Mapping[str, float] | None = None, fix: Mapping[str, float] | None = None) -> Any

Choose the free parameters so that the steady state hits targets (expressions of the variables, e.g. {"k/y": 10}); a Calibration with the new model. See pymetrix.models.calibrate.

in_logs

in_logs(*names: str) -> Model

The same model with these endogenous variables (all, without names) written as exp(x) in every equation, so that x is the log of the variable: levels that grow by a factor (1 + g) each period then grow by log(1 + g), a balanced growth path steady_state(growth=True) finds; first-order solutions are in log deviations (as IRIS's log variables and Dynare's loglinear).

linearize

linearize(at: Any = None, shocks: Sequence[str] = (), exogenous: Mapping[str, float] | None = None, guess: Mapping[str, float] | None = None) -> Any

The first-order approximation around a steady state (default: steady_state()), as a LinearModel in deviations from it. shocks are the exogenous variables that are random (default: those with Role.SHOCK in roles); exogenous and guess are passed to steady_state.

estimate

estimate(data: Dataset, measurement: Any, shocks: Sequence[str] | None = None, shock_sd: Mapping[str, float] | None = None, estimate: Sequence[str] | None = None, priors: Mapping[str, Any] | None = None, bounds: Mapping[str, tuple[float, float]] | None = None, span: tuple[Any, Any] | None = None, guess: Mapping[str, float] | None = None, growth: bool = False, start: str = 'auto', presample: int = 0, max_iter: int = 2000, starts: int = 1, seed: int | None = 0, workers: int | str | None = 'auto', occbin: bool = False, horizon: int = 40, cov: str = 'classic', regimes: Any = None, shock_corr: Mapping[Any, float] | None = None, order: int = 1, filter: str | None = None, particles: int = 2000, gradient: str = 'auto', smooth_paths: int = 100, diffuse_terms: str = 'include') -> Any

Estimate the linearised model from data (a FittedModel): maximum likelihood, or the posterior mode when any estimated parameter has a prior. measurement links the data to the model (a MeasurementMap, or model variables observed as they are). start is the Kalman filter's start (auto, stationary, diffuse or scaled, Dynare's lik_init=2); presample periods are filtered but left out of the likelihood; max_iter caps the optimiser's iterations. starts optimises from that many points (the starting values, then draws from the priors), in workers processes at once, and keeps the best: every start's result is in provenance.method["starts"], and the summary says when they found different modes. occbin=True takes the likelihood of the OccBin filter instead, for a model with occasionally binding constraints (its own max or min): see pymetrix.models.occbin_filter; horizon is how far ahead each period's regimes are worked out. cov="none" skips the inverse Hessian (no standard errors), for speed when only the mode is wanted. regimes: parameters or equations that change at known dates in the sample (Regime objects or text such as "2009Q1: phi_pi=1.2"), filtered through the time-varying rules they give; their values are estimated as <parameter>@<regime> (phi_pi@2009Q1; see pymetrix.models.regimes). shock_corr gives the shocks' correlations ({("ey", "ei"): 0.3}): estimated as corr_ey_ei, as shock sizes are (see pymetrix.models.covariance). order=2 estimates the second-order (pruned) solution on the likelihood of the particle filter (filter="particle", bootstrap, the default at order 2, or "guided") with particles particles and common random numbers from seed (0 if None): every observed series needs a measurement error; filter="particle" at order 1 checks it against the Kalman filter; smooth_paths paths of the particle smoother give the fit's smoothed (0: the filtered means instead). See pymetrix.models.particle. gradient: the optimiser's and the Hessian's gradient, "auto" (analytic where it applies, see pymetrix.models.kalman_score, else finite differences), "analytic" (refused where it does not apply) or "numerical". diffuse_terms, with diffuse states (unit roots, or start="diffuse"): "include" (default) maximises the exact diffuse log likelihood of Durbin and Koopman (2012, section 7.2.2), with the diffuse periods' terms; "exclude" leaves them out (statsmodels' default convention; Kalman filter only), see pymetrix.statespace. See pymetrix.models.estimation.

dsge_var

dsge_var(data: Dataset, measurement: Any, lags: int = 4, lambda_: Any = 1.0, lambdas: Sequence[float] | None = None, shocks: Sequence[str] | None = None, shock_sd: Mapping[str, float] | None = None, estimate: Sequence[str] | None = None, priors: Mapping[str, Any] | None = None, bounds: Mapping[str, tuple[float, float]] | None = None, span: tuple[Any, Any] | None = None, guess: Mapping[str, float] | None = None, max_iter: int = 2000, shock_corr: Mapping[Any, float] | None = None) -> Any

A DSGE-VAR(lambda) (Del Negro and Schorfheide 2004): a VAR(lags) with a constant in the observables, its prior from the model's population moments weighted as lambda T observations, and the model's parameters estimated by the VAR's marginal likelihood (a FittedDSGEVAR: the posterior mode, then .mcmc(...)). lambda_: a number (fixed, at least (k + n) / T); "grid", the best marginal data density over lambdas (lambda-hat); or a prior (Gamma(1, 0.5)), lambda then estimated as lambda. The rest as in estimate. See pymetrix.models.dsge_var.

identification

identification(measurement: Any, params: Sequence[str] | None = None, shocks: Sequence[str] | None = None, shock_sd: Mapping[str, float] | None = None, lags: int = 4, at: Mapping[str, float] | None = None, elasticity: bool = False, guess: Mapping[str, float] | None = None, growth: bool = False, regimes: Any = None, span: Any = None) -> Any

Whether the observables' moments could tell params apart, before any data exist: Iskrev's test at the calibration (or at={name: value}), as estimate(...).identification(lags, at) gives at the same point. params are named as in estimate (default: the calibrated parameters and every sd_<shock>); measurement, shocks and shock_sd as there. regimes (known-date regimes, their values named <parameter>@<regime>) over a sample span (("2000Q1", "2019Q4")): the moments of every period of it through the regimes' time-varying rules (bayes.regime_moments); regimes that start after the span are left out, as estimation leaves them to forecasts. An Identification.

add_factors

add_factors(data: Dataset, span: tuple[Any, Any] | None = None) -> dict[str, Series]

Tracking add factors: by equation name, each equation's residual at the data in each period of span (default: every period where it can be computed), as EViews's addinit sets them. Solved with Scenario(adjust=model.add_factors(data)) the model reproduces the data (a baseline projection, say) exactly, under any solver, so a scenario's other changes read as deviations from that baseline.

solve

solve(data: Dataset, span: tuple[Any, Any] | None, scenario: Scenario | None = None, solver: Newton | GaussSeidel | Fallback | PerfectForesight | FirstOrder | None = None, draws: int | None = None, seed: int | None = 0, errors: str | DataFrame | Dataset | Mapping[str, Series] = 'normal', shock_sd: Mapping[str, float] | None = None, coefficients: bool = False, entity_params: Mapping[Any, Mapping[str, float]] | None = None, regimes: Any = None, shock_corr: Mapping[Any, float] | None = None, error_scale: Mapping[Any, float] | None = None, workers: int | None = None, ordering: str = 'joint') -> Solution

Solve over span under scenario. With draws, a stochastic simulation as well: the deterministic solution with that many draws (Solution.simulation; quantiles, mean, sd, fan). A backward-looking model draws its fitted equations' errors (errors: "normal" or "bootstrap"; shock_sd by equation; coefficients=True draws their coefficients too), or resamples a sample of residuals given (errors= a DataFrame, periods by equation, a whole period at a time; or a Dataset of them, over its active sample, or the add factors add_factors gives over a historical span, in the periods every equation has one), with error_scale multiplying the errors of some periods ({"2025Q1": 0.5}) and workers processes solving the draws; a first-order solution draws its shocks, with shock_sd by shock and correlations shock_corr ({("ey", "ei"): 0.3}). seed makes the draws reproducible. See pymetrix.models.stochastic.

With over (an entity axis of a panel data), the model is solved for each entity on its own time series: with the same parameters, or each entity's in entity_params ({"UK": {"cons.y": 0.6}}); scenario is one for all or {entity: Scenario}; draws take seed + the entity's position. Returns a PanelSolution. With links (foreign variables, world aggregates), the entities are solved jointly, each draw too: see pymetrix.models.links.

regimes (first-order solver, or perfect foresight): parameters or equations that change at known dates (Regime objects or text such as "2025Q1..2026Q4: rho=1, phi_pi=0"); see pymetrix.models.regimes. With PerfectForesight the stacked system's equations switch at the regimes' dates, the nonlinear model's own (pymetrix.models.perfect_foresight), known in advance unless a regime is a surprise (expected=False), solved again from its start.

ordering (a backward-looking model solved period by period): "joint" (default) gives the solver all the equations each period; "blocks" splits them into recursive and simultaneous blocks first, solves each recursive equation once, in order, and iterates only within the simultaneous blocks, each with the solver given (Newton, GaussSeidel or a Fallback, block by block); see pymetrix.models.ordering. The same solution, with far fewer evaluations for a model that is mostly recursive. Solution.convergence then reports the blocks iterated on and the recursive equations by period, and the blocks in .attrs["blocks"].

ModelSource dataclass

ModelSource(text: str, syntax: Syntax = 'pymetrix', name: str = 'model')

A model as text in a syntax: see the module docstring.

check

check() -> SourceCheck

The problems in the text, with their places, and the symbols: without solving the model.

build

build() -> Any

The model the text describes: a Template (pymetrix syntax: the model, its shocks and their sizes, the measurement equations, guesses and descriptions), a DynareModel (Dynare syntax, as read_mod) or a Template (IRIS syntax, as read_iris: parameter values in !parameters, shock sizes as std_<shock>), or a Template (EViews syntax, as read_eviews: model text or a program; its shocks are its @innovs). Refused, with the first problems, when the text has errors.

export

export(syntax: Syntax) -> Any

The model in another syntax (a Translation: the text, notes on what did not carry across, and whether it solves the same): built from this text, then written. See pymetrix.models.writers.

algebraic

algebraic(style: Literal['unicode', 'latex'] = 'unicode') -> Any

The equations in algebraic notation (AlgebraicEquations: name, variable, text), the measurement equations last: see pymetrix.models.writers.algebraic_equations.

latex

latex() -> str

The equations as LaTeX align blocks, each tagged with its name.

check_solution

check_solution() -> SolutionCheck

Whether the model solves: its steady state, then the roots of the model linearised there and the Blanchard-Kahn conditions. The roots are found whether or not the conditions hold, to see which fail.

completions

completions(line: int, column: int, found: SourceCheck | None = None) -> list[str]

What may complete the word before the cursor, at line and column (from 1; the cursor before that column's character): the names the text declares (found, a check of it, or a new one), then the functions, then the syntax's keywords, those that start with the word typed so far (any case). None inside a comment, a description or a number.

hover

hover(line: int, column: int, found: SourceCheck | None = None) -> str

What the name or function at line and column (from 1) is: a symbol's role, value, description, estimation settings and the lines that use it; a function's signature and what it does; empty for anything else (and inside comments).

ModelSystem dataclass

ModelSystem(equations: tuple[SystemEquation, ...], parameters: ParameterSet, endogenous: tuple[str, ...], exogenous: tuple[str, ...], shocks: tuple[str, ...], roles: Mapping[str, Role])

A model compiled: equations as residuals, variables by role, parameters, lead and lag structure.

incidence property

incidence: dict[str, tuple[int, ...]]

For each variable, the lags (negative) and leads (positive) at which it appears.

residuals

residuals(values: Mapping[str, float] | None = None) -> list[Expr]

The residuals with parameter values substituted: the model's own, or values where given.

contemporaneous

contemporaneous() -> dict[str, list[str]]

For each equation, the endogenous variables it contains in the current period.

incidence_table

incidence_table() -> Table

Equations by variables: where each variable enters each equation (t-1, t, t+1...).

Newton dataclass

Newton(tol: Annotated[float, Widget('number', min=1e-15, max=0.01, advanced=True, help='largest equation residual accepted')] = 1e-10, max_iter: Annotated[int, Widget('number', min=1, max=10000, advanced=True, help='iterations allowed in each period')] = 50, convergence: Annotated[Convergence, Widget('choice', advanced=True, help="stop on the largest residual (in the equations' units), on the scaled step |x_new - x_old| / (1 + |x_old|), or on both")] = 'residual', line_search: Annotated[bool, Widget('checkbox', advanced=True, help='backtrack (Armijo) when the full step does not reduce the residuals')] = False, refresh: Annotated[Literal['iteration', 'period'], Widget('choice', advanced=True, help='evaluate the Jacobian every iteration, or once a period and again only when convergence slows (modified Newton)')] = 'iteration')

Newton's method with the analytic Jacobian; solves all equations jointly.

In each period every step solves the model's equations linearised at the current values, so simultaneous blocks are solved together and convergence near the solution is fast. It also handles scenarios that swap a target for a free variable, which Gauss-Seidel cannot. It can fail when the starting values are far from the solution, or when the Jacobian is singular because some equation does not determine its variable; the error names the equation with the largest residual. The tolerance applies to the residuals as written, so it depends on the equations' units: convergence="step" stops on the scaled step instead, the largest |x_new - x_old| / (1 + |x_old|), which does not ("both" requires both tests). line_search=True backtracks (Armijo) when the full step does not reduce the residuals enough, for starts far from the solution. refresh="period" is a modified Newton: the Jacobian is evaluated and factorised once and kept while each step cuts the largest residual at least to a quarter, and evaluated again when convergence slows; for models whose Jacobian is costly to evaluate.

PerfectForesight dataclass

PerfectForesight(terminal: Annotated[Literal['constant', 'data', 'steady_state', 'growth'], Widget('choice', help='leads beyond the last period: hold the last value, take the data, the steady state, or the last value on the balanced growth path')] = 'constant', tol: Annotated[float, Widget('number', min=1e-15, max=0.01, advanced=True, help='largest equation residual accepted')] = 1e-10, max_iter: Annotated[int, Widget('number', min=1, max=1000, advanced=True, help='Newton iterations allowed')] = 50)

Models with expectations (leads such as x[+1]): every period solved at once (stacked-time Newton).

Expectations are model-consistent: agents foresee the whole simulated path, including announced changes to exogenous variables. Beyond the last period, leads take their terminal values: the last simulated value (constant), the data, or the steady state. Simulate well past the periods of interest so the terminal condition matters little.

pymetrix.extension.Diagnostic dataclass

Diagnostic(line: int, column: int, message: str, severity: Literal['error', 'warning', 'note'] = 'error', length: int = 1)

A problem in the text: where it is (line and column from 1), what it is, and how bad.

Scenario dataclass

Scenario(set: Mapping[str, Path] = dict(), shift: Mapping[str, Path] = dict(), fix: Mapping[str, Path | None] = dict(), adjust: Mapping[str, Path] = dict(), hold: Mapping[str, Path] = dict(), free: Sequence[str] = (), unanticipated: Sequence[str] = (), name: str = 'scenario', hold_sd: Mapping[str, Path] = dict(), free_sd: Mapping[str, float] = dict(), hold_lower: Mapping[str, Path] = dict(), hold_upper: Mapping[str, Path] = dict(), partial: bool | Sequence[str] = False)

How a simulation departs from the data. hold and free exogenize and endogenize: by default each held variable is paired, in order, with one free variable that takes whatever values hold it. With hold_sd or free_sd (first-order solutions only), or a different number of free shocks than holds, the plan is a least-norm conditional forecast instead: every free shock is free in each period up to the last held one, and the smallest free shocks (in units of free_sd) that meet the holds are found; a hold with a standard deviation in hold_sd is soft, met only as far as it is worth, and one without (or 0) is exact. hold_lower and hold_upper (first-order solutions only) keep variables within a range instead: the free shocks move only as far as needed to keep each bounded value at or above its lower bound and at or below its upper one.

partial (nonlinear solvers: Newton, Gauss-Seidel, perfect foresight) applies fix and hold only in the periods their paths give a value: True for every fixed and held variable, or the names of some. In a period with a value (not NaN) the variable is exogenous at it, its equation dropped (fixed) or its free variable solved for (held); in a period without one its equation determines it as usual, and a held variable's free partner keeps its value in the data. A fix at the data's values (fix={"x": None}) applies where the data have values. Without partial a fixed or held variable needs a value in every period of the span, as before. A first-order solution holds variables only where their paths give values in any case.

ranges property

ranges: bool

Whether the scenario keeps some variable within a range (hold_lower or hold_upper).

Functions

compare_solutions

compare_solutions(**solutions: Any) -> ScenarioSet

Solutions already computed (e.g. by Model > Solve model, one per scenario), side by side; the baseline is the one named "baseline", else the first (.with_baseline(name) for another).

export_model

export_model(obj: Any, syntax: str, origin: str = '', form: str = 'program') -> Translation

obj (a template, a Dynare model or a Model) written in syntax ("pymetrix", "dynare", "iris" or "eviews"): see the module docstring. origin is said in the first comment line (where the model came from); form (EViews only) is "program" (a .prg: model m, m.append lines and the values) or "text" (the model's text alone, its values in a comment).

optimal_control

optimal_control(model: Any, data: Any, span: Any, instruments: Sequence[str], loss: Mapping[str, float], desired: Mapping[str, Any] | None = None, control: Any = None, discount: float = 1.0, scenario: Any = None, solver: Any = None, tol: float = 1e-06, max_iter: int = 20) -> OptimalControl

The paths of instruments (exogenous series, moved in each period of control: the span by default) that minimise the discounted quadratic loss over span, with model solved under scenario as the constraint: see the module docstring.

optimal_policy

optimal_policy(obj: Any, instrument: str, loss: Mapping[str, float], kind: str = 'commitment', beta: float = 0.99, rule: str | None = None) -> OptimalPolicy

Optimal policy for obj (a template, a Dynare or IRIS model, or a Model): see the module docstring.

osr

osr(obj: Any, params: Sequence[str], loss: Mapping[str, float], bounds: Mapping[str, tuple[float, float]] | None = None, start: Mapping[str, float] | None = None) -> OSRResult

The coefficients params of a template's (or Dynare or IRIS model's) policy rule that minimise the weighted unconditional variances: see the module docstring.

policy_rules

policy_rules(data: Any, rate: str, inflation: str, gap: str | None = None, unemployment: str | None = None, long_run_unemployment: float | str | None = None, inflation_target: float | str = 2.0, neutral_rate: float | str = 2.0, rules: Sequence[str] = RULES, custom: Mapping[str, Mapping[str, Any]] | None = None, okun: float = 2.0, smoothing: float = 0.85, elb: float = 0.125, per_year: int | None = None, vintages: Any = None, vintage_lag: int | None = None) -> PolicyRules

The policy rate that simple monetary policy rules prescribe, period by period, with the range across them and the actual rate's deviation from each: the benchmarks of the Federal Reserve's Monetary Policy Report.

rate is the actual policy rate and inflation four-quarter inflation (the Fed uses core PCE), both in percent; slack is the output gap (percent of potential), or the unemployment rate with its long_run_unemployment (a number or a series), turned into a gap by Okun's law, okun * (u* - u). inflation_target (pi) and neutral_rate (r, the neutral real rate: a number, or a series such as a Laubach-Williams estimate or a QPM's rr_bar) are numbers or series names. rules: any of taylor, balanced_approach, adjusted_taylor, inertial and first_difference (all by default); custom adds rules of your own, {name: {"inflation": a, "gap": b, "smoothing": rho, "difference": False}}: R = rho R[-1] + (1 - rho)(r* + pi + a (pi - pi) + b gap), or with difference=True, R = R[-1] + a (pi - pi) + b (gap - gap a year earlier). smoothing is the inertial rule's weight on last period's rate (0.85), elb the adjusted rule's effective lower bound (0.125, 12.5 basis points), per_year the periods in a year (from the data's frequency when not given). vintages (VintageTable, one per series) make the prescriptions real time: each period's figures as first published, or as they stood vintage_lag days after the period ended.

pymetrix.extension.line_and_column

_place(text: str, offset: int) -> tuple[int, int]

The line and column (both from 1) of an offset (from 0) in text.

read_eviews_sspace

read_eviews_sspace(source: str | Path, params: Mapping[str, float] | None = None) -> Any

An EViews state-space object (sspace: @signal, @state, @ename, @evar var(e) = ..., errors as [var = ...]; bare or after ss.append) as pymetrix's StateSpace: signals are measurement equations (terms in data series moved to the left: the observed side), states transition equations, an error's variance beta(3)^2 the shock's standard deviation, the parameter beta_3 (or a number); coefficients beta(3) are parameters beta_3, with starting values from beta(3) = 0.5 lines or params. Refused (with the first problems at their places) for what does not map: covariances of errors, variances not of that form, terms mixing data and states, data in state equations, and EViews's programming language.

read_eviews_xml

read_eviews_xml(path: str | Path, mce: bool | list[str] = False, name: str | None = None) -> EViewsXmlModel

Read an XML model file in the format of the Federal Reserve's FRB/US package (mods/model.xml) into a Template (in an EViewsXmlModel with each variable's kind, sector, description and stochastic type). mce uses the model-consistent-expectations versions of the equations that have them (True: all; or a list of their groups, e.g. ["mcap", "mcwp"]) instead of the standard (VAR-expectations) ones. The equations go through the EViews reader (read_eviews), their coefficients y_x(1) becoming parameters y_x_1.

scenarios

scenarios(source: Any, scenarios: Mapping[str, Any] | Sequence[Any], span: tuple[Any, Any], data: Any = None, workers: int | None = None, baseline: str | None = None) -> ScenarioSet

Solve source (an estimated model, forecast from the end of its data, or a rational-expectations solution with data) under each scenario over span: see the module docstring. baseline: the scenario the others are compared with (default: one named "baseline", else the first).

sweep

sweep(obj: Any, values: Mapping[str, Sequence[float]], what: Any = 'irf', grid: str = 'product', workers: int | None = None, response: str | None = None, shock: str | None = None, **options: Any) -> SweepResult

Run obj (a template, a Dynare or IRIS model, a Model) once for each set of parameter values: see the module docstring. response and shock: the impulse response plot() draws by default.

Results

ModelCheck dataclass

ModelCheck(rows: tuple[tuple[str, str, str], ...], system: ModelSystem, missing: Any = None, provenance: Any = None)

The diagnostics of Model.check: one row per check, each ok, note, warning or error.

ok property

ok: bool

No errors (notes and warnings allowed).

summary

summary() -> Table

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

OptimalControl dataclass

OptimalControl(solution: Any, baseline: Any, moves: DataFrame, loss: float, baseline_loss: float, gradient: DataFrame, iterations: int, weights: Mapping[str, float] = dict(), discount: float = 1.0, history: tuple[float, ...] = (), provenance: Any = None)

An optimal-control solution: see the module docstring.

OptimalPolicy dataclass

OptimalPolicy(kind: str, instrument: str, weights: Mapping[str, float], beta: float, solution: Any, shock_sd: Mapping[str, float] = dict(), dropped: str = '', provenance: Any = None)

The optimal-policy solution: see the module docstring.

loss

loss() -> float

The weighted unconditional variances, sum w_v Var(v): the loss per period on average.

OSRResult dataclass

OSRResult(values: Mapping[str, float], loss: float, template: Any, weights: Mapping[str, float], converged: bool = True, provenance: Any = None)

An optimal simple rule: the coefficients, the loss, and the model with them.

PolicyRules dataclass

PolicyRules(prescriptions: DataFrame, actual: Series, inputs: DataFrame, rules: DataFrame, rate: str, inflation: str, slack: str, real_time: str = '', provenance: Any = None)

The policy rate simple rules prescribe, period by period: prescriptions (a column per rule, labelled), actual (the policy rate), inputs (inflation, the objective, the neutral rate, the gap and, for the adjusted rule, the make-up term Z), rules (each rule's formula, source and parameters) and the settings. range is the band across the rules (low, median, high) and deviations the actual rate less each prescription.

range property

range: DataFrame

Each period's lowest, median and highest prescription across the rules.

deviations property

deviations: DataFrame

The actual rate less each rule's prescription: positive where policy is tighter than the rule.

last property

last: Any

The last period with a prescription.

to_frame

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

The actual rate, each rule's prescription and the range across them, by period; or the table of a view.

summary

summary() -> Table

The last period: each rule's prescription and the actual rate's deviation from it, and the range.

plot

plot(kind: Literal['both', 'lines', 'range'] = 'both', span: tuple[Any, Any] | None = None) -> Figure

The actual rate (black) with each rule's prescription as a line ("lines"), the range across the rules shaded ("range"), or both, as the Monetary Policy Report draws them.

ScenarioSet dataclass

ScenarioSet(solutions: Mapping[str, Any], errors: Mapping[str, str | None] = dict(), baseline: str = '', loss: Mapping[str, float] = dict(), desired: Mapping[str, float] = dict(), discount: float = 1.0, provenance: Any = None)

Model paths under several named scenarios, compared with one of them, the baseline: see the module docstring.

baseline is the scenario the others are measured against: the one given, else one named "baseline", else the first. deviations, impact and plot(deviations=True) show each scenario less the baseline, which is what a policy brief reports (Report.from_template("policy_brief", {...: set})). with_loss sets a quadratic loss to rank the scenarios by (losses): as optimal control's, the sum over the periods solved and the variables weighted of discount^t * weight * (value - desired)^2.

alternatives property

alternatives: list[str]

The scenarios other than the baseline that solved.

variables property

variables: list[str]

The variables every scenario that solved has, in the first's order.

with_baseline

with_baseline(name: str) -> ScenarioSet

The same scenarios, compared with name.

with_loss

with_loss(loss: Mapping[str, float], desired: Mapping[str, float] | None = None, discount: float = 1.0) -> ScenarioSet

The same scenarios with a loss to rank them by (losses, the window's Loss tab, the policy brief): loss the weight on each variable's squared gap ({"pi": 1, "ygap": 0.5}), desired the value each gap is measured from ({"pi": 2}; 0 otherwise), discount per period (1: none), as optimal control's.

losses

losses() -> Table

Each scenario's loss (with_loss): a row per scenario that solved, a column per variable's part, the total, and the total less the baseline's (negative: better than the baseline).

frame

frame(variable: str) -> DataFrame

variable in each scenario, side by side (the periods the scenarios solved).

difference

difference(scenario: str, baseline: str | None = None, variables: Sequence[str] | None = None) -> Table

Each variable in scenario less baseline (the set's baseline if not given), period by period.

deviations

deviations(variable: str, percent: bool = False) -> DataFrame

variable in each scenario less the baseline, side by side; percent: as a percentage of the baseline (for levels, not rates).

impact

impact(variables: Sequence[str] | str | None = None, at: Any = 'average', percent: bool = False) -> Table

A scenario per row and a variable per column: how far each scenario is from the baseline. at: "average" over the periods solved, "end" (the last period), "peak" (the largest departure, with its sign) or a period.

plot

plot(variables: Sequence[str] | str | None = None, deviations: bool = False) -> Any

Each variable in a panel, a line per scenario (the baseline first); deviations: each scenario less the baseline, with a zero line.

Solution dataclass

Solution(frame: DataFrame, axes: tuple[Axis, ...], variables: Mapping[str, Variable] = dict(), flags: DataFrame | None = None, meta: DatasetMeta = DatasetMeta(), model: Any = None, scenario: Any = None, converged: bool = True, iterations: int = 0, provenance: Provenance | None = None, simulation: Any = None, convergence: DataFrame | None = None)

Bases: Dataset

solved

solved() -> Dataset

The simulated periods only.

quantiles

quantiles(qs: Sequence[float] = (0.05, 0.5, 0.95), variables: Sequence[str] | None = None) -> Dataset

The draws' quantiles in each period of the span: {variable}_q5, {variable}_q50, ... (q2_5 for 2.5%).

mean

mean() -> Dataset

The draws' mean in each period (for a nonlinear model, not the deterministic solution).

sd

sd() -> Dataset

The draws' standard deviation in each period.

bands

bands(coverages: Sequence[float] = (0.3, 0.6, 0.9), variables: Sequence[str] | None = None) -> DataFrame

The median of the draws and central bands holding each share of them: {variable}, {variable}_lo90, {variable}_hi90, ..., as forecast rounds and fan charts take them.

fan

fan(variables: Sequence[str] | None = None, coverages: Sequence[float] = (0.3, 0.6, 0.9), history: int = 16) -> Any

Fan charts of the draws: the median and bands at each coverage, after the recent history in the data.

SweepResult dataclass

SweepResult(names: tuple[str, ...], points: tuple[tuple[float, ...], ...], results: tuple[Any, ...], errors: tuple[str | None, ...], what: str = 'irf', grid: str = 'product', options: Mapping[str, Any] = dict(), provenance: Any = None)

The runs of a parameter sweep: see the module docstring.

values

values(extract: Callable[[Any], Any]) -> DataFrame

extract(result) for every run (a number, or a dict of numbers), one row per run; NaN where a run failed.

table

table(*args: Any, horizon: int | None = None, statistic: str = 'std. dev.') -> Table

One value per run. For impulse responses: table(response, shock, horizon=h) (every horizon without horizon); steady states: table(variable); moments: table(variable, statistic="std. dev.") (or "autocorr. 1" ...).

plot

plot(response: str | None = None, shock: str | None = None) -> Any

Impulse responses of every run, overlaid (by default the pair the sweep was given, else the first response and shock).

Other names

ModelError

Bases: PyMetrixError, ValueError

A model could not be built or solved.

Parameter dataclass

Parameter(name: str, value: float, status: Status = 'calibrated', equation: str | None = None, se: float | None = None, spec: Param | None = None)

One parameter of a model: its value, where it came from, and its metadata.

status: estimated (from a fit), calibrated (set by the user), or fixed (held at its value when the model's parameters are estimated). spec carries the Param metadata: bounds, transform, start, prior and symbol.

ParameterSet dataclass

ParameterSet(parameters: tuple[Parameter, ...] = ())

The parameters of a model, in order, looked up by name.

with_values

with_values(values: Mapping[str, float], status: Status | None = None) -> ParameterSet

New values for some parameters (and, if given, a new status for them).

fix

fix(*names: str) -> ParameterSet

Hold these parameters at their values when the model is estimated.

summary

summary() -> Table

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