VARs & structural identification¶
The classes and functions of the row "VARs & structural identification" 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: Vector autoregressions, Cointegration and VECMs, Structural VARs by A-B restrictions, BVARs with stochastic volatility, FAVARs and Markov-switching VARs, Generalised impulse responses of nonlinear models, Smooth-transition autoregressions, Markov-switching models, Bootstrap bands and intervals, Panel VARs, Proxy SVARs, Quantile regression, Bayesian VARs, Unit roots and stationarity.
How do I: Estimate a VAR, then impulse responses and a forecast, Check whether a result survives other specifications.
Classes¶
AB
dataclass
¶
AB(A: Sequence[Sequence[Any]] | None = None, B: Sequence[Sequence[Any]] | None = None, long_run: Sequence[Sequence[Any]] | None = None, starts: int = 10, seed: int = 0)
Identification by restrictions on A and B (A u = B e); "*" marks a free entry, numbers are fixed. A is the
identity and B entirely free unless given; long_run sets zeros (or other fixed values) of the long-run
effects, with A the identity.
Bounds
dataclass
¶
A range condition: the variable (or shock) is at least lower and at most upper in a period; leave one
out (None) for a one-sided condition. Bounds(3, 4) is "between 3 and 4".
Cholesky
dataclass
¶
Recursive identification; order lists the variables from most to least exogenous
(default: the VAR's own order).
EngleGranger
dataclass
¶
EngleGranger(variables: Annotated[str, Widget('', help='the series, comma-separated: the first is regressed on the others and the residuals tested')], trend: Annotated[Literal['c', 'ct', 'ctt', 'n'], Widget('', help='terms in the levels regression: c constant, ct adds a trend, ctt a quadratic, n none')] = 'c', autolag: Annotated[Literal['aic', 'bic', 't-stat'], advanced(help="how the residuals' ADF lags are chosen: aic, bic, or t-stat (drop the last until significant)")] = 'aic', max_lags: Annotated[str | int, advanced(help="largest lag of the residuals' ADF regression searched; empty = 12*(n/100)^(1/4), capped in short samples to keep 4 residual degrees of freedom after the levels regression")] = '', backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments')] = dict(), critical_values: Annotated[Literal['mackinnon', 'simulated'], Widget('', help=_CRITICAL_HELP)] = 'mackinnon', draws: Annotated[int, advanced(help=_DRAWS_HELP)] = 2000, seed: Annotated[int, advanced(help=_SEED_HELP)] = 0, exog: Annotated[str, advanced(help='fixed regressors in the levels regression that are not I(1), comma-separated (impulse or break dummies); they enter every simulated regression as given. Needs critical values = simulated')] = '')
Bases: Test
Engle-Granger (augmented) cointegration test: the first variable is regressed on the others.
The first step regresses the first variable on the others and the deterministic terms by least squares; the second runs an ADF regression, without deterministic terms, on its residuals. The null is no cointegration (the residuals have a unit root); a large negative statistic rejects it in favour of a stationary combination. The p-values and critical values are MacKinnon's for residual-based tests: they depend on the number of variables and the trend, and are further out than ordinary ADF values because the coefficients are estimated. The result can depend on which variable comes first, and the test cannot say how many relations there are: with three or more variables, Johansen's tests count them. After a rejection, estimate the relation by FMOLS or DOLS for valid standard errors, or fit an error-correction model.
MacKinnon's values are asymptotic, and with 13 to 30 observations they are far off. With
critical_values="simulated" they are simulated for this sample instead: draws sets of independent Gaussian
random walks, one per variable, of the sample's length (seeded by seed), each tested exactly as the data are
(the same trend terms in the levels regression, the same ADF regression on the residuals and the same lag
search). Columns named in exog that are not I(1), such as impulse or break dummies, enter the levels
regression of the data and of every draw as given. The critical values are the 1, 5 and 10% quantiles of the
draws' statistics and the p-value is the share at or below the statistic, with its Monte Carlo standard error.
GeneralisedIRF
dataclass
¶
GeneralisedIRF(values: ndarray, groups: tuple[str, ...], sizes: tuple[float, ...], responses: tuple[str, ...], shocks: tuple[str, ...], regime_dynamics: str = 'evolve', identification: str = '', model: str = '', histories: tuple[int, ...] = (), draws: int = 0, seed: int = 0, lower: ndarray | None = None, upper: ndarray | None = None, difference_lower: ndarray | None = None, difference_upper: ndarray | None = None, coverage: float = 0.68, band_draws: int = 0, band_source: str = '', notes: tuple[str, ...] = (), provenance: Any = None)
Generalised impulse responses values[group, size, horizon, response, shock] of a nonlinear model, by
history group; lower and upper the bands from parameter draws, if asked for. differences() gives each
group's responses minus the first group's.
response
¶
response(group: str | int = 0, size: float | None = None, response: str | None = None, shock: str | None = None) -> Series
One response by horizon: of response (default the first variable) to shock (default the first) of
size (default the first) in group (a label or its position).
to_frame
¶
Every response by horizon, a column "group, size s: response <- shock" each (with its lower and upper
band, if any); or one of the views by name.
differences
¶
Each group's responses minus the first group's (e.g. recession minus expansion), by horizon, with bands from the same parameter draws if there are any. Empty with a single group.
scaled
¶
The responses divided by the shock's size: for a linear model every size gives the same paths, so differences between them are the model's asymmetry (sign) and nonlinearity in size.
summary
¶
summary() -> Table
Impact, peak and the last horizon's response for each group, size, response and shock.
plot
¶
plot(response: str | None = None, shock: str | None = None, scaled: bool = True) -> Figure
A panel per response and shock, a line per group and size (divided by the size when scaled and there are
several sizes, so the lines of a linear model would coincide), with the bands; then the differences between
groups.
Granger
dataclass
¶
Granger(cause: Annotated[str | Sequence[str], Widget('text', help='the variables whose lags are tested')], effect: Annotated[str | Sequence[str], Widget('text', help='the variables they may help predict')])
Bases: Test
Do lags of cause help predict effect? Wald test on the VAR, reported as F.
The null is that every lag of the causing variables has a zero coefficient in the equations of the caused ones: given the past of the other variables, they do not help predict them. For a VAR the Wald statistic over the number of restrictions is reported as F, with the chi-squared form in the details; for a VECM statsmodels computes the test. Granger causality is about prediction, not structural causation, and it is relative to the variables in the system: an omitted variable can create or hide it. With integrated variables in a VAR in levels the statistic need not have its usual distribution, so treat its p-value with caution, or test in a VECM when the variables are cointegrated.
HeteroskedasticitySVAR
dataclass
¶
HeteroskedasticitySVAR(variables: tuple[str, ...], breaks: tuple[str, ...], impact: ndarray, ratios: ndarray, regime_sigmas: tuple[ndarray, ...], regime_nobs: tuple[int, ...] = (), coefs: ndarray = None, provenance: Any = None)
A VAR identified through shifts in its shocks' variances (Rigobon 2003).
fevd
¶
Forecast-error variance decomposition in the first variance regime, where each shock has unit variance.
LongRun
dataclass
¶
Blanchard-Quah: the long-run effects of the shocks are lower triangular.
MaxShare
dataclass
¶
One shock: the one that explains the largest share of variable's forecast-error variance between start
and horizon periods ahead (zero_impact: none of it on impact, as for news shocks).
MSVAR
dataclass
¶
MSVAR(variables: Sequence[str], lags: int = 1, regimes: int = 2, switching: Literal['intercept', 'intercept_variance', 'all'] = 'intercept_variance')
A Markov-switching VAR.
fit
¶
fit(data: Dataset, starts: int = 10, max_iter: int = 5000, tol: float = 1e-12, seed: int = 0, span: Any = None) -> FittedMSVAR
Maximum likelihood by EM and a polish of the exact likelihood. starts: the random soft splits are
starts - 1 of the starting regime paths, after those read off the data (pymetrix.ms_var_em);
max_iter: EM iterations from each start; tol: EM stops when the log likelihood changes by less than
this, relative (no tighter than 1e-8: the polish finishes); seed: the random splits and k-means.
PhillipsOuliaris
dataclass
¶
PhillipsOuliaris(variables: Annotated[str, Widget('', help='the series, comma-separated; the first is the dependent variable (Pz is the same in any order)')], trend: Annotated[Literal['c', 'ct', 'ctt', 'n'], Widget('', help='terms in the cointegrating regression: c constant, ct adds a trend, ctt a quadratic, n none')] = 'c', test_type: Annotated[Literal['Zt', 'Za', 'Pu', 'Pz'], Widget(kind='', help='Zt and Za: corrected Dickey-Fuller on the residuals; Pu: variance ratio; Pz: trace, the same whichever variable is first')] = 'Zt', kernel: Annotated[Literal['bartlett', 'parzen', 'qs'], advanced(help='kernel for the long-run variance (qs: quadratic spectral)')] = 'bartlett', bandwidth: Annotated[str | int, advanced(help='kernel bandwidth; empty = chosen from the data')] = '', backend_options: Annotated[BackendOptions, Widget('', advanced=True, help="further arguments for arch's phillips_ouliaris, e.g. force_int; not those set above")] = dict())
Bases: Test
Phillips-Ouliaris residual-based cointegration tests (Zt, Za, Pu, Pz), computed by arch.
Zt and Za correct the Dickey-Fuller statistics of the cointegrating regression's residuals for serial correlation nonparametrically (a kernel long-run variance), with no lag choice; Pu and Pz are variance-ratio and trace statistics. Pz does not depend on which variable is normalised as dependent.
The null is no cointegration; Zt and Za reject when small (large and negative), Pu and Pz when large, as the details say. Their appeal over Engle-Granger is that no lag length need be chosen; the price is that kernel corrections of this kind can reject too often in small samples when the errors have a large negative moving-average component, and that the kernel and bandwidth then matter. As with Engle-Granger, Zt, Za and Pu can depend on which variable is first, and none of them counts the cointegrating relations. With the bandwidth left empty, arch chooses it, and arch 9.0 chooses it differently from earlier versions (Newey and West's rule as R's sandwich has it); the details record arch's version and the bandwidth used.
Portmanteau
dataclass
¶
Portmanteau(lags: Annotated[int, Widget('', help='residual autocorrelations tested; more than the VAR order, best well beyond it')] = 10, adjusted: Annotated[bool, Widget('checkbox', help='small-sample adjusted statistic')] = False)
Bases: Test
Multivariate portmanteau (Ljung-Box type) test of residual autocorrelation up to lags.
The null is that the residuals of every equation are uncorrelated with each other's and their own past up to the given lag. For a VAR the statistic is chi-squared with K^2 (lags - p) degrees of freedom, K the number of variables and p the VAR's order, so the lag must exceed the order, and the approximation is good only well beyond it; for a VECM statsmodels computes the test. The adjusted statistic is closer to its distribution in small samples. A rejection suggests adding lags to the VAR.
ProxySVAR
dataclass
¶
ProxySVAR(var: Any, instrument: str = '', normalise_on: str = '', scale: str = 'sd', impact: Series = None, irf: Any = None, first_stage: tuple[float, float] = (nan, nan), nobs: int = 0, z: Any = None, block: int | None = None, provenance: Any = None)
A VAR's shock identified by an external instrument: its impact, responses with bands, and the first stage.
historical_decomposition
¶
Each variable over the VAR's sample, split into the identified shock's contribution, the other shocks' contribution combined, and the baseline (the path from the first observations and the deterministic terms, with no shocks). The parts add up to the data exactly.
The identified shock is e(t) = b' Sigma^-1 u(t) / (b' Sigma^-1 b), the part of the residuals along the
impact column b, whatever its scale; its contribution propagates b e(t) through the VAR, the other shocks'
propagates u(t) - b e(t). The other shocks are not identified one by one, so they are shown together.
With draws, coverage bands: quantiles over the decompositions of the data under Jentsch and
Lunsford's moving-block bootstrap draws (the residuals and the proxy resampled together, the VAR and the
impact column estimated again), the draws the impulse-response bands use for the same seed. Returns a
Decomposition.
QuantileVAR
dataclass
¶
A recursive quantile VAR at one quantile for every equation.
Restricted
dataclass
¶
Restricted(zeros: Mapping[str, Sequence[str]] = dict(), block_exogenous: Sequence[str] = (), iterate: bool = False, max_iter: int = 100)
Zero restrictions on a VAR's coefficients, estimated by feasible GLS (seemingly unrelated regressions,
Lutkepohl 2005, section 5.2): each equation's own regressors; the residual covariance from least squares on them,
then GLS (iterate=True: until the estimates settle, the maximum-likelihood estimate).
zeros maps an equation to the regressors left out of it: a variable (all its lags), one lag ("r[-2]"), or
a deterministic or exogenous term ("const"). block_exogenous variables' equations leave out the other
variables' lags (a small open economy's world block, say).
mask
¶
Which coefficients (regressor, equation) are estimated.
SignRestrictions
dataclass
¶
SignRestrictions(signs: Mapping[str, Mapping[str, Any]] = dict(), horizon: int = 0, rotations: int = 1000, max_tries: int = 200000, seed: int = 0, narrative_signs: Mapping[str, Mapping[str, str]] = dict(), narrative_major: Mapping[str, Mapping[str, str]] = dict(), zeros: Mapping[str, Sequence[str]] = dict(), long_run_zeros: Mapping[str, Sequence[str]] = dict())
Set identification by the signs of responses (Uhlig 2005; Rubio-Ramírez, Waggoner and Zha 2010).
signs names each identified shock and the signs its responses must have, on impact and for horizon
periods after: {"supply": {"gy": "+", "pi": "-"}, "demand": {"gy": "+", "pi": "+"}}. Random orthogonal
rotations of the Cholesky factor (uniform, by QR) are kept when some column, or its negative, satisfies each
shock's signs, until rotations are accepted (or max_tries drawn). Shocks not named are left
unidentified. Responses are the pointwise median of the accepted draws; the impact matrix (for variance
decompositions) is the accepted draw closest to that median (Fry and Pagan's median target).
narrative_signs and narrative_major add Antolin-Diaz and Rubio-Ramirez's narrative restrictions: a named
shock's sign at a date, or that it was the largest contributor to a variable's surprise at a date (see
pymetrix.identification_extra).
zeros and long_run_zeros add zero restrictions (Arias, Rubio-Ramírez and Waggoner 2018): the variables a
shock does not move on impact, or in the long run (the cumulated response, for variables in differences):
zeros={"monetary": ["gy", "pi"]}. A shock may have zeros and no signs. With zeros, rotations are drawn column
by column in the null space of the zeros (ARW's algorithm), each column signed by its first sign restriction and
kept if every sign holds (shocks keep their columns: no search over columns), with ARW's importance weights; the
kept draws are resampled by weight (see pymetrix.zerosign). Ordered by their number of zeros, the first shock
may have n - 1, the next n - 2, and so on.
named
property
¶
The identified shocks: those with signs, then any with zeros only.
VAR
dataclass
¶
VAR(variables: Annotated[Sequence[str], Widget('text', help='the endogenous series, in identification order')], lags: Annotated[int | Criterion, Widget('text', help='number of lags, or a criterion to choose them: aic, bic, hq, fpe')], max_lags: Annotated[int, Widget('number', min=1, max=48, help='largest lag searched when lags is a criterion')] = 8, exog: Annotated[Sequence[str], Widget('text', help='exogenous expressions, e.g. dlog(oil)')] = (), trend: Literal['n', 'c', 'ct'] = 'c', by: Annotated[str | None, Widget('hidden', help='the entity axis, for a panel VAR')] = None, factors: Annotated[Any, Widget('hidden', help='not used: fit a factor-augmented VAR with favar(...)')] = None)
Vector autoregression, estimated equation by equation by least squares.
Each variable is regressed on lags of all of them, so the VAR summarises the data's joint dynamics with few restrictions; its coefficients are hard to read one by one, and it is used through impulse responses, variance decompositions, causality tests and forecasts. Responses to shocks need an identification: the default Cholesky scheme lets a variable respond within the period only to the shocks of variables listed before it, so the order of the variables is an assumption and the responses can change with it. The lag length is a trade-off: too few leave autocorrelation in the residuals, too many spend k squared parameters per lag and make the estimates and forecasts noisy (BIC tends to choose fewer lags than AIC). Check that the model is stable (every root inside the unit circle) before reading its responses. Integrated variables can stay in levels, but some tests then lose their usual distributions; difference them, or use a VECM if they cointegrate.
select_order
¶
select_order(data: Dataset, max_lags: int | None = None, span: tuple | None = None) -> LagSelection
Information criteria for 0..max_lags lags, all on the sample that max_lags allows.
fit
¶
fit(data: Dataset, span: tuple | None = None, method: Any = None, transform: Literal['fod', 'within'] = 'fod', instrument_lags: int | None = None) -> FittedVAR
Estimate the VAR on data over span: by least squares, equation by equation, or with method=Bayes(...)
and a prior (e.g. Minnesota). A lag criterion (lags="bic") chooses the lags first, up to max_lags.
With by (an entity axis), a panel VAR: GMM on forward orthogonal deviations (transform, instrument_lags;
see pymetrix.panelvar).
VARNormality
dataclass
¶
Bases: Test
Multivariate Jarque-Bera test on Cholesky-standardised residuals (Lütkepohl).
VECM
dataclass
¶
VECM(variables: Annotated[Sequence[str], Widget('text', help='the endogenous series (at least two)')], lags: Annotated[int, Widget('number', min=0, max=24, help='lagged differences (one fewer than the lags of the VAR in levels); select_order compares them')] = 1, rank: Annotated[int | Literal['trace', 'maxeig'], Widget('text', help='number of cointegrating relations, or trace / maxeig to test for it')] = 'trace', deterministic: Annotated[Deterministic, Widget('choice', help='n none; ci constant in the relations; co constant outside; coli, colo add a linear trend inside or outside')] = 'co', exog: Annotated[Sequence[str], Widget('text', advanced=True, help='unrestricted exogenous expressions')] = (), exog_coint: Annotated[Sequence[str], Widget('text', advanced=True, help='exogenous expressions inside the cointegrating relations')] = (), seasons: Annotated[int, Widget('number', min=0, max=52, advanced=True, help='seasonal dummies, e.g. 4 for quarterly data; 0 = none')] = 0, first_season: Annotated[int, Widget('number', min=0, max=51, advanced=True, help='position of the first observation in the seasonal cycle (0 to seasons - 1), aligning the dummies')] = 0, signif: Annotated[float, Widget('number', min=0.01, max=0.1, step=0.01, advanced=True, help='significance level for choosing the rank: 0.10, 0.05 or 0.01')] = 0.05, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other statsmodels arguments; model.x for the constructor')] = dict())
Vector error-correction model (statsmodels), with the cointegrating rank chosen by Johansen tests or given.
For series that are each integrated of order one but share long-run relations (cointegration): the differences respond to last period's deviations from those relations. beta holds the relations, normalised on the first variables, so the order of the variables decides how they read; alpha holds the speeds of adjustment, and a variable whose alpha is near zero does not correct towards the relations (it is weakly exogenous). The Johansen tests that choose the rank depend on the lags and on the deterministic case, and over-reject in small samples; check that the rank makes economic sense. If the tests find no cointegration a VAR in differences is the model; if they find full rank the series look stationary and a VAR in levels is. Impulse responses of a VECM need not die out: shocks can move the levels permanently.
johansen
¶
johansen(data: Dataset, span: tuple | None = None) -> JohansenResult
The Johansen tests that choose the rank in fit: on the rows the model is fitted to (those complete in
the exogenous terms too), with its lags and deterministic case. The test does not model exog,
exog_coint or seasonal dummies; its notes say so when the model has them.
Functions¶
favar
¶
favar(data: Dataset, panel: Sequence[str], observed: Sequence[str], factors: int | FactorCriterion = 3, lags: int | str = 2, slow: Sequence[str] | None = None, span: Any = None, max_factors: int = 8, max_lags: int = 8) -> FittedFAVAR
A FAVAR: factors principal components of the panel (or as many as Bai and Ng's "icp1", "icp2"
or "icp3" choose, up to max_factors) with the observed variables in a VAR(lags; or chosen by
"aic", "bic", "hq" or "fpe" up to max_lags).
johansen
¶
johansen(data: Dataset, variables: Sequence[str], lags: int = 1, det_order: Literal[-1, 0, 1] = 0, signif: float = 0.05, span: tuple | None = None) -> JohansenResult
Johansen cointegration tests (statsmodels coint_johansen). lags: lags in differences;
det_order: -1 none, 0 constant, 1 linear trend. Critical values are tabulated for 10%, 5% and 1%.
threshold_var
¶
threshold_var(data: Dataset, variables: Sequence[str], lags: int = 1, threshold: str | None = None, delay: int = 1, trim: float = 0.15, span: Any = None) -> FittedThresholdVAR
A two-regime threshold VAR (Tsay 1998), split by threshold (default: the first variable) delay periods back.
varma
¶
varma(data: Dataset, variables: Sequence[str], p: int = 1, q: int = 1, span: Any = None) -> FittedVARMA
A VARMA(p, q) of variables by conditional maximum likelihood, from the VAR(p) least-squares estimates.
Results¶
FEVD
dataclass
¶
FEVD(values: ndarray, variables: Sequence[str], shocks: Sequence[str], identification: str = '', lower: ndarray | None = None, upper: ndarray | None = None, coverage: float | None = None, band_source: str = '', bootstrap: Any = None, provenance: Any = None)
Shares values[h, variable, shock] of the h+1-step forecast-error variance.
FittedFAVAR
dataclass
¶
FittedFAVAR(var: Any, factor_names: tuple[str, ...], observed: tuple[str, ...], loadings: DataFrame, scale: Series, centre: Series, r2: Series, factors: DataFrame, panel: DataFrame | None = None, observed_data: DataFrame | None = None, slow: tuple[str, ...] = (), factor_selection: Table | None = None, provenance: Any = None)
A factor-augmented VAR: the VAR in the factors and observed variables, and the panel's loadings.
irf
¶
irf(series: Sequence[str] | None = None, periods: int = 20, draws: int = 0, bootstrap: Literal['favar', 'var'] = 'favar', coverage: float = 0.95, seed: int = 0) -> Any
Responses of panel series (default: all) to the VAR's (recursively identified) shocks, in their units,
with (coverage) percentile bands from draws bootstrap replications: of the whole two-step procedure
(bootstrap="favar", Bernanke-Boivin-Eliasz, Kilian 1998), or of the VAR alone, factors and loadings held
fixed ("var").
fevd
¶
The share of each series' common component's forecast-error variance due to each shock, by horizon (the
idiosyncratic part left out, as Bernanke, Boivin and Eliasz report it; r2 gives the common part's share
of the series).
FittedMSVAR
dataclass
¶
FittedMSVAR(spec: MSVAR, intercepts: ndarray, coefs: ndarray, sigmas: ndarray, transition: ndarray, loglike: float = 0.0, iterations: int = 0, filtered: DataFrame = None, smoothed: DataFrame = None, nobs: int = 0, sample_rows: DataFrame | None = None, provenance: Any = None)
An estimated Markov-switching VAR.
params
property
¶
The coefficients of each regime as a PointEstimate ("regime 1 y: const", "regime 1 y: x[-1]", ...);
no covariance (the EM estimates do not give one).
irf
¶
irf(regime: int = 0, periods: int = 20, draws: int = 0, coverage: float = 0.68, seed: int = 0) -> Any
Responses within a regime (as if it lasted), recursively identified with that regime's covariance. With
draws, coverage bands: pointwise quantiles over draws of the parameters from the estimates' asymptotic
normal distribution (parameter_draws).
girf
¶
girf(shock: Any = None, size: Any = 1.0, history: Any = 'regimes', periods: int = 20, draws: int = 500, seed: int = 0, regime: str = 'evolve', bands: int = 0, coverage: float = 0.68) -> Any
Generalised impulse responses (Koop, Pesaran and Potter 1996), by simulation: E[y_(t+h) | shock, history] -
E[y_(t+h) | history], averaged over each group of histories (history: "regimes", the default, for each
regime's histories; "all"; a regime; a period such as "2008Q4"; or a list), for shocks of each size in
standard deviations (e.g. (1, -1, 2), to see the asymmetry). regime="evolve" lets the regime move after
the shock (drawn from the transition matrix; "fixed" gives irf(regime=...)); "fixed" holds the regime it arrives in. draws paths from each history, bands
draws of the parameters for coverage bands. See pymetrix.girf.
parameter_covariance
¶
The estimates' asymptotic covariance, on the scale parameter_draws draws on (intercepts; lag
coefficients; each covariance's Cholesky factor, log diagonal; each transition row's logits against its last
entry): the inverse of minus the Hessian of the exact log likelihood. Computed once.
parameter_draws
¶
Draws of the parameters from the estimates' asymptotic normal distribution, on a scale where every draw is
a valid set of covariance and transition matrices (see pymetrix.ms_var_bands): intercepts (N, M, K),
coefs (N, M, K, K p), sigmas (N, M, K, K) and transition (N, M, M).
fevd
¶
fevd(regime: int = 0, periods: int = 20, draws: int = 0, coverage: float = 0.68, seed: int = 0) -> Any
Forecast-error variance decomposition within a regime (held fixed over the horizon, as irf), the shocks
recursively identified with that regime's covariance. With draws, coverage bands: pointwise quantiles
of the shares over draws of the parameters from the estimates' asymptotic normal distribution (each draw's
shares add up to one; the point shares are those at the estimates).
regime_path
¶
The most likely regime each period, by the smoothed probabilities.
historical_decomposition
¶
Each variable over the sample, split into the contributions of the recursively identified shocks and the
baseline, along the most likely regime path: in each period the regime with the highest smoothed probability
(regime_path()) supplies the intercepts, lag matrices and impact matrix (the Cholesky factor of its
covariance). The residuals u_t = y_t - c_s(t) - sum_l A_l,s(t) y_t-l give the shocks e_t = P_s(t)^-1 u_t; each
shock's contribution follows x_j,t = sum_l A_l,s(t) x_j,t-l + P_s(t)[:, j] e_j,t from zero, and the baseline
b_t = c_s(t) + sum_l A_l,s(t) b_t-l from the first observations, so the regime's intercepts (and so any shift
of the mean between regimes) are in the baseline. The parts add up to the data exactly. (Weighting the
regimes' parameters by their probabilities would also add up, but the weighted system is no regime of the
model; the most likely path is a history the model can produce.)
With draws, coverage bands for each contribution: pointwise quantiles over the decompositions under
draws of the parameters from the estimates' asymptotic normal distribution, the regime path held at the most
likely one (so the bands leave out the uncertainty about the regimes). Every draw's parts add up to the data;
the point decomposition is the one at the estimates.
FittedQuantileVAR
dataclass
¶
FittedQuantileVAR(spec: QuantileVAR, intercepts: ndarray, A0: ndarray, A: ndarray, index: Index, nobs: int = 0, sample_rows: DataFrame | None = None, provenance: Any = None)
An estimated recursive quantile VAR: A_0 y_t = c + sum_l A_l y_t-l at the quantile.
params
property
¶
The estimates as a PointEstimate, equation by equation as they were estimated: each equation's constant
("y: const"), its coefficients on the variables ordered before it in the same period ("y: x", which
is -A0[i, j]) and on the lags ("y: x[-1]", A[l][i, j]). Quantile regressions here estimate no
covariance, so cov is None (the standard errors are missing).
irf
¶
Responses of the quantile system to a one-unit structural shock in each equation.
residuals
¶
The reduced-form quantile residuals u_t = y_t - A_0^-1 (c + sum_l A_l y_t-l): each variable less the quantile system's prediction (at quantile 0.5 about as many positive as negative; at 0.1 mostly positive).
fevd
¶
Forecast-error variance decomposition of the quantile system (Ando, Greenwood-Nimmo and Shin's quantile
connectedness, orthogonalised as Diebold and Yilmaz 2009): the moving-average weights of the system at the
quantile, Psi_h, and the covariance Sigma of its reduced-form quantile residuals (about their mean, divided
by T), orthogonalised by its Cholesky factor in the VAR's order: theta_h = Psi_h chol(Sigma). Each row adds
up to one. When the structural quantile residuals are uncorrelated, chol(Sigma) is the responses' impact
A_0^-1 scaled by their standard deviations, so the shocks are irf's; at the median of a Gaussian VAR the
decomposition is close to the least-squares VAR's Cholesky decomposition.
generalised=True: Pesaran and Shin's (1998) generalised decomposition, as Ando, Greenwood-Nimmo and Shin
use it, which does not depend on the order: the share of variable i's h-step forecast-error variance due to
shock j is sum_l (e_i' Psi_l Sigma e_j)^2 / Sigma_jj over sum_l e_i' Psi_l Sigma Psi_l' e_i, each row
then divided by its sum so that it adds up to one (Diebold and Yilmaz 2012); with Sigma diagonal it is the
Cholesky decomposition.
FittedThresholdVAR
dataclass
¶
FittedThresholdVAR(variables: tuple[str, ...], lags: int, threshold_variable: str, delay: int, gamma: float, coefs_low: ndarray, coefs_high: ndarray, sigma: ndarray, regime: Series, LR: float = 0.0, trim: float = 0.15, Y: ndarray = None, z: ndarray = None, provenance: Any = None)
A two-regime threshold VAR.
params
property
¶
The coefficients of both regimes as a PointEstimate ("regime 1 y: x[-1]", ...); no covariance (the
threshold is estimated, and the regimes' least-squares covariances ignore it).
test
¶
Tsay's (1998) sup-LR test of linearity, its p-value by a residual bootstrap of the linear VAR, the threshold searched again in every draw (Hansen 1996).
girf
¶
girf(shock: Any = None, size: Any = 1.0, history: Any = 'regimes', periods: int = 20, draws: int = 500, seed: int = 0, regime: str = 'evolve', bands: int = 0, coverage: float = 0.68) -> Any
Generalised impulse responses (Koop, Pesaran and Potter 1996), by simulation: E[y_(t+h) | shock, history] -
E[y_(t+h) | history], averaged over each group of histories (history: "regimes", the default, for each
regime's histories; "all"; a regime; a period such as "2008Q4"; or a list), for shocks of each size in
standard deviations (e.g. (1, -1, 2), to see the asymmetry). regime="evolve" lets the regime move after
the shock (through the simulated threshold variable, which must be in the VAR); "fixed" holds the regime it arrives in. draws paths from each history, bands
draws of the parameters for coverage bands. See pymetrix.girf.
FittedVAR
dataclass
¶
FittedVAR(spec: VAR, lags: int, estimate: _Estimate, arrays: _Arrays, identification: Any = Cholesky(), provenance: Provenance | None = None, restriction: Any = None)
eigenvalues
property
¶
The companion matrix's eigenvalues (complex), largest modulus first.
shocks
property
¶
The structural shocks' names: the variables', or those the sign restrictions give.
residual_correlogram
¶
Auto- and cross-correlations of the residuals up to lags, with ±1.96/sqrt(T) bands; table() and
plot(). The portmanteau test (test("portmanteau")) sums them up.
roots_plot
¶
roots_plot() -> Figure
The companion matrix's eigenvalues in the complex plane, with the unit circle: all inside for a stable VAR.
heteroskedasticity_svar
¶
The shocks identified by shifts in their variances at breaks (Rigobon 2003; see
pymetrix.identification_extra).
proxy_svar
¶
proxy_svar(data: Dataset, instrument: str, normalise_on: str | None = None, periods: int = 20, scale: Literal['sd', 'unit'] = 'sd', draws: int = 500, block: int | None = None, coverage: float = 0.95, seed: int = 0) -> Any
The shock of normalise_on (default: the VAR's first variable) identified by the external instrument:
its impact, responses with moving-block bootstrap bands, and the first stage (see pymetrix.proxy). With
scale="unit" the shock moves normalise_on by one on impact. (normalise_on was called target; the
old name still works, with a DeprecationWarning.)
structural
¶
Under A-B restrictions: A and B by maximum likelihood, with standard errors, the log likelihood and the
test of any over-identifying restrictions (see pymetrix.structural).
sign_draws
¶
The impact matrices the sign restrictions accept at the estimates: the identified set, as drawn.
irf
¶
irf(periods: int = 20, orthogonal: bool = True, cumulative: bool = False, draws: int = 500, coverage: float = 0.95, seed: int = 0, bootstrap: Any = None) -> IRF
Impulse responses to one-standard-deviation structural shocks (or unit reduced-form
shocks with orthogonal=False). Bands: parametric bootstrap with draws replications, or the bootstrap
bootstrap gives (Bootstrap("wild"), "residual", "block", "pairs", with Kilian's bias
correction and Hall's intervals as options; see pymetrix.bootstrap); irf.bootstrap reports what was done.
Under sign restrictions: the median of the accepted rotations, with bands from a rotation for each
bootstrap draw (or, with draws=0, spanning the identified set at the estimates); with zero restrictions
too, ARW's draws, importance-weighted and resampled.
girf
¶
girf(periods: int = 20, cumulative: bool = False, draws: int = 500, coverage: float = 0.95, seed: int = 0, bootstrap: Any = None) -> IRF
Generalised impulse responses (Pesaran and Shin 1998; Koop, Pesaran and Potter 1996): the response to a
one-standard-deviation shock in each equation, the other shocks at their expected values given it, so
Phi_h Sigma e_j / sqrt(sigma_jj). Invariant to the ordering; shock j's response is the Cholesky response with
variable j first. The shocks are correlated, so there is no variance decomposition. Bands as irf's.
fevd
¶
fevd(periods: int = 20, bootstrap: Any = None, coverage: float = 0.95) -> FEVD
Forecast-error variance decomposition under the current identification. With bootstrap (a
Bootstrap(...) or a kind's name, 500 draws unless it says), coverage bands for each share: quantiles
of the shares over the re-estimated VARs (point identification only).
forecast
¶
forecast(data: Dataset, span: tuple[Any, Any], coverage: float = 0.95, dynamic: bool = True) -> Dataset
Dynamic forecasts from the period before span; intervals reflect shock uncertainty only.
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, bootstrap: Any = None) -> Dataset
Forecasts given conditions on some variables: exact paths (Waggoner and Zha 1999) or ranges, met by all the
shocks or by the identified shocks named (a structural scenario), with intervals.
conditions maps a variable to a condition held over every forecast period or to period -> condition
({"r": {"2025Q1": 2.0, "2025Q2": 2.25}}). A condition is a number (exact) or a range:
Bounds(3, 4), Bounds(lower=3), Bounds(upper=4), (3, 4) or {"lower": 3, "upper": 4}.
With every shock free to move (shocks=None), the shocks that meet exact conditions are the most likely
ones, so the result is the conditional expectation given the conditions and does not depend on how shocks are
identified. shocks names the identified shocks that may move to meet them; the others keep their
unconditional distribution (Antolin-Diaz, Petrella and Rubio-Ramirez 2021). shock_conditions conditions
the structural shocks themselves, as conditions ({"r": 0.0}: no policy shocks).
Exact conditions alone give the closed form: columns <v>, <v>_se, <v>_lower, <v>_upper
(mean +/- z se); conditioned values have no uncertainty. With a range, the forecast is simulated (draws
paths, default 5,000, with seed; see pymetrix.var_conditions) and the columns are the mean, sd,
median and the coverage quantile interval; every draw meets every bound. Intervals reflect the shocks,
not parameter uncertainty (a Bayesian VAR's include that).
bootstrap (Bootstrap(...) or a kind's name, as irf) adds parameter uncertainty: the VAR is
re-estimated on each bootstrap draw (pymetrix.bootstrap) and, as a Bayesian VAR does with its posterior
draws, one path meeting the conditions is drawn under each draw's coefficients, covariance and impact; the
columns are then the paths' mean, sd, median and interval, and the report is in the metadata
(meta.extra["bootstrap"]). draws and seed stay the paths' when it is given; the bootstrap's draws
and seed are its own (500 and seed unless it says).
historical_decomposition
¶
historical_decomposition(draws: int = 0, coverage: float = 0.95, seed: int = 0, bootstrap: Any = None) -> Any
Each variable over the estimation sample, split into the contributions of the identified structural shocks and the baseline: the path from the first observations and the deterministic and exogenous terms, with no shocks. The parts add up to the data exactly.
The structural shocks are the residuals through the impact matrix of the current identification,
e(t) = P^-1 u(t); shock j's contribution is sum over s <= t of Phi(t - s) P[:, j] e_j(s). Under sign
restrictions the impact matrix is the median-target member of the identified set. Returns a
Decomposition: contributions[variable] (periods x shocks), deviations (the data less the
baseline), baseline and shocks; plot() draws the contributions as stacked bars.
With draws, coverage bands for each contribution, pointwise quantiles over the decompositions of the
data under each draw: a Bayesian VAR's posterior draws (each with its own coefficients, residuals, baseline and
impact matrix: under sign or zero and sign restrictions, a rotation accepted for that draw), under sign
restrictions the identified set at the estimates (draws accepted rotations), or for a point-identified
VAR draws replications of the parametric bootstrap that gives irf's bands (each re-estimated VAR's
coefficients, deterministic terms and impact matrix, applied to the data). Every draw's parts add up to
the data. The point decomposition is unchanged (at a BVAR's posterior mean); lower, median and
upper hold the bands, bands_table() and plot_bands() show them. A point-identified VAR's
bootstrap (a Bootstrap(...) or a kind's name) chooses another bootstrap than the parametric one.
FittedVARMA
dataclass
¶
FittedVARMA(variables: tuple[str, ...], p: int, q: int, c: ndarray, A: ndarray, M: ndarray, sigma: ndarray, cov: ndarray, loglike: float = 0.0, nobs: int = 0, resid: DataFrame = None, provenance: Any = None)
A VARMA(p, q) estimated by conditional maximum likelihood.
FittedVECM
dataclass
¶
FittedVECM(spec: VECM, rank: int, results: Any, index: PeriodIndex, identification: Any = Cholesky(), provenance: Provenance | None = None, johansen: JohansenResult | None = None)
Bases: BackendResult
coefs
property
¶
Coefficients of the equivalent VAR in levels, shape (lags + 1, K, K).
eigenvalues
property
¶
The eigenvalues of the companion matrix of the levels VAR, largest modulus first: K - rank of them are exactly one (the common stochastic trends).
params
property
¶
The estimates as a PointEstimate with their covariance, equation by equation: each equation's
adjustment to the cointegrating relations ("da: ce1", alpha), its short-run coefficients ("da: db[-1]",
as short_run()) and its deterministic terms outside the relations ("da: const"); then the free
elements of the cointegrating vectors ("ce1: c": the rows below the first rank, which are normalised
to the identity, and any deterministic terms inside the relations). The first block's covariance is the
library's (Lütkepohl 2005, 7.2.21: given the cointegrating vectors); the vectors' block is Lütkepohl's
(p. 297), and the two are uncorrelated asymptotically (the vectors converge at rate T).
residual_correlogram
¶
Auto- and cross-correlations of the residuals up to lags, with ±1.96/sqrt(T) bands (see
FittedVAR.residual_correlogram).
roots_plot
¶
The levels VAR's companion eigenvalues with the unit circle: K - rank on it, the rest inside if the relations are stationary.
relations
¶
The cointegrating relations over the sample: beta' y(t), with any constant, trend or exogenous terms restricted to them (cases ci and coli), as they enter the error correction of the next period's changes. Stationary around zero if the variables cointegrate as estimated.
recursive_eigenvalues
¶
recursive_eigenvalues(start: Any = None, base: Literal['Z', 'R'] = 'Z') -> Dataset
Johansen's eigenvalues estimated on samples ending each period from start (default: a third of the way
into the sample) to the end, as Hansen and Johansen (1999) use to check that the cointegration is stable:
the first rank should settle and stay put.
base="Z" re-estimates everything on each sample; "R" partials the short-run, deterministic and
exogenous terms out once, at the full-sample estimates, and recomputes only the reduced-rank step. Columns
lambda1 ... lambdaK, largest first, indexed by each sample's last period.
fluctuation_test
¶
fluctuation_test(start: Any = None, draws: int = 199, seed: int = 0) -> TestResult
A fluctuation test of the constancy of the first rank eigenvalues, from their recursive estimates with
the short run held at the full-sample estimates (Hansen and Johansen's R representation).
Each eigenvalue is taken as xi = ln(lambda / (1 - lambda)), and the statistic is the largest over the
recursions of sqrt(T) (t / T) |xi(t) - xi(T)|, for the sum of the first rank xi's (and, in
details["by eigenvalue"], each one). Its p-value is from draws bootstrap samples of the fitted VECM,
whose parameters are constant: the residuals resampled, the series rebuilt, the recursions run again.
details["paths"] holds each statistic's path, details["critical values"] the bootstrap 5% values.
fluctuation_plot
¶
The fluctuation statistic's path for each eigenvalue and their sum, with its bootstrap 5% critical value.
recursive_eigenvalues_plot
¶
The first rank recursive eigenvalues (recursive_eigenvalues), each in a panel.
irf
¶
irf(periods: int = 20, orthogonal: bool = True, cumulative: bool = False, draws: int = 0, coverage: float = 0.95, seed: int = 0, bootstrap: Any = None, **_: Any) -> IRF
Impulse responses of the levels, with draws bootstrap replications for (coverage) percentile bands.
The bootstrap resamples the centred residuals, builds each series again from the estimated VECM (its
cointegrating relations, adjustment, short-run, deterministic and exogenous terms) from the first lags + 1
observations, and re-estimates it with the same rank, lags and deterministic case, as JMulTi and R's vars.
bootstrap (a Bootstrap(...) or a kind's name: residual, wild, block or parametric; 500 draws unless it
or draws says) chooses how the residuals are drawn, as Cavaliere, Rahbek and Taylor's bootstrap of a VECM
with its rank held; irf.bootstrap reports the draws used, the failures and whether every draw kept the
rank.
historical_decomposition
¶
The levels over the estimation sample, split into the contributions of the identified shocks and the
baseline: the path the VECM gives from the first lags + 1 observations with its deterministic and exogenous
terms and no shocks. The parts add up to the data exactly. Shocks are the residuals through the impact matrix;
their contributions go through the levels VAR, so permanent shocks keep contributing. A Decomposition,
as FittedVAR.historical_decomposition.
forecast
¶
forecast(data: Dataset, span: tuple[Any, Any], coverage: float = 0.95, dynamic: bool = True) -> Dataset
Forecasts of the levels from the end of the estimation sample (statsmodels predict).
test_beta
¶
test_beta(H: Any) -> TestResult
Johansen's LR test that the cointegrating vectors lie in the columns of H (beta = H phi): one row for each
variable, then the restricted constant or trend if the case has one (see pymetrix.vecm_restrictions).
test_weak_exogeneity
¶
test_weak_exogeneity(variables: Sequence[str]) -> TestResult
Johansen's LR test that variables do not adjust to the cointegrating relations (their rows of alpha
are zero), so they are weakly exogenous for beta.
IRF
dataclass
¶
IRF(values: ndarray, responses: Sequence[str], shocks: Sequence[str], lower: ndarray | None = None, upper: ndarray | None = None, cumulative: bool = False, identification: str = '', coverage: float = 0.95, bootstrap: Any = None, provenance: Any = None)
Responses values[h, response, shock]; optional bootstrap bands.
paths
property
¶
The responses as a table: a column per response and shock, labelled "y <- shock" (the response, then
the shock), shocks in order and the responses within each, and a row per horizon 0, 1, ... (paths["y <-
e"][2] is values[2, i, k]). The bands, if any, are in to_frame(). Exercise checks read it by name:
value = "paths.y <- e.2".
to_frame
¶
Every response (and band) by horizon; or one of its views by name ("Selected horizons").
summary
¶
summary() -> Table
The responses as a table, as table() gives them (every shock): what every result answers.
JohansenResult
dataclass
¶
JohansenResult(table: Table, rank_trace: int, rank_maxeig: int, eigenvalues: ndarray, signif: float, provenance: Provenance | None = None)
Trace and maximum-eigenvalue statistics for each null rank r = 0 .. K-1.
StructuralEstimate
dataclass
¶
StructuralEstimate(variables: tuple[str, ...], A: ndarray, B: ndarray, A_se: ndarray, B_se: ndarray, loglike: float = 0.0, LR: float | None = None, df: int = 0, nobs: int = 0, converged: bool = True, provenance: Any = None)
A and B estimated by maximum likelihood, with standard errors and the over-identification test.