02. Cointegration design#

This notebook walks through cointegration_design, the helper in bayesian_vecm._design that turns a raw (T, K) series into the three aligned matrices a VECM regression equation actually consumes.

It builds directly on notebook 01, which ended with three matrices of mismatched row counts and an open question: how do we line them up so every row refers to the same time index? That question is exactly what this helper answers.

If you haven’t read notebook 01, the very short version: validate_endog cleans the input, difference gives you Δy, and lag_matrix stacks lags. This notebook glues those three together.

from __future__ import annotations

import numpy as np

from bayesian_vecm._data import difference, lag_matrix
from bayesian_vecm._design import CointegrationDesign, cointegration_design

np.set_printoptions(precision=3, suppress=True)

1. The alignment problem#

Recall the VECM equation:

\[\Delta y_t = \alpha\, \beta'\, y_{t-1} + \Gamma_1 \Delta y_{t-1} + \dots + \Gamma_k \Delta y_{t-k} + \varepsilon_t\]

For each row of the regression we need three things, all evaluated at the same time \(t\):

Symbol

Role

Shape per row

\(\Delta y_t\)

left-hand side

\(K\)

\(y_{t-1}\)

feeds \(\beta' y_{t-1}\) (the error-correction term)

\(K\)

\([\Delta y_{t-1}, \dots, \Delta y_{t-k}]\)

feeds \(\Gamma_1, \dots, \Gamma_k\)

\(K \cdot k\)

Each of those individually is easy to build with the helpers from notebook 01. The hard part is that they have different smallest-defined-time-index \(t\):

  • \(\Delta y_t\) needs \(y_t\) and \(y_{t-1}\), so \(t \geq 1\).

  • \(y_{t-1}\) as a level needs \(t \geq 1\) (trivially satisfied).

  • \(\Delta y_{t-k}\) needs \(y_{t-k}\) and \(y_{t-k-1}\), so \(t \geq k + 1\).

The binding constraint is the last one. The earliest usable \(t\) is \(k + 1\) (0-based), and \(t\) runs up to \(T - 1\), so the regression has

\[T_{\text{eff}} = T - k - 1\]

rows in total. cointegration_design does this trimming for you and hands back three matrices, each of shape (T_eff, …), with row \(r\) of every matrix corresponding to the same time \(t = k + 1 + r\).

2. A tiny hand-built example you can read by eye#

Use the same (T=5, K=2) series the unit tests are built around. The numbers are picked so the differences are easy to read off mentally:

\(t\)

\(y_t\)

\(\Delta y_t\)

0

\((1, 10)\)

none

1

\((2, 20)\)

\((1, 10)\)

2

\((4, 40)\)

\((2, 20)\)

3

\((7, 70)\)

\((3, 30)\)

4

\((11, 110)\)

\((4, 40)\)

With \(k = 1\) we get \(T_{\text{eff}} = 5 - 1 - 1 = 3\) usable rows, corresponding to \(t \in \{2, 3, 4\}\). Let’s run the helper and inspect each output.

y = np.array(
    [
        [1.0, 10.0],  # y_0
        [2.0, 20.0],  # y_1
        [4.0, 40.0],  # y_2
        [7.0, 70.0],  # y_3
        [11.0, 110.0],  # y_4
    ]
)

design = cointegration_design(y, k_ar_diff=1)
assert isinstance(design, CointegrationDesign)
print("Returned:", type(design).__name__, "with fields:", design._fields)
print()
print("delta_y shape:", design.delta_y.shape)
print("delta_x shape:", design.delta_x.shape)
print("y_lag1  shape:", design.y_lag1.shape)
Returned: CointegrationDesign with fields: ('delta_y', 'delta_x', 'y_lag1', 'exog')

delta_y shape: (3, 2)
delta_x shape: (3, 2)
y_lag1  shape: (3, 2)

All three are (3, 2): T_eff rows of K (or K*k) columns each. Now the row-by-row content:

for r in range(design.delta_y.shape[0]):
    t = 1 + 1 + r  # k_ar_diff + 1 + r, the time index this row refers to
    print(f"row r={r}  (t={t}):")
    print(f"  delta_y = {design.delta_y[r]}    <- Δy_{t} = y_{t} - y_{t - 1}")
    print(f"  y_lag1  = {design.y_lag1[r]}    <- y_{t - 1}")
    print(f"  delta_x = {design.delta_x[r]}    <- [Δy_{t - 1}]")
    print()
row r=0  (t=2):
  delta_y = [ 2. 20.]    <- Δy_2 = y_2 - y_1
  y_lag1  = [ 2. 20.]    <- y_1
  delta_x = [ 1. 10.]    <- [Δy_1]

row r=1  (t=3):
  delta_y = [ 3. 30.]    <- Δy_3 = y_3 - y_2
  y_lag1  = [ 4. 40.]    <- y_2
  delta_x = [ 2. 20.]    <- [Δy_2]

row r=2  (t=4):
  delta_y = [ 4. 40.]    <- Δy_4 = y_4 - y_3
  y_lag1  = [ 7. 70.]    <- y_3
  delta_x = [ 3. 30.]    <- [Δy_3]

Notice the alignment: row \(r=0\) refers to \(t=2\) in all three matrices. That’s the property that makes these three arrays drop straight into a regression: each row is one equation evaluated at one time.

Cross-check by hand#

Convince yourself that what came out matches what you’d build with the lower-level helpers from notebook 01 (difference and lag_matrix) once you trim the right rows:

delta = difference(y, d=1)  # shape (T-1, K) = (4, 2)
print("difference(y):")
print(delta)
print()
print("delta_y should be the last T_eff rows of difference(y):")
print(delta[1:])  # drop the first k_ar_diff = 1 rows
difference(y):
[[ 1. 10.]
 [ 2. 20.]
 [ 3. 30.]
 [ 4. 40.]]

delta_y should be the last T_eff rows of difference(y):
[[ 2. 20.]
 [ 3. 30.]
 [ 4. 40.]]
print("delta_x should be lag_matrix(difference(y), n_lags=1):")
print(lag_matrix(delta, n_lags=1))
print()
print("y_lag1 should be y[k_ar_diff : T-1] = y[1:4]:")
print(y[1:4])
delta_x should be lag_matrix(difference(y), n_lags=1):
[[ 1. 10.]
 [ 2. 20.]
 [ 3. 30.]]

y_lag1 should be y[k_ar_diff : T-1] = y[1:4]:
[[ 2. 20.]
 [ 4. 40.]
 [ 7. 70.]]

All three match the corresponding outputs of cointegration_design. The whole helper is really just: call difference once, slice to align, and run lag_matrix on the differences. The value it adds is doing the alignment correctly so callers never have to think about off-by-one errors in \(T_{\text{eff}}\).

3. The k_ar_diff = 0 special case#

Setting k_ar_diff = 0 removes the short-run dynamics block entirely:

\[\Delta y_t = \alpha\, \beta'\, y_{t-1} + \varepsilon_t.\]

This is the simplest possible VECM: pure error correction, no autocorrelation in the differences. You’d reach for it as a starting point or if diagnostics suggest no residual short-run structure.

cointegration_design handles it cleanly: delta_x comes out as a (T_eff, 0) array, so downstream code that does np.hstack([y_lag1, delta_x]) works unconditionally.

design0 = cointegration_design(y, k_ar_diff=0)
print("k_ar_diff = 0:")
print("  delta_y shape:", design0.delta_y.shape, "  (T_eff = T - 1 = 4)")
print("  delta_x shape:", design0.delta_x.shape, "  <- zero columns")
print("  y_lag1  shape:", design0.y_lag1.shape)
print()
print("delta_y =")
print(design0.delta_y)
print()
print("y_lag1 =")
print(design0.y_lag1)
k_ar_diff = 0:
  delta_y shape: (4, 2)   (T_eff = T - 1 = 4)
  delta_x shape: (4, 0)   <- zero columns
  y_lag1  shape: (4, 2)

delta_y =
[[ 1. 10.]
 [ 2. 20.]
 [ 3. 30.]
 [ 4. 40.]]

y_lag1 =
[[ 1. 10.]
 [ 2. 20.]
 [ 4. 40.]
 [ 7. 70.]]

Notice \(T_{\text{eff}}\) here is \(T - 1 = 4\), not 3: with no lagged differences to bind us, we can use every row except the first (which has no \(y_{t-1}\) to lean on).

4. Higher k_ar_diff and the lag-major column order#

For k_ar_diff = 2, \(\Delta x_t\) holds two lagged differences:

\[\Delta x_t = [\Delta y_{t-1}, \; \Delta y_{t-2}]\]

Each \(\Delta y\) is itself a \(K\)-vector, and they’re concatenated most-recent-first matching the column convention from notebook 01 (and statsmodels). So with \(K = 2\), each row of delta_x has 4 columns, laid out as [Δy_{t-1}[0], Δy_{t-1}[1], Δy_{t-2}[0], Δy_{t-2}[1]].

design2 = cointegration_design(y, k_ar_diff=2)
print("k_ar_diff = 2  (T_eff = 5 - 2 - 1 = 2)")
print()
print("column meaning: [Δy_{t-1}[0]  Δy_{t-1}[1]   Δy_{t-2}[0]  Δy_{t-2}[1]]")
print()
for r in range(design2.delta_y.shape[0]):
    t = 2 + 1 + r  # k_ar_diff + 1 + r
    print(f"row r={r}  (t={t}):")
    print(f"  delta_y = {design2.delta_y[r]}  <- Δy_{t}")
    print(f"  y_lag1  = {design2.y_lag1[r]}  <- y_{t - 1}")
    print(f"  delta_x = {design2.delta_x[r]}")
    print(f"           the four entries are [Δy_{t - 1}, Δy_{t - 2}], each a K=2 vector")
    print()
k_ar_diff = 2  (T_eff = 5 - 2 - 1 = 2)

column meaning: [Δy_{t-1}[0]  Δy_{t-1}[1]   Δy_{t-2}[0]  Δy_{t-2}[1]]

row r=0  (t=3):
  delta_y = [ 3. 30.]  <- Δy_3
  y_lag1  = [ 4. 40.]  <- y_2
  delta_x = [ 2. 20.  1. 10.]
           the four entries are [Δy_2, Δy_1], each a K=2 vector

row r=1  (t=4):
  delta_y = [ 4. 40.]  <- Δy_4
  y_lag1  = [ 7. 70.]  <- y_3
  delta_x = [ 3. 30.  2. 20.]
           the four entries are [Δy_3, Δy_2], each a K=2 vector

When the model picks up \(\Gamma_1\) and \(\Gamma_2\) during estimation, \(\Gamma_1\) multiplies the first \(K\) columns (the most recent lag), \(\Gamma_2\) multiplies the next \(K\) columns, and so on. That column ordering is what makes this all the way through to the eventual PyMC model just work.

5. End-to-end on a tiny cointegrated synthetic dataset#

To bring this back to something that looks like real data, here’s the same small cointegrated pair we built in notebook 01, but this time, after running cointegration_design, the three matrices are aligned and ready to plug into a regression.

Recall the setup: x is a random walk (non-stationary), z = 0.8·x + noise tracks it. Each individual series is \(I(1)\), but the linear combination \(z - 0.8x\) is stationary noise: that’s the cointegration relation, and the \(\beta\) we’d want to recover is (proportional to) \((0.8, -1)\).

For now we’re not fitting anything; we’re just showing that the design matrices come out the right shape and aligned correctly. Notebook 04 fits it.

rng = np.random.default_rng(0)

n_obs = 8
shocks = rng.standard_normal((n_obs, 2)) * 0.1
x = np.cumsum(shocks[:, 0])
z = 0.8 * x + shocks[:, 1]
y_synth = np.column_stack([x, z])

print("raw y_synth (T=8, K=2):")
print(y_synth)
raw y_synth (T=8, K=2):
[[ 0.013 -0.003]
 [ 0.077  0.072]
 [ 0.023  0.055]
 [ 0.153  0.217]
 [ 0.083 -0.06 ]
 [ 0.021  0.021]
 [-0.212 -0.191]
 [-0.336 -0.342]]
design_synth = cointegration_design(y_synth, k_ar_diff=1)
print("All three matrices come out with the same number of rows:")
print(f"  delta_y.shape = {design_synth.delta_y.shape}")
print(f"  delta_x.shape = {design_synth.delta_x.shape}")
print(f"  y_lag1.shape  = {design_synth.y_lag1.shape}")
print()
print(f"  T_eff = T - k - 1 = 8 - 1 - 1 = {design_synth.delta_y.shape[0]}")
print()
print("compared to notebook 01, which ended with shapes (7, 2), (6, 2), (7, 2)")
print("the helper has trimmed them all to a common (T_eff, ...) so a single")
print("regression can use them together.")
All three matrices come out with the same number of rows:
  delta_y.shape = (6, 2)
  delta_x.shape = (6, 2)
  y_lag1.shape  = (6, 2)

  T_eff = T - k - 1 = 8 - 1 - 1 = 6

compared to notebook 01, which ended with shapes (7, 2), (6, 2), (7, 2)
the helper has trimmed them all to a common (T_eff, ...) so a single
regression can use them together.
print("delta_y (LHS):")
print(design_synth.delta_y)
print()
print("y_lag1 (feeds β' y_{t-1}):")
print(design_synth.y_lag1)
print()
print("delta_x (Γ regressors):")
print(design_synth.delta_x)
delta_y (LHS):
[[-0.054 -0.017]
 [ 0.13   0.163]
 [-0.07  -0.278]
 [-0.062  0.081]
 [-0.233 -0.212]
 [-0.125 -0.151]]

y_lag1 (feeds β' y_{t-1}):
[[ 0.077  0.072]
 [ 0.023  0.055]
 [ 0.153  0.217]
 [ 0.083 -0.06 ]
 [ 0.021  0.021]
 [-0.212 -0.191]]

delta_x (Γ regressors):
[[ 0.064  0.075]
 [-0.054 -0.017]
 [ 0.13   0.163]
 [-0.07  -0.278]
 [-0.062  0.081]
 [-0.233 -0.212]]

6. Deterministic terms#

A VECM almost never lives in a world without constants or trends: real time series have means, drifts, and sometimes long-run trends in the equilibrium relationship itself. cointegration_design supports five single-character codes, following statsmodels’ convention:

Code

What it adds

Where the column sits

"n"

Nothing (the default)

none

"co"

Constant outside the cointegration relation

last column of delta_x

"ci"

Constant inside the cointegration relation

last column of y_lag1

"lo"

Linear trend outside the cointegration relation

last column of delta_x

"li"

Linear trend inside the cointegration relation

last column of y_lag1

The inside vs outside distinction matters more than the jargon suggests. Take the constant case:

  • "co": constant outside. The model is $\(\Delta y_t \;=\; \mu_0 \;+\; \alpha\, \beta'\, y_{t-1} \;+\; \dots\)\( Each variable has its own drift \)\mu_0\( *on top of* whatever the cointegration relation is doing. Use this when the levels of the series themselves trend and you don't want that absorbed into \)\beta$.

  • "ci": constant inside. The model is $\(\Delta y_t \;=\; \alpha\, (\beta'\, y_{t-1} + \rho_0) \;+\; \dots\)\( The equilibrium relation itself has a non-zero level \)\rho_0$. Use this when there’s no drift in the levels but you want the cointegrating combination to equilibrate around something other than zero, e.g. a cost-of-carry constant in a finance pair, or a baseline brand-share level.

Trends ("lo" and "li") are the same distinction, one derivative up: a trend outside is each variable drifting linearly; a trend inside is the equilibrium relationship itself drifting.

Compound cases (Johansen 4 = constant outside + trend inside; Johansen 5 = constant outside + trend outside) are not supported. Only single codes are accepted, and a compound code raises a ValueError.

# Build all five design variants on the same tiny dataset to see exactly
# what each code adds. Baseline shape (deterministic="n") is:
#   delta_x.shape == (3, 2)   <- T_eff=3 rows, K*k_ar_diff=2 columns
#   y_lag1.shape  == (3, 2)
for code in ("n", "co", "ci", "lo", "li"):
    d = cointegration_design(y, k_ar_diff=1, deterministic=code)
    print(f"deterministic={code!r}")
    print(f"  delta_x.shape = {d.delta_x.shape}")
    print(f"  y_lag1.shape  = {d.y_lag1.shape}")
    if code in ("co", "lo"):
        print(f"  trailing delta_x column: {d.delta_x[:, -1]}")
    elif code in ("ci", "li"):
        print(f"  trailing y_lag1 column:  {d.y_lag1[:, -1]}")
    print()
deterministic='n'
  delta_x.shape = (3, 2)
  y_lag1.shape  = (3, 2)

deterministic='co'
  delta_x.shape = (3, 3)
  y_lag1.shape  = (3, 2)
  trailing delta_x column: [1. 1. 1.]

deterministic='ci'
  delta_x.shape = (3, 2)
  y_lag1.shape  = (3, 3)
  trailing y_lag1 column:  [1. 1. 1.]

deterministic='lo'
  delta_x.shape = (3, 3)
  y_lag1.shape  = (3, 2)
  trailing delta_x column: [1. 2. 3.]

deterministic='li'
  delta_x.shape = (3, 2)
  y_lag1.shape  = (3, 3)
  trailing y_lag1 column:  [1. 2. 3.]

The shape contract is straightforward: an outside term bumps delta_x.shape[1] by 1; an inside term bumps y_lag1.shape[1] by 1; the row count T_eff is unchanged.

Trend columns are 1-indexed ([1, 2, ..., T_eff]). The exact origin is arbitrary (only the slope coefficient is invariant under shifts of the trend), so we picked the convention that keeps the column strictly positive and easy to read.

Compound codes like "colo" or "cili" raise a ValueError with a message that names them as unsupported. The failure tells you whether you’ve mistyped or hit the documented gap:

try:
    cointegration_design(y, k_ar_diff=1, deterministic="colo")
except ValueError as exc:
    print("ValueError:", exc)
ValueError: deterministic='colo' looks like a compound code. Compound deterministic cases (Johansen cases 4 and 5, e.g. 'colo', 'cili') are a planned follow-up; v0 supports only single codes ['ci', 'co', 'li', 'lo', 'n'].

7. What this unlocks and what comes next#

With aligned design matrices in hand, the VECM regression equation

\[\Delta y_t = \alpha\, \beta'\, y_{t-1} + \Gamma_1 \Delta y_{t-1} + \dots + \Gamma_k \Delta y_{t-k} + \varepsilon_t\]

becomes a perfectly ordinary linear model: delta_y regressed on [y_lag1, delta_x], where the coefficient on y_lag1 is the rank-r outer product \(\alpha \beta'\).

The remaining work to get to a Bayesian VECM was:

  1. Priors. Sensible weakly-informative defaults on \(\alpha\), \(\beta\), \(\Gamma_i\), and the residual covariance \(\Sigma\). pymc_marketing.MMM is the model for the priors API: optional, overridable, with good defaults.

  2. PyMC graph. Build the model with \(\alpha \beta'\) as a rank-r factorisation, \(\Gamma_i\) as free matrices, and an LKJ prior on \(\Sigma\).

  3. Identification of \(\beta\). A subtle issue: \(\alpha \beta'\) is invariant under \((\alpha, \beta) \to (\alpha R^{-1}, \beta R^{\top})\) for any invertible \(R\). Without a normalisation (e.g. fixing \(\beta[:r, :] = I_r\)), the posterior over \(\beta\) alone is non-identified and sampling will struggle. This is the first real piece of econometrics we’ll hit.

Constants and linear trends (single codes) are now part of cointegration_design: see §6 above. Compound cases (Johansen 4 and 5) are still not supported.

But the data plumbing is now done. From here on, everything is modelling.