Skip to content

Bayesian methods

The classes and functions of the row "Bayesian methods" 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: Bayesian estimation of an equation, Bayesian VARs, BVARs with stochastic volatility, FAVARs and Markov-switching VARs, Vector autoregressions, The forecast workflow, TVP-VARs with stochastic volatility.

Classes

Bayes dataclass

Bayes(prior: Annotated[str | Mapping[str, _Prior] | None, Widget('text', help='priors by coefficient, mean and standard deviation, e.g. x=Normal(0.5, 0.1); sigma=InvGamma1(1, 1) (Normal, Beta, Gamma, InvGamma, InvGamma1, Uniform); empty = flat')] = None, draws: Annotated[int, Widget('number', min=100, max=1000000, step=500, help='posterior draws kept per chain after the burn-in; more lower the Monte Carlo error of the summaries')] = 5000, sampler: Annotated[Literal['auto', 'rwmh', 'nuts'], Widget('choice', advanced=True, help='auto: Gibbs where every step is exact, else random-walk Metropolis-Hastings; nuts: the No-U-Turn sampler (gradients), whose burn-in adapts its step size and mass matrix')] = 'auto', seed: Annotated[int | None, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='random seed; empty = a fresh one')] = 0, chains: Annotated[int, Widget('number', min=1, max=16, help='independent chains, for R-hat')] = 2, burn: Annotated[int, Widget('number', min=0, max=1000000, step=500, advanced=True, help='draws discarded at the start of each chain')] = 1000, metric: Annotated[Literal['diag', 'dense', 'mode'], Widget('choice', advanced=True, show_if=('sampler', ('nuts',)), help='NUTS: the mass matrix; dense undoes correlations between coefficients (adapted in the burn-in), mode keeps the inverse Hessian at the mode')] = 'diag', likelihood: Annotated[Literal['exact', 'conditional'], Widget('choice', advanced=True, help='ARMA errors: exact (Kalman filter), or conditional on the first p observations (AR errors only; every step exact, priors on the AR coefficients themselves)')] = 'exact')

Bayesian estimation, of VARs (by their priors) and of single equations (by coefficient priors).

For VARs: ``prior=Minnesota(...)``, with exact posterior draws, or ``prior=NormalWishart(...)``, sampled by Gibbs.
For single equations (Gaussian, logit, probit, Poisson): ``prior={"x": Normal(0.5, 0.1), "sigma": InvGamma1(1, 1)}``
by coefficient name, flat where none is given; ``sampler="auto"`` is Gibbs where every step is exact (normal or flat
coefficient priors, an inverse gamma or none on a Gaussian error) and random-walk Metropolis-Hastings otherwise

(sampler="rwmh" always), and sampler="nuts" the No-U-Turn sampler with analytic gradients (metric its mass matrix: "diag", "dense" or "mode", as FittedModel.mcmc); chains chains of draws each after burn. See pymetrix.estimation.bayes_equation.

An equation with ARMA errors (``Equation("y ~ x", errors=ARMA(1, 1))``, or ``errors="arma(1,1)"``) is sampled by
Metropolis within Gibbs on the exact likelihood, its AR and MA priors (``"ar[1]": Uniform(0, 1)``) on their partial
autocorrelations; ``likelihood="conditional"`` conditions on the first p observations for AR errors, every step
exact. See pymetrix.estimation.bayes_arma.

A single equation's priors can also be typed, as the Estimate dialog gives them: ``prior="x=Normal(0.5, 0.1);
sigma=InvGamma1(1, 1)"`` (by mean and standard deviation; read into the dictionary of priors).

BMA dataclass

BMA(outcome: Annotated[str, Widget('text', help='the series to explain or forecast, e.g. dlog(gdp)')], candidates: Annotated[tuple[str, ...], Widget('text', help='regressors that may or may not belong, e.g. spread[-1], pmi[-1]')], always: Annotated[tuple[str, ...], Widget('text', advanced=True, help='regressors in every model (besides the intercept)')] = (), g: Annotated[float, Widget('number', min=0, max=1000000000.0, advanced=True, help="the g-prior's g; 0 = the benchmark max(n, K^2)")] = 0.0)

