Skip to content

Session, records and errors

pymetrix's public names that are not analytical tools: the session's settings (random numbers, threads, themes), data and metadata records, errors, the plugin registry and modules. Import them from pymetrix.

Results

Theme dataclass

Theme(name: str, palette: tuple[str, ...] = OKABE_ITO, line_styles: tuple[str, ...] = ('-',), line_width: float = 1.6, font_size: float = 8.0, title_size: float = 9.5, font_family: str = '', grid: bool = True, band_alpha: float = 0.15, digits: int = 4, version: int = 1, rc: tuple[tuple[str, Any], ...] = ())

Appearance settings for figures, tables and reports.

from_mplstyle classmethod

from_mplstyle(path: str, name: str | None = None) -> Theme

A theme from a matplotlib style sheet (.mplstyle), registered under name (default: the file's name).

The sheet's colour cycle becomes the palette, and its font, font size, title size, line width and grid set those of the theme; every other setting in the sheet (spines, ticks, background, ...) is kept and applied while drawing, as matplotlib would apply the sheet. Use it as theme="name" on any figure or report.

with_options

with_options(**changes: Any) -> Theme

A copy with some settings changed: get_theme("policy").with_options(digits=1).

Other names

__version__ module-attribute

__version__ = '0.1.0a24'

Adjustment

Bases: str, Enum

DataError

Bases: PyMetrixError, ValueError

Something about the data: a series' values, frequency, sample, or too few observations.

DatasetMeta dataclass

DatasetMeta(title: str = '', description: str = '', license: str = '', contact: str = '', extra: Mapping[str, Any] = dict(), sample: Mapping[str, Any] | None = None, vintage: Mapping[str, Any] | None = None)

demo

demo(name: str = 'forecast_round') -> Any

A new session with the demo's steps already run.

demos

demos() -> dict[str, str]

The demo projects: name -> what it shows.

get_blas_threads

get_blas_threads() -> int | None

BLAS threads used during estimation, sampling, identification and sweeps (None: the library's own setting).

get_random_generator

get_random_generator() -> str

The bit generator pymetrix draws with: "pcg64" (the default), "mt19937", "philox" or "sfc64".

get_theme

get_theme(theme: str | Theme | None = None) -> Theme

A theme by name, the theme itself, or (None) the session's default.

Measure

Bases: str, Enum

What a series measures; sets default aggregation.

NotFoundError

Bases: PyMetrixError, KeyError

A name that does not exist: a series, an object, a test, a template, an equation.

nowcast

Nowcasting tools: what was known when (the ragged edge), and the standard ways of handling it.

monthly = Dataset.example("sample_monthly")      # each series knows its publication lag (Variable.release_lag)
monthly.ragged_edge()                            # last observation of each series, and when it was published
known = monthly.as_of("2025-02-15")              # what was known on that day: later values removed
fill_edge(known, lags=2)                         # missing months at the end forecast by an AR model (bridge style)
realign(known)                                   # each series shifted so its last value is in the same period

Data published with different delays end in different periods: a survey for last month is out, industrial production only for the month before. as_of rebuilds that ragged edge for any day from the publication lags, so a nowcast can be made (and checked) with only what was known then. Three ways of dealing with it: leave the gaps for a model that handles missing values (a factor model, by the Kalman filter); fill them with forecasts from a small autoregression of each series (what bridge equations do); or realign each series so its latest value is treated as current (vertical realignment, Altissimo et al. 2010). Values are not revised here: as_of removes what was not yet published, it does not restore earlier vintages (Variable.vintage and ALFRED data do that).

Param dataclass

Param(name: str, label: str = '', symbol: str | None = None, bounds: tuple[float, float] = (-inf, inf), transform: Literal['none', 'log', 'logit'] = 'none', start: float | None = None, prior: Any = None, fixed: bool = False)

Metadata for a model or equation parameter, or a model's shock size (sd_<shock>) or measurement error (sd_<series>): its description (label), its symbol in algebraic notation ("φ_π"), bounds, the transform estimation works on ("log": positive; "logit": between 0 and 1, when no bounds are given), a starting value for estimation, a prior, and whether it is fixed (held at its value when the model is estimated).

limits property

limits: tuple[float, float]

The bounds, or those the transform implies when none are given: (0, inf) for log, (0, 1) for logit.

merged

merged(other: Param | None) -> Param

This spec, with other's fields where this one leaves them at their defaults (a model's spec over an equation's).

PlannedError

Bases: PyMetrixError, NotImplementedError

A feature that is planned but not built yet.

plugin_table

plugin_table() -> Any

Installed plugins, their status and what they provide, as a Table.

PluginInfo dataclass

PluginInfo(name: str, version: str, api: str = API, requires: Mapping[str, str] = dict(), license: str = '', maintainer: str = '', description: str = '', install: str = '')

Who provides a set of extensions, what they need, and under which licence.

requires maps importable library names to the versions supported, e.g. {"linearmodels": ">=6"}. install is the command shown when they are missing.

prefix property

prefix: str

The plugin part of qualified identifiers: pymetrix-linearmodels -> linearmodels.

unsupported property

unsupported: list[str]

Libraries that are installed in a version the plugin does not support, with what is needed.

problem property

problem: str | None

Why the plugin cannot be used, with what to do about it; None when it can.

supported property

supported: bool

Written for an extension API this pymetrix provides: a supported major version, and within the current major, no newer a minor version than this pymetrix's (a plugin gives the oldest API it works with).

needs_newer property

needs_newer: bool

Written for a newer minor version of this pymetrix's extension API (api="1.14" on 1.13).

Prices

Bases: str, Enum

priors

Prior distributions, for Bayesian estimation and posterior-mode estimation of state-space models.

Parameterised by mean and standard deviation, as in Dynare, so priors read the way economists usually state them. logpdf(x) is the log density and support the interval where it is positive (estimation keeps parameters inside it); rvs(rng) is a draw (estimation's extra starting points).

The two inverse gammas are Dynare's: InvGamma1 (Dynare's inv_gamma_pdf and inv_gamma1_pdf) is the usual prior on a standard deviation, s/sigma^2 being chi-squared; its standard deviation may be infinite (2 degrees of freedom, as fs2000 uses). InvGamma (also InvGamma2, Dynare's inv_gamma2_pdf) is the inverse gamma of the value itself, the usual prior on a variance.

Dynare's generalised priors (the third and fourth prior parameters of estimated_params): GeneralisedBeta(mean, sd, low, high), a beta on (low, high); ShiftedGamma, ShiftedInvGamma1 and ShiftedInvGamma2(mean, sd, low), on (low, inf). The mean and standard deviation are those of the generalised distribution, as in Dynare's manual. quantile(prior, q) gives a prior's quantiles (Dynare's prior_trunc).

Provenance dataclass

Provenance(data_vintages: Mapping[str, Vintage | None], spec: Mapping[str, Any], method: Mapping[str, Any], sample: tuple[str, str] | None, nobs: int, dropped: int, seed: int | None = None, package_version: str = '', created: datetime = now(), data_fingerprint: str = '', warnings: tuple[str, ...] = (), converged: bool | None = None, resolved: Mapping[str, Any] | None = None, sample_source: str = '', sample_definition: Mapping[str, Any] | None = None, backend: Mapping[str, Any] | None = None, options: Mapping[str, Any] | None = None, messages: tuple[str, ...] = (), rows: Any = None, presample: tuple[str, ...] = (), dropped_rows: Mapping[str, Any] | None = None, vintage_request: Mapping[str, Any] | None = None, random_generator: str | None = None, build: Mapping[str, Any] | None = None)

Where a result came from: data vintages, specification, method and sample.

table

table() -> Any

The standard Provenance view of a result (its window's Provenance tab), as a Table.

from_data classmethod

from_data(spec: Any, data: Any, names: Any, index: Any, method: Mapping[str, Any], *, span: Any = None, before: int = 0, seed: int | None = None, converged: bool | None = None, resolved: Any = None, wraps: str = '') -> Provenance

The provenance of an estimate made from the columns names of the dataset data, over the rows index (with the before rows preceding them for lags): the data's vintages, the sample and how it was chosen (span), the rows used and dropped, method, a fingerprint of the data, the seed and whether an optimiser converged. wraps names the estimator (the spec's type by default). For plugins' results, as pymetrix's own estimators make theirs.

from_inputs classmethod

from_inputs(spec: Any, method: Mapping[str, Any], *, seed: int | None = None, converged: bool | None = None, resolved: Any = None, wraps: str = '') -> Provenance

The provenance of a result computed from numbers given directly rather than a dataset (an option's spot, strike and volatility; CDS spreads): spec records the inputs, method how the result was computed. No data vintages, sample or fingerprint. For plugins' results, as from_data for those made from data.

pymetrix.data.Axis module-attribute

pymetrix.errors.PluginUnavailable

Bases: NotFoundError

Something a plugin provides, asked for while that plugin is disabled or not installed.

pymetrix.estimation.Params module-attribute

Params = PointEstimate | Draws

pymetrix.figures.SIZES module-attribute

SIZES: dict[str, tuple[float, float | None]] = {'column': (89.0, None), 'page': (183.0, None), 'slide': (254.0, 142.875), 'half-a4': (170.0, 120.0)}

PyMetrixError

Bases: Exception

Base class of every error pymetrix raises itself.

random_generator

random_generator(name: str) -> Iterator[str]

Use another bit generator inside the block, then go back to the one before.

registry

registry(group: str) -> Registry

Role

Bases: str, Enum

A variable's role in a model.

set_blas_threads

set_blas_threads(n: int | None) -> None

Set the BLAS threads used during estimation, sampling, identification and sweeps; None leaves them alone.

set_random_generator

set_random_generator(name: str) -> str

Choose the bit generator for every random draw pymetrix makes from now on; returns the previous one.

"pcg64" (the default, NumPy's), "mt19937" (Mersenne Twister), "philox" or "sfc64". Even the Mersenne Twister does not reproduce MATLAB's or Dynare's draws (they seed it and make normal draws differently).

set_theme

set_theme(theme: str | Theme) -> str | Theme

Make a theme the default for figures and reports that do not name one; returns the previous default.

SpecificationError

Bases: PyMetrixError, ValueError

A formula, option or argument that cannot be used as given.

Status

Bases: str, Enum

Observation status, stored in Dataset.flags.

templates

Template models: small, standard models to learn from, check and copy.

from pymetrix.models import templates
nk = templates.new_keynesian()               # three equations: output gap, inflation, policy rate
nk.check()                                   # steady state and Blanchard-Kahn
solution = nk.solve()                        # decision rules, impulse responses, simulations
system = nk.system()                         # state-space form, with the template's measurement equations
system.filter(data)                          # the unobserved variables, from data
templates.new_keynesian(phi=1.2).model       # change a parameter; .model is an ordinary Model to edit

Templates are examples, not classes to inherit: each is a Model of ordinary equations with calibrated parameters, the shocks, their sizes, a starting guess for the steady state, and measurement equations that link the model to the kind of data it is usually fitted to. Copy the equations to start a model of your own.

  • new_keynesian: the textbook three-equation model (Galí 2015, chapter 3), variables in percent deviations from the steady state, quarterly. Observed: annualised inflation, the policy rate, GDP growth.
  • rbc: the stochastic growth model with log utility, full depreciation of the time endowment and a technology shock (King, Plosser and Rebelo 1988), as in the Dynare examples. Variables in levels.
  • gap_model: a small semi-structural model of the kind used in central banks' quarterly projection systems (Berg, Karam and Laxton 2006): output gap, inflation with forward- and backward-looking terms, a policy rule, and the real interest rate. Observed: inflation and the policy rate; the output gap is unobserved, which is what the Kalman filter estimates.
  • qpm: the quarterly projection model of Berg, Karam and Laxton (2006) for a small open economy, as in the IMF's forecasting and policy analysis systems: IS curve, Phillips curve, uncovered interest parity and a forward-looking policy rule in gaps, the trends behind them (potential output and growth, the equilibrium real interest rate and real exchange rate, the inflation target) and a foreign block. Real GDP, the CPI and the nominal exchange rate are levels (100*log) on a balanced growth path (Template.growth), observed as they are, with the foreign output gap, CPI and interest rate and the policy rate. qpm(open=False): the closed economy.

    q = templates.qpm() # BKL's calibration for Canada (their how-to guide, Table 1) q.steady_state().growth # 100*log GDP grows by g_ss/4 a quarter, the CPI by pi_ss/4 smoothed = q.system().filter(data) # gaps and trends from the levels q.solve().solve(smoothed, ("2025Q1", "2027Q4"), Scenario(shift={"e_rs": {"2025Q1": 1.0}})) # a policy scenario

The QPM's equations, with BKL's (how-to guide, IMF WP/06/81; the overview is WP/06/80, equations 1-5), in percent (levels 100*log, rates and inflation a year):

IS (eq. 1; App. II.A):  y_gap = beta_ld y_gap[+1] + beta_lag y_gap[-1] - beta_rrgap rr_gap[-1] + beta_zgap z_gap[-1]
                                + beta_rw y_gap_rw + e_y_gap
Phillips (eq. 2):       pi = alpha_pild pi4[+4] + (1 - alpha_pild) pi4[-1] + alpha_ygap y_gap[-1]
                             + alpha_z (z - z[-1] - dz_bar/4) + e_pi
UIP (eqs. 3-4):         z = delta_z z[+1] + (1 - delta_z)(z[-1] + dz_bar/2) - (rr - rr_rw - prem)/4 + e_z
policy rule (eq. 5):    rs = gamma_rslag rs[-1] + (1 - gamma_rslag)(rr_bar + pi4 + gamma_pi (pi4[+4] - pi_tar[+4])
                             + gamma_ygap y_gap) + e_rs
premium (App. II.B):    prem = 4 (z_bar - z_bar[+1]) + rr_bar - rr_bar_rw
potential (App. II.B):  4 (l_gdp_bar - l_gdp_bar[-1]) = g_bar + e_l_gdp_bar; g_bar, rr_bar, pi_tar: AR(1) to their
                        steady states; z_bar = z_bar[-1] + dz_bar/4 + e_z_bar, dz_bar AR(1)
identities (App. II.C): l_gdp = l_gdp_bar + y_gap, rr = rs - pi[+1], pi = 4 (l_cpi - l_cpi[-1]), pi4 = l_cpi - l_cpi[-4],
                        z = l_s + l_cpi_rw - l_cpi, rr_gap = rr - rr_bar, z_gap = z - z_bar
foreign: y_gap_rw, pi_rw, rs_rw and rr_bar_rw AR(1); rr_rw = rs_rw - pi_rw[+1]

The terms in dz_bar keep the path balanced when the equilibrium real exchange rate trends (BKL's footnote 16 notes the issue); with dz_ss = 0 and no trend shock they vanish and the equations are BKL's. BKL's Appendix II has the equilibrium real exchange rate stationary around a constant; here it is a random walk with drift, as in later QPMs.

themes

themes() -> list[str]

The names of the themes: the built-in ones and those added since (Theme.from_style, set_theme).

toolkit

Building blocks for writing your own estimators and solution methods.

These are the pieces pymetrix's own estimators are made of, kept stable as part of the Extension API. A custom estimator written with them works like a built-in one: in Equation.fit, the Estimate dialog (once registered), scripts, projects, group loops and Results tables.

Data to arrays:

d = design("c ~ y + c[-1]", data, span=("2000Q1", None))   # d.y, d.X, d.names, d.index
index, M = arrays(data, ["c", "y"])                          # plain columns as a matrix

Inference:

beta, u = least_squares(d.y, d.X)
V = covariance("hac", d.X, u, d.df_resid)                    # classic, white, hac, Cluster(...)
V = sandwich(H, scores, kind="white")                        # for M- and ML estimators
H = hessian(f, x); J = jacobian(g, x)                        # numerical derivatives

Results:

return result(eq, data, d, self, beta, V, u)                 # a FittedEquation, with statistics

A worked estimator (ridge regression) and solver (damped Newton) are in examples/custom_estimator.py and examples/custom_solver.py; see also the help topic "Writing your own estimator".

Variable dataclass

Variable(name: str, label: str = '', description: str = '', units: str = '', scale: int = 0, measure: Measure | None = None, prices: Prices = NONE, base_period: str | None = None, adjustment: Adjustment = NSA, source: str = '', source_key: str = '', vintage: Vintage | None = None, release_lag: int | None = None, derived_from: str | None = None, symbol: str | None = None, extra: Mapping[str, Any] = dict(), recipe: Any = None, retrieved: str = '', external_ref: str = '')

Metadata for one series (one column of a Dataset).

Where a series came from, the minimum pymetrix keeps itself: source (the provider or file, in words), source_key (the series' ID there, also source_id), vintage (when the provider released the data; never when they were loaded), retrieved (when pymetrix fetched or imported them, ISO 8601), and the units, frequency and recipe (derived or not). external_ref is for a plugin with a richer source system (e.g. a statistical data management system): an opaque reference to its own record of the series, which pymetrix keeps, saves and shows but does not interpret.

source_id property

source_id: str

The series' ID at its source (source_key).

Vintage dataclass

Vintage(released: date, retrieved: datetime | None = None, revision: int | None = None)

When data was released. released is the release date, never the load date.