04. First PyMC model#
This notebook walks through the first slice in which BayesianVECM actually samples. The previous three notebooks built up the data plumbing (validate_endog, difference, lag_matrix, cointegration_design) and the class skeleton; this one wires those into a PyMC graph and fits it.
Since this notebook.
fitnow handles any cointegration rank and all five deterministic codes (notebook 06).sample_posterior_predictiveforecasts (notebook 05). The two scope notes below describe the package at this stage.
Two things up front at this stage:
The first scope is narrow on purpose.
fitonly estimatescoint_rank=1+deterministic="n". The public API already accepts the wider envelope (higher ranks, deterministic terms) but the PyMC graph raisesNotImplementedErrorfor everything outside that: better to fail loudly than to silently misspecify.sample_posterior_predictiveis still a stub. Forecasting through the VAR recursion is meaningfully its own design problem (drawing innovations from \(\Sigma\), rolling forward N steps, choosing the return shape) and is the next thing on the roadmap, on its own branch.
The headline econometric idea below is the identification of \(\beta\). We flagged it in notebook 02 §5 and notebook 03 §7 as the central problem the first PyMC slice would have to solve; this notebook is where it actually gets solved, and we eyeball whether the posterior recovers the true cointegrating vector under the normalisation.
from __future__ import annotations
import numpy as np
from bayesian_vecm import BayesianVECM
np.set_printoptions(precision=3, suppress=True)
1. A synthetic cointegrated series#
We need a small dataset where we know the true parameters, so we can ask the model to recover them. The simplest non-trivial VECM is a bivariate pair driven entirely by error correction: no short-run dynamics, no deterministic terms:
Let the cointegrating vector be \(\beta = (1, -0.5)^{\top}\) and the loadings be \(\alpha = (-0.4, 0.2)^{\top}\). The error-correction term is then
and each component updates as \(\Delta y_{t,k} = \alpha_k\, \text{ec}_t + \varepsilon_{t,k}\).
Individually each series is non-stationary (an \(I(1)\) random walk with drift driven by shocks), but their linear combination \(y_{t,0} - 0.5 y_{t,1}\) is mean-reverting: that’s exactly what cointegration means. The model’s job is to discover that combination from the data alone.
Predictions for the fit. Under the normalisation \(\beta_0 = 1\) that the model imposes for identification, the posterior should report:
\(\beta_1 \approx -0.5\) (the only free entry of \(\beta\) for \(K=2,r=1\)).
\(\alpha_0 \approx -0.4\) and \(\alpha_1 \approx 0.2\).
\(\Gamma_1\) centred near zero: the DGP has no short-run dynamics, so the lagged-difference block is just absorbing noise.
\(\Sigma\) a diagonal-ish matrix with \(\sigma_{kk}^2 \approx 0.25\) (we set \(\varepsilon\)’s scale to 0.5 below).
def make_cointegrated_series(
n_obs: int = 300,
alpha_true: tuple[float, float] = (-0.4, 0.2),
beta_true: tuple[float, float] = (1.0, -0.5),
sigma: float = 0.5,
seed: int = 0,
) -> np.ndarray:
rng = np.random.default_rng(seed=seed)
a0, a1 = alpha_true
b0, b1 = beta_true
y = np.zeros((n_obs, 2))
y[0] = rng.normal(size=2)
for t in range(1, n_obs):
ec = b0 * y[t - 1, 0] + b1 * y[t - 1, 1]
y[t, 0] = y[t - 1, 0] + a0 * ec + rng.normal(scale=sigma)
y[t, 1] = y[t - 1, 1] + a1 * ec + rng.normal(scale=sigma)
return y
endog = make_cointegrated_series()
print("endog shape:", endog.shape)
print("first few rows:")
print(endog[:5])
# Show the error-correction term is mean-reverting even though each level isn't.
true_ec = endog[:, 0] - 0.5 * endog[:, 1]
print(f"\nec_t = y0 - 0.5 y1 : mean = {true_ec.mean(): .3f}, std = {true_ec.std(): .3f}")
print(f"y0: mean = {endog[:, 0].mean(): .3f}, std = {endog[:, 0].std(): .3f}")
print(f"y1: mean = {endog[:, 1].mean(): .3f}, std = {endog[:, 1].std(): .3f}")
endog shape: (300, 2)
first few rows:
[[ 0.126 -0.132]
[ 0.369 -0.041]
[-0.055 0.217]
[ 0.663 0.658]
[ 0.177 0.092]]
ec_t = y0 - 0.5 y1 : mean = -0.101, std = 0.658
y0: mean = 0.556, std = 1.005
y1: mean = 1.315, std = 1.864
Individual series wander (large std), but their cointegrating combination stays close to zero (small std). That’s the signal the model picks up on.
2. Construct and fit#
The construction step is unchanged from notebook 03: BayesianVECM(k_ar_diff=1, coint_rank=1, deterministic="n") was the only supported configuration at this stage. What’s new is that fit actually runs pm.sample now instead of raising.
Sampler defaults are 4 chains × 1000 draws after 1000 tuning iterations, with target_accept=0.9 (slightly cautious; the default is 0.8). On a small bivariate model this takes roughly a minute end-to-end, mostly PyTensor compilation.
# ---------------------------------------------------------------------------
# Sampling configuration
# ---------------------------------------------------------------------------
# Set FAST_SAMPLING = True for quick execution (CI / first read-through).
# Set FAST_SAMPLING = False for publication-quality posteriors.
# ---------------------------------------------------------------------------
FAST_SAMPLING = True
if FAST_SAMPLING:
DRAWS, TUNE, CHAINS = 200, 200, 2
else:
DRAWS, TUNE, CHAINS = 1000, 1000, 4
print(f"Sampling config: draws={DRAWS}, tune={TUNE}, chains={CHAINS}")
if FAST_SAMPLING:
print("(FAST_SAMPLING=True: posteriors are coarser; set to False for full quality)")
Sampling config: draws=200, tune=200, chains=2
(FAST_SAMPLING=True: posteriors are coarser; set to False for full quality)
model = BayesianVECM(k_ar_diff=1, coint_rank=1, deterministic="n")
model.fit(endog, draws=DRAWS, tune=TUNE, chains=CHAINS, random_seed=42, progressbar=False, cores=1)
print("\nFitted. Attributes set during fit:")
print(f" endog_.shape = {model.endog_.shape}")
print(f" idata_ groups = {list(model.idata_.groups)}")
print(f" variable_names_ = {model.variable_names_}")
print(f" posterior data vars = {list(model.idata_.posterior.data_vars)}")
NUTS[nutpie]: [alpha, beta_free, Gamma, Sigma_chol]
Fitted. Attributes set during fit:
endog_.shape = (300, 2)
idata_ groups = ['/', '/posterior', '/sample_stats', '/constant_data', '/observed_data']
variable_names_ = None
posterior data vars = ['alpha', 'beta_free', 'Gamma', 'Sigma_chol', 'beta', 'Sigma_chol_corr', 'Sigma_chol_stds', 'Sigma']
3. The \(\beta\)-identification check#
Recall the problem from notebook 03 §7: the cointegration term \(\alpha \beta^{\top} y_{t-1}\) is invariant under \((\alpha, \beta) \to (\alpha R^{-1}, \beta R^{\top})\) for any invertible \(r \times r\) matrix \(R\). The likelihood can’t distinguish \((\alpha, \beta)\) from \((\alpha/c, c\beta)\) for any non-zero scalar \(c\) when \(r = 1\).
The model handles this the standard Johansen way: pin \(\beta[:r, :] = I_r\) inside the graph. For \(r = 1\) that means the first entry of \(\beta\) is fixed at exactly 1 in every posterior draw, and only the remaining \(K - 1\) entries are free.
If that pin is working, every draw of beta[0, 0] should be exactly 1.0: not approximately, not sometimes, every single one.
beta_samples = model.idata_.posterior["beta"].values # shape (chain, draw, K, r)
print("beta_samples shape:", beta_samples.shape)
print()
first_entries = beta_samples[..., 0, 0]
print("beta[0, 0] across all chains and draws:")
print(f" min = {first_entries.min()}")
print(f" max = {first_entries.max()}")
print(f" all == 1.0? {np.all(first_entries == 1.0)}")
print()
free_entry = beta_samples[..., 1, 0].ravel()
print("beta[1, 0] (the one free entry) posterior:")
print(f" mean = {free_entry.mean(): .3f}")
print(f" std = {free_entry.std(): .3f}")
print(f" q 3% = {np.quantile(free_entry, 0.03): .3f}")
print(f" q 97% = {np.quantile(free_entry, 0.97): .3f}")
print(" true = -0.5")
beta_samples shape: (2, 200, 2, 1)
beta[0, 0] across all chains and draws:
min = 1.0
max = 1.0
all == 1.0? True
beta[1, 0] (the one free entry) posterior:
mean = -0.455
std = 0.033
q 3% = -0.520
q 97% = -0.389
true = -0.5
Two things to take away from that cell:
The first entry is bit-exact 1.0 in every draw. That’s the normalisation working as advertised: the pin is implemented by stacking a constant
pt.eye(r)block on top of a(K - r, r)free RV, so the fixed entries aren’t free random variables at all and can’t drift.The free entry’s posterior is centred near \(-0.5\) with a 94% interval (3rd to 97th percentile) that should contain the true value comfortably. If it doesn’t, the identification is broken or the sampler hasn’t converged: either way, a red flag worth pausing on.
4. Parameter recovery#
model.summary() is a thin wrapper around arviz.summary with a sensible default var_names list (\(\alpha\), \(\beta\), \(\Gamma\), \(\Sigma\)). It shows posterior means, standard deviations, the bounds of an 89% equal-tailed interval (eti89), and convergence diagnostics (\(\hat{R}\) and the two ESS measures).
summary = model.summary()
print(summary)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat \
alpha[0, 0] -0.339 0.051 -0.42 -0.26 563 321 1.00
alpha[1, 0] 0.24 0.05 0.16 0.33 546 353 1.00
beta[0, 0] 1 0 1 1 400 400 NaN
beta[1, 0] -0.455 0.033 -0.51 -0.4 613 330 1.00
Gamma[0, 0] -0.052 0.058 -0.14 0.046 626 313 1.00
Gamma[0, 1] -0.011 0.054 -0.097 0.067 648 348 1.01
Gamma[1, 0] -0.068 0.059 -0.17 0.025 594 323 1.01
Gamma[1, 1] -0.015 0.052 -0.1 0.063 809 347 1.02
Sigma[0, 0] 0.255 0.023 0.22 0.29 548 304 1.00
Sigma[0, 1] 0.001 0.0142 -0.023 0.025 762 363 1.01
Sigma[1, 0] 0.001 0.0142 -0.023 0.025 762 363 1.01
Sigma[1, 1] 0.251 0.019 0.22 0.28 753 364 1.00
mcse_mean mcse_sd
alpha[0, 0] 0.0021 0.0013
alpha[1, 0] 0.0021 0.0016
beta[0, 0] 0 NaN
beta[1, 0] 0.0014 0.0011
Gamma[0, 0] 0.0023 0.0016
Gamma[0, 1] 0.0022 0.0017
Gamma[1, 0] 0.0024 0.0018
Gamma[1, 1] 0.0019 0.0012
Sigma[0, 0] 0.001 0.00076
Sigma[0, 1] 0.00051 0.00034
Sigma[1, 0] 0.00051 0.00034
Sigma[1, 1] 0.00072 0.00051
Walking through the table:
alpha[0, 0]should land near \(-0.4\);alpha[1, 0]near \(0.2\). These are the error-correction loadings: they say how strongly each variable pulls back when the cointegration term wanders from zero.beta[0, 0]is identically 1.0 (sd = 0). This is the pinned identification, not a parameter the data informed.beta[1, 0]is the substantive estimate: near \(-0.5\), with the only free uncertainty in the cointegrating direction.Gamma[i, j]entries should all be close to 0: the DGP has no short-run dynamics, so any structure here is noise the model is absorbing. The interval should comfortably include 0 for each entry.Sigma[i, i]should be near \(\sigma^2 = 0.25\) on the diagonal and near \(0\) off the diagonal: the shocks are independent across the two series in our DGP.r_hatshould be close to 1.0 (PyMC’s rule of thumb: anything above 1.01 is suspicious);ess_bulkshould be in the hundreds at minimum for a small bivariate model with 4 × 1000 draws.
If a column flags an issue (\(\hat{R}\) high, ESS low, or divergences in the sample stats), the usual next steps are: more tuning, more draws, or a higher target_accept. We’ll cover those properly in a diagnostics-focused notebook once we have a few more model variants to compare.
5. What this unlocks and what’s still raw#
Shipped this slice:
BayesianVECM.fit(endog, ...)forcoint_rank=1+deterministic="n". Runs validate → design → build → sample → store.model.idata(property) andmodel.idata_(set during fit) hold the full posterior, withendogand the design matrices stashed insideconstant_dataso a serialised file is self-contained.model.summary()wrapsarviz.summarywith a sensible defaultvar_names.The \(\beta\)-identification problem from notebooks 02–03 is solved by pinning \(\beta[:r, :] = I_r\). This is the standard Johansen normalisation; the trade-off (the recovered \(\beta\) is in a chosen scale, not the raw \(\alpha\beta'\) scale) is documented in the docstring and surfaced via the
pm.Deterministic("beta", ...)node.
Still raw, in roadmap order:
sample_posterior_predictive. Currently raisesNotImplementedError. Next slice. Forecasting through the VAR recursion (seed fromself.endog_[-(k_ar_diff + 1):], draw \(\varepsilon\) from the posterior \(\Sigma\), roll forward) is meaningfully its own design problem and gets its own branch + notebook 05.Higher cointegration rank (\(r > 1\)). The free \(\beta\) block becomes \((K-r) \times r\), and we need to decide how to surface rank uncertainty (Bayesian model averaging across separate fits).
Deterministic terms (\(\text{co}, \text{ci}, \text{lo}, \text{li}\)).
cointegration_designalready produces the augmented matrices; the PyMC graph just needs to grow a coefficient block for them.CI execution of notebooks. Currently nothing checks that this notebook still runs end-to-end after future refactors. Adding
nbconvert --executeto CI catches silent drift.
The package’s public surface has now reached the headline goal set at the start: Construct a BayesianVECM, call fit(endog), inspect idata and summary(). It’s the first working Bayesian VECM, not just an API skeleton.