Bayesian model averaging over every subset of candidate regressors, with Zellner's g-prior.

Each model has an intercept, the always regressors and a subset of the candidates; all models are equally likely a priori. g 0 means the benchmark prior, max(n, K^2).

fit

fit(data: Dataset, span: Any = None) -> FittedBMA

Fit every model on the periods of span (first, last) and weight each by its posterior probability.

BVARSV dataclass

BVARSV(variables: Sequence[str], lags: int = 4)

A Bayesian VAR with stochastic volatility: constant coefficients, drifting shock volatilities.

GLP dataclass

GLP(mcmc: Annotated[bool, Widget('checkbox', help='integrate over the hyperparameters by MCMC (else: at their posterior mode)')] = False, sum_of_coefficients: Annotated[bool, Widget('checkbox', help='the sum-of-coefficients prior (mu), with its hyperprior')] = True, initial_observation: Annotated[bool, Widget('checkbox', help='the single-unit-root prior (delta), with its hyperprior')] = True, own_mean: Annotated[float | Mapping[str, float], Widget('number', help="prior mean of each variable's own first lag: 1 for levels, 0 for growth rates")] = 1.0, decay: Annotated[float, Widget('number', min=0, max=4, advanced=True, help="lag l's prior standard deviation shrinks as 1/l**decay (GLP: 1)")] = 1.0, tightness_mode: Annotated[float, Widget('number', min=0.001, max=5, advanced=True, help='mode of the gamma hyperprior on lambda')] = 0.2, tightness_sd: Annotated[float, Widget('number', min=0.001, max=10, advanced=True, help='standard deviation of the gamma hyperprior on lambda')] = 0.4, soc_mode: Annotated[float, Widget('number', min=0.001, max=50, advanced=True, help='mode of the gamma hyperprior on mu')] = 1.0, soc_sd: Annotated[float, Widget('number', min=0.001, max=50, advanced=True, help='standard deviation of the gamma hyperprior on mu')] = 1.0, dio_mode: Annotated[float, Widget('number', min=0.001, max=50, advanced=True, help='mode of the gamma hyperprior on delta')] = 1.0, dio_sd: Annotated[float, Widget('number', min=0.001, max=50, advanced=True, help='standard deviation of the gamma hyperprior on delta')] = 1.0, psi_shape: Annotated[float, Widget('number', min=0, advanced=True, help='shape of the inverse-gamma hyperprior on each psi')] = 0.02 ** 2, psi_scale: Annotated[float, Widget('number', min=0, advanced=True, help='scale of the inverse-gamma hyperprior on each psi')] = 0.02 ** 2, burn: Annotated[int, Widget('number', min=0, max=1000000, advanced=True, help='MCMC draws of the hyperparameters discarded first')] = 2000, deterministic: Annotated[float, Widget('number', advanced=True, help='prior variance of the constant, trend and exogenous terms (loose)')] = 1000000.0, scale_lags: Annotated[int, Widget('number', min=1, max=12, advanced=True, help='lags of the autoregressions that centre and bound psi')] = 1, decay_hyperprior: Annotated[bool, Widget('checkbox', advanced=True, help='estimate the lag decay too, with a gamma hyperprior (else: fixed at decay)')] = False, decay_mode: Annotated[float, Widget('number', min=0.01, max=4, advanced=True, help='mode of the gamma hyperprior on the lag decay')] = 1.0, decay_sd: Annotated[float, Widget('number', min=0.001, max=10, advanced=True, help='standard deviation of the gamma hyperprior on the lag decay')] = 0.5)

The hierarchical Minnesota prior of Giannone, Lenza and Primiceri (2015): hyperpriors on the tightness, the sum-of-coefficients and single-unit-root hyperparameters and the prior scales psi, which are estimated at their posterior mode or integrated over by MCMC.

Minnesota dataclass

