03. BayesianVECM skeleton walkthrough#
This notebook walks through the public-facing BayesianVECM class: the headline API of the whole package, and what this slice ships.
Two things up front:
No estimation runs yet. Every method that depends on a fitted PyMC graph (
fit,idata,summary,sample_posterior_predictive) raisesNotImplementedError. That isn’t a bug: it’s the point. The skeleton’s job is to lock in the shape of the public API before any sampling code lands, so we don’t end up retrofitting an API around a model graph instead of the other way round.This notebook still earns its keep. The class encodes three real design decisions about how a Bayesian VECM should be configured, what’s init-time vs fit-time state, and how priors are specified. Those decisions are what we’ll walk through, with live demos of the bits that do run (construction, validation) and prose for the bits that don’t (the post-fit attributes).
Written before
fitexisted. At this stage every method that needs a fitted graph raisedNotImplementedError. They are all implemented now: notebook 04 fits the model and notebook 05 forecasts. The pre-fit guard in §6 and the configuration checks still behave as shown.
If you haven’t read notebook 02, the very short summary is: the preprocessing helpers in _data.py and _design.py turn a raw (T, K) series into three aligned matrices a VECM regression actually consumes. This notebook starts where that ends: given the design matrices, what does the public API look like?
from __future__ import annotations
from bayesian_vecm import BayesianVECM
1. The class in one breath#
Construct a model and inspect what it stores. With no arguments, you get the documented defaults: one lagged-difference block, cointegration rank 1, no deterministic terms, no user-supplied priors.
model = BayesianVECM()
print(f"k_ar_diff = {model.k_ar_diff}")
print(f"coint_rank = {model.coint_rank}")
print(f"deterministic = {model.deterministic!r}")
print(f"priors = {model.priors}")
k_ar_diff = 1
coint_rank = 1
deterministic = 'n'
priors = None
That’s the entire init-time surface area. Every other attribute on the class (endog_, idata_, …) is fit-time state, and we’ll discuss those below, but they don’t exist yet because fit raises.
2. Configuration in __init__, data in fit#
Notice that all four constructor arguments are model configuration, not data. endog doesn’t appear until fit(endog). That separation matters most for coint_rank:
where \(\alpha\) is \(K \times r\) and \(\beta\) is \(K \times r\). Changing \(r\) changes the shape of two of the model’s free parameters, which means the PyMC graph has to be rebuilt from scratch. So “re-fit with a different rank” was never going to be a cheap operation: you may as well construct a new model.
That sounds like a small detail; in practice it’s the thing that determines the rank-selection workflow.
# Two models with different rank: fully independent objects.
m1 = BayesianVECM(coint_rank=1)
m2 = BayesianVECM(coint_rank=2, k_ar_diff=2, deterministic="ci")
for name, m in [("m1", m1), ("m2", m2)]:
print(f"{name}: rank={m.coint_rank}, k_ar_diff={m.k_ar_diff}, det={m.deterministic!r}")
m1: rank=1, k_ar_diff=1, det='n'
m2: rank=2, k_ar_diff=2, det='ci'
The rank-selection workflow falls out naturally: construct one model per candidate rank, fit each one, keep all of the resulting idatas. That keeps everything available for the eventual Bayesian-model-averaging step over \(r\). That step is future work, but it is easy to lay the ground for now.
# Sketch: once `fit` is implemented this is the rank-selection loop.
fitted = {}
for r in [1, 2, 3]:
fitted[r] = BayesianVECM(coint_rank=r)
# fitted[r].fit(endog) # fitting is shown in notebook 04
print({r: f"rank={m.coint_rank}" for r, m in fitted.items()})
{1: 'rank=1', 2: 'rank=2', 3: 'rank=3'}
3. Priors as a plain dict#
priors is a dict[str, dict]. Keys are parameter names ("alpha", "beta", "Gamma", "Sigma"); each value is a distribution spec of the form {"dist": "<Name>", **kwargs}. Anything you omit falls back to a weakly-informative default chosen at fit time.
This is inspired by the pymc_marketing.MMM pattern but kept one step simpler: no dedicated Prior class. Trade-offs:
Pros. Trivial to document. JSON-serialisable, so a model config can be checked into a repo or sent over the wire. Forward-compatible: a richer
Prior-style object can be accepted in addition later without breaking dict callers.Cons. No structured validation of the dict’s contents at init time: that happens at
fittime, once we know what parameters are needed (e.g., dimensions depend onKwhich we don’t see until the data arrives). Init only checks thatpriorsis eitherNoneor a dict; everything else is deferred.
priors = {
"alpha": {"dist": "Normal", "mu": 0.0, "sigma": 1.0},
"Sigma": {"dist": "LKJCholeskyCov", "eta": 2.0},
}
m_priors = BayesianVECM(priors=priors)
print("priors stored verbatim:", m_priors.priors)
print()
print("`None` and `{}` are both legal: both mean 'use defaults':")
print(" BayesianVECM().priors =", BayesianVECM().priors)
print(" BayesianVECM(priors={}).priors =", BayesianVECM(priors={}).priors)
priors stored verbatim: {'alpha': {'dist': 'Normal', 'mu': 0.0, 'sigma': 1.0}, 'Sigma': {'dist': 'LKJCholeskyCov', 'eta': 2.0}}
`None` and `{}` are both legal: both mean 'use defaults':
BayesianVECM().priors = None
BayesianVECM(priors={}).priors = {}
4. Post-fit state lives on the model as endog_ (sklearn style)#
After fit(endog) runs, the model will expose three new attributes, all with a trailing underscore: the scikit-learn convention meaning “set during fit, not init”:
endog_: the input array, shape(T, K).idata_: the fullarviz.InferenceDataposterior record.variable_names_: column labels, if the input exposed them (e.g. apandas.DataFrame).
Why store endog at all, rather than just idata? Because forecasting needs it. sample_posterior_predictive(steps=12) is a forecast: it seeds the recursion with the last k_ar_diff + 1 rows of the original series and rolls forward. Requiring the caller to pass endog again at predict time is friction and a footgun: if they accidentally pass a different series, the forecast silently becomes nonsense.
Belt and braces: the same endog will also be stored inside idata_.constant_data. The two storage locations serve different needs:
self.endog_: fast attribute access on the live object.idata_.constant_data: keeps a serialisedidataself-contained, so somebody who only has the saved posterior file can still reproduce a forecast without needing the original Python object.
When this notebook was written fit raised, so these attributes were only a contract. Notebook 04 shows them on a fitted model.
5. Validation is eager#
Configuration errors are caught at construction time, not deferred to fit. That means typos and bad-shape mistakes surface immediately, with a clear message, rather than a confusing PyMC traceback later.
bad_configs = [
{"k_ar_diff": -1},
{"coint_rank": 0},
{"deterministic": "N"}, # case matters
{"deterministic": "cili"}, # compound Johansen case: not supported
{"priors": [("alpha", "Normal")]}, # not a dict
]
for cfg in bad_configs:
try:
BayesianVECM(**cfg)
except (ValueError, TypeError) as exc:
print(f"{cfg!r:50s} -> {type(exc).__name__}: {exc}")
{'k_ar_diff': -1} -> ValueError: k_ar_diff must be non-negative; got k_ar_diff=-1
{'coint_rank': 0} -> ValueError: coint_rank must be at least 1; got coint_rank=0
{'deterministic': 'N'} -> ValueError: deterministic must be one of ['ci', 'co', 'li', 'lo', 'n']; got deterministic='N'. Compound Johansen codes (cases 4 and 5) are a v0.x follow-up.
{'deterministic': 'cili'} -> ValueError: deterministic must be one of ['ci', 'co', 'li', 'lo', 'n']; got deterministic='cili'. Compound Johansen codes (cases 4 and 5) are a v0.x follow-up.
{'priors': [('alpha', 'Normal')]} -> TypeError: priors must be a dict or None; got priors of type list
# The five single-character deterministic codes are all accepted.
for code in ["n", "co", "ci", "lo", "li"]:
m = BayesianVECM(deterministic=code)
print(f"deterministic={code!r:6s} -> model.deterministic = {m.deterministic!r}")
deterministic='n' -> model.deterministic = 'n'
deterministic='co' -> model.deterministic = 'co'
deterministic='ci' -> model.deterministic = 'ci'
deterministic='lo' -> model.deterministic = 'lo'
deterministic='li' -> model.deterministic = 'li'
6. Pre-fit guard: calling methods before fitting#
Note: when this notebook was first written,
fit,idata,summary, andsample_posterior_predictiveall raisedNotImplementedError. They are now fully implemented: see notebooks 04 and 05 for live demos. What does still apply is the pre-fit guard: callingidata,summary, orsample_posterior_predictivebeforefitraises aRuntimeErrorwith a clear message rather than anAttributeError. That guard is part of the class contract locked in by this skeleton, so it’s worth demonstrating.
m = BayesianVECM()
for call_desc, call in [
("model.idata", lambda: m.idata),
("model.summary()", lambda: m.summary()),
("model.sample_posterior_predictive(12)", lambda: m.sample_posterior_predictive(steps=12)),
]:
try:
call()
except RuntimeError as exc:
print(f"{call_desc:45s} -> RuntimeError: {exc}")
model.idata -> RuntimeError: BayesianVECM has not been fitted yet; call .fit(endog) first.
model.summary() -> RuntimeError: BayesianVECM has not been fitted yet; call .fit(endog) first.
model.sample_posterior_predictive(12) -> RuntimeError: BayesianVECM has not been fitted yet; call .fit(endog) first.
7. The headline problem for the next slice: identification of \(\beta\)#
Notebook 02 flagged this; here’s the slightly fuller version, because it’s the first piece of real econometrics the next slice will have to solve.
The cointegration term in the VECM is \(\alpha \beta' y_{t-1}\), with \(\alpha\) a \(K \times r\) loading matrix and \(\beta\) a \(K \times r\) cointegrating-vector matrix. Only the product \(\alpha \beta'\) enters the likelihood. So for any invertible \(r \times r\) matrix \(R\),
which means the pair \((\alpha, \beta)\) and the pair \((\alpha R^{-1}, \beta R^{\top})\) describe identical models. The likelihood can’t distinguish them. Concretely, for the simplest case \(K=2, r=1\), \(R\) is just a non-zero scalar \(c\): replacing \(\alpha\) with \(\alpha / c\) and \(\beta\) with \(\beta \cdot c\) leaves the model unchanged.
Why this matters for Bayesian inference: without a constraint, the posterior over \(\beta\) alone is non-identified. The sampler can wander along the \(R\) orbit without ever resolving where on it it should sit. In practice that shows up as terrible mixing, divergent transitions, and an inability to report a sensible posterior mean for \(\beta\).
The standard fix (going back to Johansen, 1995) is to normalise \(\beta\) by fixing its top \(r \times r\) block to the identity: \(\beta[:r, :] = I_r\). That uses up exactly the \(r \times r\) degrees of freedom \(R\) provides, leaving a unique \(\beta\) that the sampler can converge on.
Implementing this in PyMC is the central design choice of the feat/first-pymc-model slice. The skeleton class is deliberately silent on it for now: the question is “what does the API look like?”, not “how do we make sampling work?”.
8. What this unlocks#
With the class skeleton in place, the next slice has somewhere to attach. feat/first-pymc-model is going to:
Implement
BayesianVECM.fit(endog)end-to-end for the smallest realistic case: known cointegration rank \(r = 1\),deterministic="n", weakly-informative defaults for \(\alpha\), \(\beta\), \(\Gamma_i\), \(\Sigma\). Callscointegration_designunder the hood (notebook 02).Solve the \(\beta\)-identification problem with a clean normalisation: probably
β[:r, :] = I_rper the discussion above, but worth re-checking against Johansen 1995 once we’re writing PyMC code.Add
pymcandarvizas runtime dependencies.Build out
model.idata,model.summary(), andmodel.sample_posterior_predictive(steps=...)as thin wrappers around the fitted record.Ship its own walkthrough notebook (04), fitting on the synthetic cointegrated series from notebook 02 and showing whether the recovered \(\beta\) matches the true cointegrating vector.
Until then, the class exists and the public-API contract is locked in. That alone is real progress: it forces the next slice to fit into an API rather than design one along the way.