Model details#
How the model is built: the design matrices, the priors and the derived outputs. These notes come from the module docstrings of the internal modules. None of these modules are public API.
The PyMC graph and priors#
PyMC model graph for the BayesianVECM.
This module is the home of the real econometrics in the package: turning the
three design matrices from
bayesian_vecm._design.cointegration_design() into a PyMC graph that
can sample.
Current scope#
The model supports:
Known cointegration rank \(r \geq 1\).
All five deterministic codes:
"n","co","ci","lo","li".Weakly-informative defaults for \(\alpha, \beta, \Gamma, \Sigma\).
Regularised horseshoe prior on \(\Gamma\) (opt-in).
The graph reads shapes directly off the design matrices produced by
bayesian_vecm._design.cointegration_design(), so deterministic columns
are handled automatically:
Outside terms (
"co","lo") append a column todelta_x, which widens \(\Gamma\) from \((K, Kk)\) to \((K, Kk+1)\).Inside terms (
"ci","li") append a column toy_{t-1}, which widens \(\beta\) from \((K, r)\) to \((K+1, r)\). The extra row is free (not pinned), so the constant/trend inside the cointegration relation is estimated from the data.
Identification of \(\beta\)#
The cointegration term \(\alpha \beta' y_{t-1}\) is invariant under
for any invertible \(r \times r\) matrix \(R\). Without a normalisation the posterior is non-identified, the sampler wanders along the orbit, and divergences pile up. The standard fix (Johansen, 1995) is to pin \(\beta[:r, :] = I_r\). The leading \(r \times r\) block is a constant; the remaining \((K - r, r)\) free entries are sampled. For \(r = 1\) that means just the first entry is fixed at 1.
The fixed entries are not stored as free random variables; the full
\((K, r)\) \(\beta\) matrix is exposed as a pm.Deterministic()
so downstream consumers can read it directly from idata without having
to remember the normalisation.
Mean structure#
For a row \(t\) of the design,
where \(\Delta x_t = [\Delta y_{t-1}; \dots; \Delta y_{t-k}]\) is the stacked lagged-difference regressor. In matrix form
with shapes \((T_{\text{eff}}, K) = (T_{\text{eff}}, K)(K, r)(r, K)
+ (T_{\text{eff}}, Kk)(Kk, K)\). The \(\Gamma\) term is dropped
entirely when k_ar_diff == 0 so the graph never multiplies a
zero-column matrix.
Default priors#
All are weakly informative; any of the four can be overridden via the
priors dict on BayesianVECM.
\(\alpha\):
Normal(0, 1.0), shape \((K, r)\). EC loadings are typically small and can be negative.\(\beta_{\text{free}}\):
Normal(0, 5.0), shape \((K - r, r)\). Cointegrating-vector entries can have arbitrary scale; the wider prior is more permissive than \(\alpha\)’s. Not present whenK == r(fully cointegrated system — no free rows).\(\Gamma\):
Normal(0, 0.5), shape \((K, Kk)\). Short-run dynamics are typically small and centred at zero. Alternatively, a regularised horseshoe prior can be requested — see below.\(\Sigma\):
LKJCholeskyCov(eta=2.0, sd_dist=HalfNormal(1.0)). The standard PyMC idiom;eta=2.0mildly favours weaker correlations.
The \(\Sigma\) prior is special-cased — the LKJCholeskyCov factory
doesn’t fit the simple {"dist": ..., **kwargs} pattern — and only
eta and sd_sigma overrides are accepted for it.
Centred constant#
Log levels in marketing data sit far from zero (log sales near 7). With a raw constant \(c\), the term \(\alpha\beta^{\top} y_{t-1}\) is large and \(c\) must cancel most of it. The posterior then ties \(c\) to \(\alpha\) with a correlation near \(-1\), and NUTS needs very long trajectories.
For the two codes that carry a constant ("co" and "ci") the graph
samples the constant of the model in demeaned levels instead. With
\(m\) the column means of the lagged levels:
"co": the free variable isGamma_centred. Its last column is \(\tilde c\).Gammais a deterministic with the raw constant \(c\) in its last column."ci": the constant row ofbeta_freeis \(\tilde b\). The constant row ofbetais \(b = \tilde b - \beta_y^{\top} m\), where \(\beta_y\) is the first \(K\) rows of \(\beta\).
The likelihood is unchanged, and Gamma and beta in the posterior
are on the raw scale. Only the prior moves: it now applies to the constant
of the demeaned model. "n", "lo" and "li" have no constant to
absorb the shift and are left as they are. The means are stored as
y_lag1_mean in the constant data.
Regularised horseshoe prior on \(\Gamma\)#
With real marketing data the true lag order is unknown. Setting k_ar_diff
generously over-parameterises \(\Gamma\), leaving many near-zero entries
that inflate posterior uncertainty. A regularised horseshoe (RHS) prior
(Piironen & Vehtari 2017) shrinks irrelevant entries toward zero while
preserving genuine short-run dynamics — more principled than hard lag
selection via information criteria.
Opt in by passing priors={"Gamma": {"dist": "Horseshoe"}} to
BayesianVECM. Optional kwargs (all with sensible defaults):
tau_scale(float, default1.0) — scale of the half-Cauchy global shrinkage prior \(\tau \sim \text{HalfCauchy}(\tau_{\text{scale}})\).slab_scale(float, default2.0) — scale of the Student-t slab that caps large coefficients.slab_df(float, default4.0) — degrees of freedom of the slab.
The hierarchy is:
The slab variance \(c^2\) acts as a finite upper bound on the effective prior scale, preventing the heavy tails of the pure horseshoe from causing sampling pathologies.
Two choices keep the sampler stable:
Non-centred. The free variable is \(z_{ij} \sim \mathcal{N}(0, 1)\) and \(\Gamma_{ij} = z_{ij} \tau \tilde{\lambda}_{ij}\) is a deterministic. Drawing \(\Gamma\) directly from \(\mathcal{N}(0, \tau^2 \tilde{\lambda}^2)\) gives a funnel that NUTS cannot cross.
Lags only. The shrinkage covers the lag columns of \(\Gamma\). Any outside deterministic column (the constant under
"co", the trend under"lo") keeps the defaultNormal(0, 0.5)prior, so the drift is not pulled towards zero.
Auxiliary RVs added to the graph: Gamma_tau, Gamma_lambda,
Gamma_c2, Gamma_z and, with an outside deterministic term,
Gamma_det. Expect a few divergences at the default target_accept.
target_accept=0.99 removes most of them.
Design matrices#
Design matrices for VECM estimation.
This module exposes a single helper, cointegration_design(), that turns a
raw (T, K) observation matrix into the three aligned matrices a VECM
regression equation actually consumes.
The VECM in error-correction form is
For each usable time \(t\) the regression row needs three things:
\(\Delta y_t\) — the left-hand side.
\(y_{t-1}\) — feeds the cointegration relation \(\beta' y_{t-1}\). It is the level lag, not a difference; it is what makes this a VECM and not a plain VAR-in-differences.
\([\Delta y_{t-1}, \dots, \Delta y_{t-k}]\) — the regressors that pick up short-run dynamics through the \(\Gamma_i\) matrices.
The smallest \(t\) for which all three are well defined is \(t = k + 1\) (0-based), so the effective sample size is
Deterministic terms (constants and linear trends, either inside or outside
the cointegration relation) are supported via the deterministic argument.
Only single codes are supported; compound cases (Johansen cases 4 and 5,
e.g. "colo", "cili") are rejected.
Impulse responses#
Impulse Response Functions (IRFs) for BayesianVECM.
Two identification schemes are supported:
"girf"— Generalised IRFs (Pesaran & Shin 1998)Order-invariant: no column order is needed. A shock to variable \(j\) moves the other variables by their expected same-period response under \(\Sigma\). This equals the Cholesky IRF with \(j\) ordered first. Each shock is treated as first in its own chain, so the responses to different shocks cannot all be structural at once (Kim 2009). Read them for a variable that leads the system. At horizon \(h\):
\[\text{GIRF}_h[:, j] = \frac{1}{\sqrt{\sigma_{jj}}} \, \Phi_h \, \Sigma \, e_j\]In matrix form: \(\text{GIRF}_h = \Phi_h \, \Sigma \, D^{-1/2}\) where \(D = \mathrm{diag}(\Sigma)\).
"cholesky"— Orthogonalised IRFs (Sims 1980)Requires a strict recursive (triangular) causal ordering among the variables. Appropriate only when you can defend a Wold causal chain with no contemporaneous feedback. The shock is a Cholesky-orthogonalised unit vector:
\[\text{OIR}_h = \Phi_h \, P\]where \(P\) is the lower-Cholesky factor of \(\Sigma\). The order is the column order unless
orderis given.orderpermutes \(\Sigma\) before the factorisation and maps the result back, so the output keeps the original variable order.
Both methods are computed via the VAR companion form: the VECM is first converted to a levels VAR(\(p\)) with \(p = k_{\text{ar\_diff}} + 1\), then the companion matrix \(F\) is iterated to produce the MA coefficient matrices
for horizons \(h = 0, 1, \dots, \text{steps}\).
VECM-to-VAR conversion#
Given the VECM
the equivalent levels VAR(\(p\)) with \(p = k + 1\) has coefficient matrices:
For \(k = 0\) (pure error-correction, no short-run dynamics): \(A_1 = I_K + \alpha\beta^\top\) and \(p = 1\).
Deterministic terms#
Outside deterministic terms ("co", "lo") append an extra column to
the \(\Gamma\) matrix in the fitted posterior. That column is a
constant or trend coefficient, not a VAR lag, so it must not be included in
the companion matrix. compute_irf always takes only the first
\(K \cdot k_{\text{ar\_diff}}\) columns of Gamma.
Variance decomposition#
Forecast error variance decomposition (FEVD) for BayesianVECM.
The FEVD answers one question per variable: of the uncertainty in an
h-step-ahead forecast, what share is due to shocks in each variable?
It reuses the moving-average matrices \(\Phi_s\) from the IRF code. The
h-step forecast error covariance is
"cholesky"(orthogonalised)With \(P\) the lower Cholesky factor of \(\Sigma\), the share of variable \(i\)’s forecast error variance due to shock \(j\) is
\[\frac{\sum_{s=0}^{h-1} (\Phi_s P)_{ij}^2}{\text{MSE}(h)_{ii}}.\]Rows sum to 1 exactly. The result depends on the column order.
"girf"(generalised, Pesaran & Shin 1998)The numerator becomes \(\sigma_{jj}^{-1} \sum_{s=0}^{h-1} (\Phi_s \Sigma)_{ij}^2\). This does not depend on the column order. The raw shares do not sum to 1 when shocks are correlated, so each row is rescaled to sum to 1 (Diebold & Yilmaz 2012).
In a cointegrated system the shares do not settle on a variance ratio of the levels, because the forecast error variance grows without bound. They do converge: at long horizons the permanent shocks account for everything.
Forecasts#
Posterior predictive forecasting for BayesianVECM.
Implements the VAR-level recursion:
for \(h = 1, \dots, \text{steps}\), seeded from the last
\(k_{\text{ar\_diff}} + 1\) rows of the fitted endog.
\(d_{T+h}\) is the deterministic term the model was fitted with:
"co"/"lo": the last column ofGammatimes 1 or the trend."ci"/"li": \(\alpha\) times rowKofbeta, times 1 or the trend.
The trend continues the fitted one. The design matrix numbers its rows
1, ..., T_eff, so forecast step h uses T_eff + h.
All posterior draws are processed simultaneously — the (chain x draw) dimension is vectorised so only a single Python loop over forecast steps is needed, keeping the inner body a handful of NumPy einsum calls.
Design choices#
NumPy, not PyTensor. The recursion has sequential data dependence (step h needs the output of step h-1), which rules out the standard PyMC
pm.sample_posterior_predictivescan idiom. A NumPy loop over steps, fully vectorised over draws, is readable and fast enough for any reasonablestepscount.Levels and differences both returned.
y(levels) is the headline forecast;delta_y(differences) is free to compute and useful for diagnostic plots.Innovations drawn from the posterior Cholesky. The model stores
Sigma(the full covariance) as apm.Deterministic; we re-Cholesky it once per fitted model, not once per step, so the per-step cost is just a matrix-vector product.
Evidence tables#
Posterior evidence on which variable helps predict which.
Four tables, all read from the fitted posterior:
short_runGranger causality. Does lagged growth in X help predict growth in Y? The quantity is the block of \(\Gamma\) that links X to Y, across all lags.
long_runDoes the level of X pull on Y? The quantity is one entry of \(\Pi = \alpha \beta^\top\). Unlike \(\alpha\) alone, \(\Pi\) does not depend on how \(\beta\) is normalised.
weak_exogeneityDoes the variable adjust to any long-run relation at all? The quantity is its whole row of \(\alpha\). A variable that does not adjust drives the system without being pulled back by it.
exogDoes an exogenous variable help predict Y? The quantity is its entry of \(B\), or its entries across all lags when the model has
exog_lags. Present only when the model was fitted withexog.
The evidence measure#
Each row carries one number between 0 and 1: the highest credible level at which zero lies outside the posterior region for that quantity. The region is the ellipsoid given by the posterior mean and covariance, and the level is the share of draws that sit closer to the mean than zero does.
For a single coefficient with a symmetric posterior this equals
1 - 2 * min(P(> 0), P(< 0)). A value near 1 means the posterior is far
from zero. A value near 0 means zero is close to the centre.
Two limits to keep in mind:
These are statements about prediction, not about cause. “X helps predict Y” is as far as the short-run table goes.
A shrinkage prior on \(\Gamma\) pulls coefficients towards zero, so the short-run evidence depends on that prior. The result records which prior was used. A horseshoe posterior is also less elliptical than a normal one, which makes the measure approximate there.