Minnesota(tightness: Annotated[float, Widget('number', min=0.0001, max=10, step=0.05, help='overall tightness (lambda); smaller shrinks more')] = 0.2, decay: Annotated[float, Widget('number', min=0, max=4, help='longer lags shrink as 1/lag**decay')] = 2.0, own_mean: Annotated[float | Mapping[str, float], Widget('number', help="prior mean of each variable's own first lag: 1 for levels (random walk), 0 for growth rates")] = 1.0, sum_of_coefficients: Annotated[float | None, Widget('number', help='sum-of-coefficients prior (mu); smaller pulls harder towards unit roots; empty = none')] = None, initial_observation: Annotated[float | None, Widget('number', help='single-unit-root prior (delta); empty = none')] = None, optimize: Annotated[bool, Widget('checkbox', help='choose the hyperparameters by maximising the marginal likelihood')] = False, deterministic: Annotated[float, Widget('number', advanced=True, help='prior variance of the constant, trend and exogenous terms (loose)')] = 1000000.0, scale_lags: Annotated[int, Widget('number', min=1, max=12, advanced=True, help='lags of the univariate autoregressions that scale the prior')] = 1)

The Minnesota prior for a VAR, with optional dummy-observation priors.

NormalWishart dataclass

NormalWishart(tightness: Annotated[float, Widget('number', min=0.0001, max=10, step=0.05, help='overall tightness (lambda); smaller shrinks more')] = 0.2, cross_tightness: Annotated[float, Widget('number', min=0.0001, max=1, step=0.05, help="relative tightness of other variables' lags (theta); 1 = as own lags")] = 0.5, decay: Annotated[float, Widget('number', min=0, max=4, help='longer lags shrink as 1/lag**decay')] = 2.0, own_mean: Annotated[float | Mapping[str, float], Widget('number', help="prior mean of each variable's own first lag: 1 for levels (random walk), 0 for growth rates")] = 1.0, sum_of_coefficients: Annotated[float | None, Widget('number', help='sum-of-coefficients prior (mu), as dummy observations; empty = none')] = None, initial_observation: Annotated[float | None, Widget('number', help='single-unit-root prior (delta), as dummy observations; empty = none')] = None, deterministic: Annotated[float, Widget('number', advanced=True, help='prior variance of the constant, trend and exogenous terms (loose)')] = 1000000.0, scale_lags: Annotated[int, Widget('number', min=1, max=12, advanced=True, help='lags of the univariate autoregressions that scale the prior')] = 1, burn: Annotated[int, Widget('number', min=0, max=100000, advanced=True, help='Gibbs draws discarded before the posterior draws are kept')] = 1000, optimize: Annotated[bool, Widget('checkbox', help="choose the hyperparameters by Chib's estimate of the marginal likelihood")] = False)

The Minnesota prior in its independent normal-Wishart form, sampled by Gibbs: the coefficients B ~ N(b, V) apart from Sigma ~ IW. Unlike the conjugate prior, other variables' lags can be shrunk harder than a variable's own (cross_tightness below 1), and each equation's prior does not depend on the others' error variances.

The coefficient on lag l of variable j in equation i has prior standard deviation tightness / l^decay, times cross_tightness sqrt(psi_i / psi_j) when j is not i (psi from univariate autoregressions); Sigma ~ IW with mean diag(psi), as in the conjugate prior. There is no closed-form marginal likelihood: Chib's (1995) estimate from the Gibbs draws stands in for it (pymetrix.bvar_hierarchical), and with optimize=True the hyperparameters maximise it.

TVPVAR dataclass

TVPVAR(variables: Sequence[str], lags: int = 2)

A time-varying-parameter VAR with stochastic volatility, estimated by Gibbs sampling (Primiceri 2005).

fit

fit(data: Dataset, draws: int = 2000, burn: int = 1000, training: int = 40, kq: float = 0.01, ks: float = 0.1, kw: float = 0.01, thin: int = 1, seed: int = 0) -> FittedTVPVAR

Gibbs sampling: burn draws discarded, then draws kept (every thin-th); priors from least squares on the first training periods (see the module notes). The data's active sample (with_sample) is used as if the data had been trimmed to it: the lags and the training periods are its first periods.

Results

FittedBMA dataclass

FittedBMA(spec: BMA, models: list[list[int]], posterior: ndarray, coefs: ndarray, variances: ndarray, mean: ndarray, sd: ndarray, inclusion: ndarray, g: float = 0.0, nobs: int = 0, frame: DataFrame = DataFrame(), provenance: Any = None)

A Bayesian model average: every model's posterior probability and coefficients, and the averages.

summary

summary() -> Table

Posterior inclusion probabilities and the model-averaged coefficients (means and sds), most probable first.

models_table

models_table(top: int = 10) -> Table

The top most probable models: their posterior probabilities and regressors.

forecast

forecast(data: Dataset, span: tuple[Any, Any], coverage: float = 0.95, dynamic: bool = False) -> Any

Model-averaged forecasts for the periods of span whose regressors are known (like an equation's static forecasts): each model's predictive Student-t, averaged with the posterior probabilities. Columns: forecast, se (of the mixture), lower and upper (a normal approximation), and actual where known.

plot

plot() -> Any

Posterior inclusion probabilities.

FittedBVAR dataclass

FittedBVAR(spec: VAR, lags: int, estimate: _Estimate, arrays: _Arrays, identification: Any = Cholesky(), provenance: Provenance | None = None, restriction: Any = None, method: Any = None, hyperparameters: Mapping[str, float] = dict(), log_ml: float = nan, posterior: Any = None, draws_B: ndarray | None = None, draws_sigma: ndarray | None = None, hyperparameter_draws: DataFrame | None = None)

Bases: FittedVAR

A Bayesian VAR: the posterior mean as the point estimate, with posterior draws for bands.

independent property

independent: bool

Whether the prior is the independent normal-Wishart, sampled by Gibbs.

from_draws property

from_draws: bool

Whether the point estimates are the draws' means and covariance (the independent prior, or GLP's prior integrated over its hyperparameters) rather than a conjugate posterior's.

mcse

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

Monte Carlo standard errors of the posterior means and quantiles of the coefficients (and of the hyperparameters when they were sampled), with effective sample sizes: from the draws' autocorrelations (method="ess") or batch means ("batch"). Exact conjugate draws are independent (ESS near the number of draws); Gibbs and Metropolis-Hastings draws are not.

explosive_share

explosive_share() -> float

Share of posterior draws whose companion matrix has a root on or outside the unit circle.

irf

irf(periods: int = 20, orthogonal: bool = True, cumulative: bool = False, draws: int | None = None, coverage: float = 0.95, seed: int = 0) -> IRF

Posterior median responses with coverage credible bands, from the posterior draws (all, or the first draws; 0 for the responses at the posterior mean without bands). Under sign restrictions, one accepted rotation for each posterior draw; with zero restrictions too, ARW's draws, importance-weighted and resampled (see pymetrix.zerosign).

fevd

fevd(periods: int = 20) -> Any

Variance decomposition at the posterior mean.

forecast

forecast(data: Dataset, span: tuple[Any, Any], coverage: float = 0.95, dynamic: bool = True, draws: int | None = None, seed: int = 0) -> Dataset

Forecasts from the predictive distribution: each posterior draw simulates a path with its own shocks, so the intervals include parameter uncertainty. Columns: mean, sd, median and the coverage interval.

conditional_forecast

conditional_forecast(data: Dataset, span: tuple[Any, Any], conditions: Mapping[str, Any], coverage: float = 0.95, draws: int | None = None, seed: int = 0, shocks: Sequence[str] | None = None, shock_conditions: Mapping[str, Any] | None = None, update_posterior: bool = False) -> Dataset

Forecasts given conditions on some variables, from the predictive distribution: for each posterior draw, a path that meets the conditions (Waggoner and Zha 1999 for exact ones; a truncated-normal Gibbs sampler for ranges), with the shocks the conditions leave free drawn at random, so the intervals include parameter uncertainty. Conditions, shocks and shock_conditions as for FittedVAR.conditional_forecast; the impact matrix of the identification is recomputed for each draw.

By default the posterior itself is not updated by the conditions (the usual shortcut): each posterior draw is conditioned in turn. update_posterior=True runs Waggoner and Zha's Gibbs sampler instead, which alternates a path given the parameters and the conditions with the parameters given the data and that path (the path treated as extra observations under the same prior and hyperparameters), so the conditions also inform the parameters; it needs every shock free to move (shocks=None, no shock_conditions), keeps draws iterations (default: as many as the posterior draws) after 200 of burn-in, and is slower.

predictive_draws

predictive_draws(data: Dataset, span: tuple[Any, Any], draws: int | None = None, seed: int = 0) -> tuple[PeriodIndex, ndarray]

Simulated forecast paths, one per posterior draw with its own shocks: the periods, and an array (draws, periods, variables) in the order of variables. forecast summarises them; backtests score them.

FittedBVARSV dataclass

FittedBVARSV(spec: BVARSV, B: ndarray, A: ndarray, h: ndarray, w: ndarray, index: Index, X: ndarray, Y: ndarray, provenance: Any = None)

Posterior draws of a BVAR with stochastic volatility.

coefs property

coefs: ndarray

The posterior mean lag matrices, (lags, K, K).

volatilities

volatilities(coverage: float = 0.68) -> DataFrame

Each shock's standard deviation by period: the posterior median and band.

irf

irf(periods: int = 20, period: Any = None, coverage: float = 0.68) -> Any

Recursively identified responses with that period's volatilities (default: the last), median and bands across the draws.

fevd

fevd(periods: int = 20, period: Any = None, coverage: float = 0.68) -> Any

Forecast-error variance decomposition with that period's volatilities (default: the last), as for irf: for each draw the shares of the recursively identified shocks (impact A^-1 D_t), the volatilities held at their values in that period over the horizon. The point shares are the posterior means (so each row adds up to one), the bands pointwise quantiles over the draws.

historical_decomposition

historical_decomposition(coverage: float = 0.68, draws: int | None = None) -> Any

Each variable over the sample, split into the contributions of the recursively identified shocks and the baseline (the path from the first observations and the constants, with no shocks), for each posterior draw (all, or the first draws): the residuals u_t = y_t - B'x_t, the structural shocks e_t = D_t^-1 A u_t through that period's impact matrix A^-1 D_t, and their contributions through the draw's lag matrices. Each draw's parts add up to the data exactly; the point decomposition is their mean over draws (which does too), the bands pointwise quantiles. A shock's contribution in a period, A^-1[:, j] (A u_t)_j, does not depend on the volatility (it scales the shock and its impact in opposite directions); the standardised shocks do.

FittedTVPVAR dataclass

FittedTVPVAR(spec: TVPVAR, index: Index, beta: ndarray, a: ndarray, h: ndarray, training: int = 40, m: int = 1, settings: dict[str, Any] = dict(), provenance: Any = None)

Posterior draws of a TVP-VAR-SV's paths: coefficients, contemporaneous relations and volatilities.

volatilities

volatilities(coverage: float = 0.68) -> DataFrame

Each shock's standard deviation over time: posterior median and bands.

coefficient_paths

coefficient_paths(coverage: float = 0.68) -> DataFrame

Each coefficient's posterior median over time (columns: equation, regressor).

irf

irf(period: Any = None, periods: int = 20, coverage: float = 0.68) -> Any

Responses to one-standard-deviation recursive shocks at period (default: the last), from every draw's coefficients and covariance at that date: the posterior median, with bands.

irf_paths

irf_paths(periods: int = 20, draws: int = 200) -> ndarray

The posterior median responses at every date: (dates, horizons 0 to periods, responses, shocks), as irf gives them at one date, from draws of the kept draws evenly spaced (all of them if fewer).

irf_over_time

irf_over_time(response: str, shock: str, periods: int = 20, draws: int = 200) -> DataFrame

How response answers shock at each date: posterior medians, the dates down the rows and the horizons (0 to periods) across (see irf_paths).

irf_surface

irf_surface(periods: int = 20, draws: int = 200, responses: Sequence[str] | None = None, shocks: Sequence[str] | None = None) -> Figure

The responses as they changed over time: a surface for each response and shock, horizons along x, dates along y, the posterior median response as height (irf_over_time).