01. Data utilities walkthrough#

This notebook walks through the three preprocessing helpers that live in bayesian_vecm._data:

  • validate_endog: sanitise user input into a clean (T, K) float64 array.

  • difference: turn a non-stationary series y into its differences Δy.

  • lag_matrix: stack lagged observations into a regressor matrix.

It is written for someone meeting VECMs (Vector Error Correction Models) for the first time. Each section explains what the helper does, why a VECM needs it, and shows a small synthetic example you can read row-by-row.

A 60-second VECM primer#

A VECM models several time series jointly when each individual series is non-stationary (typically I(1), meaning it wanders, but its first difference is stable) and the series move together in the long run. The model is:

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

Reading the right-hand side piece by piece:

  • \(\alpha\, \beta'\, y_{t-1}\): the error-correction term. \(\beta' y_{t-1}\) measures how far the system was from its long-run equilibrium yesterday; \(\alpha\) controls how fast each variable corrects toward that equilibrium today.

  • \(\Gamma_i \Delta y_{t-i}\): the short-run dynamics, how today’s changes depend on previous changes.

  • \(\varepsilon_t\): Gaussian innovations.

To estimate this we need three matrices, derived from raw y:

Equation piece

What we need to compute

Helper

\(\Delta y_t\) (LHS)

First differences of y

difference

\(\Delta y_{t-i}\) (RHS, \(\Gamma\) blocks)

Stacked lags of Δy

lag_matrix (applied to differences)

\(y_{t-1}\) (inside \(\beta'\))

One-period lag of y itself

lag_matrix (applied to levels)

…and all of those depend on y being a clean (T, K) numeric array, which is what validate_endog guarantees. So these three little helpers cover every preprocessing step a VECM needs.

from __future__ import annotations

import numpy as np

from bayesian_vecm._data import difference, lag_matrix, validate_endog

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

1. validate_endog: get the input into a known-good shape#

What it does#

validate_endog(data, *, min_obs=2) takes whatever the user passed in and returns a fresh, contiguous float64 array of shape (T, K). Specifically it:

  1. Accepts a 2-D numpy array or anything with a .to_numpy() method (so a pandas.DataFrame works without us depending on pandas).

  2. Casts to float64 (so integer inputs don’t silently break later arithmetic).

  3. Returns an independent copy, so downstream code can mutate freely.

  4. Raises a ValueError if the input is 1-D or 3-D, contains NaN, has fewer than min_obs rows, has zero columns, or can’t be cast to float.

Why a VECM needs it#

Real-world inputs are messy: integer dtypes, missing values, lone series passed as 1-D vectors. A VECM is a multivariate model, so silently accepting a 1-D series would lead to baffling shape errors deep inside the PyMC graph. validate_endog fails loudly and early, with a message you can act on.

It also lets every other function in the package assume a clean numpy array, which keeps difference, lag_matrix, and (later) the model code small and easy to test.

Demo 1a: happy path with a numpy array#

raw = np.arange(12).reshape(6, 2)  # int dtype on purpose
print("raw dtype:", raw.dtype, "shape:", raw.shape)

clean = validate_endog(raw)
print("clean dtype:", clean.dtype, "shape:", clean.shape)
print(clean)
raw dtype: int64 shape: (6, 2)
clean dtype: float64 shape: (6, 2)
[[ 0.  1.]
 [ 2.  3.]
 [ 4.  5.]
 [ 6.  7.]
 [ 8.  9.]
 [10. 11.]]

Demo 1b: DataFrame-like input via duck typing#

validate_endog looks for a .to_numpy() method, so any DataFrame-like object works. We don’t depend on pandas in the package, so here’s a 5-line stand-in:

class FakeFrame:
    def __init__(self, array):
        self._array = array

    def to_numpy(self):
        return self._array


df = FakeFrame(np.array([[1.0, 10.0], [2.0, 20.0], [3.0, 30.0]]))
validate_endog(df)
array([[ 1., 10.],
       [ 2., 20.],
       [ 3., 30.]])

Demo 1c: what kinds of bad input get rejected#

Each of these raises a ValueError with a message naming the problem.

bad_inputs = {
    "1-D vector": np.arange(10, dtype=float),
    "contains NaN": np.array([[1.0, 2.0], [np.nan, 4.0], [5.0, 6.0]]),
    "too few observations": np.array([[1.0, 2.0]]),
    "zero variables": np.empty((10, 0)),
}

for label, data in bad_inputs.items():
    try:
        validate_endog(data)
    except ValueError as exc:
        print(f"{label:22s} -> {exc}")
1-D vector             -> endog must be 2-dimensional with shape (T, K); got ndim=1
contains NaN           -> endog must not contain NaN values
too few observations   -> endog must have at least 2 observations; got T=1
zero variables         -> endog must have at least one variable (K >= 1)

2. difference: turn levels into changes#

What it does#

difference(data, d=1) applies the difference operator \((1 - L)^d\) to a (T, K) array. For d=1 that is simply

\[\Delta y_t = y_t - y_{t-1}\]

applied independently to each column. Higher d is just the operator applied recursively, so the output has shape (T - d, K). (d=0 returns a copy.)

Why a VECM needs it#

Most macro-financial series (GDP, prices, exchange rates) are non-stationary: their level wanders without settling around a constant mean. Standard regression machinery assumes stationarity, so we can’t model the levels directly.

The trick that makes a VECM work is that each series is non-stationary in levels but stationary in first differences (this is what economists call I(1)). The LHS of the VECM equation is \(\Delta y_t\) (the changes) precisely so we’re regressing one stationary thing on others.

In short: difference is what gets us onto stationary ground.

Demo 2a: a linear trend has constant first differences#

Consider two variables that grow linearly. The level keeps increasing forever (non-stationary), but the change from one period to the next is constant (stationary). difference strips the trend out:

y = np.column_stack(
    [
        np.arange(6, dtype=float),  # 0, 1, 2, 3, 4, 5
        100.0 + 3.0 * np.arange(6),  # 100, 103, 106, 109, 112, 115
    ]
)
print("levels y (T=6, K=2):")
print(y)
print()
print("first differences Δy (shape", difference(y).shape, "):")
print(difference(y))
levels y (T=6, K=2):
[[  0. 100.]
 [  1. 103.]
 [  2. 106.]
 [  3. 109.]
 [  4. 112.]
 [  5. 115.]]

first differences Δy (shape (5, 2) ):
[[1. 3.]
 [1. 3.]
 [1. 3.]
 [1. 3.]
 [1. 3.]]

Both columns reduce to a constant change per period: exactly what “trend has been removed” looks like.

Demo 2b: second differences#

If a series has a quadratic trend, one round of differencing yields a linear trend; a second round flattens it. This is what the recursive part of difference does.

t = np.arange(5, dtype=float)
quadratic = (t**2).reshape(-1, 1)  # 0, 1, 4, 9, 16
print("levels:        ", quadratic.ravel())
print("first diff:    ", difference(quadratic, d=1).ravel())  # 1, 3, 5, 7
print("second diff:   ", difference(quadratic, d=2).ravel())  # 2, 2, 2
levels:         [ 0.  1.  4.  9. 16.]
first diff:     [1. 3. 5. 7.]
second diff:    [2. 2. 2.]

In practice for a VECM you almost always want d=1: the model assumes the series are I(1), not I(2). Having d > 1 available is a nice-to-have for diagnostics.

3. lag_matrix: stack lagged observations into a regressor matrix#

What it does#

lag_matrix(data, n_lags) takes a (T, K) array and builds a (T - n_lags, K * n_lags) matrix where each row holds the lagged values needed to predict that row’s target.

The column ordering is lag-major, most-recent-first: with n_lags = 2 and a series \(y_0, y_1, y_2, y_3, \dots\), row \(r\) of the output is

\[\big[\, y_{r+1}, \; y_{r} \,\big]\]

(each \(y\) is itself a K-vector, and the \(K\) entries of each lag sit contiguously). This matches statsmodels.tsa.vector_ar, which matters because we want to be able to cross-check our results against statsmodels.

Why a VECM needs it#

Look back at the VECM equation: the right-hand side has \(\Delta y_{t-1}, \dots, \Delta y_{t-k}\) multiplied by matrices \(\Gamma_1, \dots, \Gamma_k\). To estimate those \(\Gamma\) blocks via standard regression machinery, the regressors at each row need to be laid out as a single wide vector. That’s exactly the design matrix lag_matrix returns.

The same helper, applied to the levels y rather than the differences Δy, also gives us the \(y_{t-1}\) term that sits inside the cointegration relation \(\beta' y_{t-1}\): the piece that distinguishes a VECM from a plain VAR-in-differences.

Demo 3a: one lag, two variables#

Read this carefully: with n_lags = 1, output row r is the regressor needed to predict row r + 1 of the target.

y = np.array(
    [
        [1.0, 10.0],  # y_0
        [2.0, 20.0],  # y_1
        [3.0, 30.0],  # y_2
        [4.0, 40.0],  # y_3
    ]
)
lagged = lag_matrix(y, n_lags=1)
print("input shape:  ", y.shape)
print("output shape: ", lagged.shape, "  (T - n_lags, K * n_lags)")
print()
print("output rows:")
for r, row in enumerate(lagged):
    print(f"  row {r}: {row}   <- predicts y_{r + 1} = {y[r + 1]}")
input shape:   (4, 2)
output shape:  (3, 2)   (T - n_lags, K * n_lags)

output rows:
  row 0: [ 1. 10.]   <- predicts y_1 = [ 2. 20.]
  row 1: [ 2. 20.]   <- predicts y_2 = [ 3. 30.]
  row 2: [ 3. 30.]   <- predicts y_3 = [ 4. 40.]

Demo 3b: two lags, and the lag-major / most-recent-first column order#

This is the easiest place to get confused. With n_lags = 2, each output row holds two lags concatenated, with the most recent lag first.

lagged2 = lag_matrix(y, n_lags=2)
print("output shape:", lagged2.shape, "  (T - n_lags, K * n_lags)")
print()
col_labels = "  cols: [y_{t-1}[0]  y_{t-1}[1]   y_{t-2}[0]  y_{t-2}[1]]"
print(col_labels)
for r, row in enumerate(lagged2):
    target_t = r + 2
    print(f"  row {r}: {row}   <- predicts y_{target_t} = {y[target_t]}")
output shape: (2, 4)   (T - n_lags, K * n_lags)

  cols: [y_{t-1}[0]  y_{t-1}[1]   y_{t-2}[0]  y_{t-2}[1]]
  row 0: [ 2. 20.  1. 10.]   <- predicts y_2 = [ 3. 30.]
  row 1: [ 3. 30.  2. 20.]   <- predicts y_3 = [ 4. 40.]

So row 0 of lagged2 is [y_1, y_0]: y_1 is the more recent lag and appears first. If you ever read Γ_1, Γ_2 in econometrics notation, the columns are in the matching order, which is why this convention was chosen.

Demo 3c: n_lags = 0 returns an empty-column array#

This sounds pointless, but it’s surprisingly useful: it lets calling code unconditionally ask for a lag block, and if the user requested zero lags they just get a (T, 0) array that contributes nothing to the regression. No special-casing needed downstream.

empty = lag_matrix(y, n_lags=0)
print("shape:", empty.shape)
shape: (4, 0)

4. Putting the three together: a preview#

Here’s what the full preprocessing pipeline for a VECM looks like, using all three helpers. We’ll use a tiny cointegrated synthetic pair so the example has VECM-like structure: x is a random walk, z follows x with a small correction, and the difference z - 0.8 * x is stationary noise: that stationary linear combination is the cointegration relation a VECM is designed to find.

rng = np.random.default_rng(0)

T = 8
shocks = rng.standard_normal((T, 2)) * 0.1
x = np.cumsum(shocks[:, 0])  # random walk -> non-stationary (I(1))
z = 0.8 * x + shocks[:, 1]  # tracks x with stationary noise

y = np.column_stack([x, z])
print("raw y (levels, T=8, K=2):")
print(y)
raw y (levels, 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]]
# Step 1: validate
y_clean = validate_endog(y)

# Step 2: differences for the LHS of the VECM equation
delta_y = difference(y_clean, d=1)
print("Δy (LHS, shape", delta_y.shape, "):")
print(delta_y)
Δy (LHS, shape (7, 2) ):
[[ 0.064  0.075]
 [-0.054 -0.017]
 [ 0.13   0.163]
 [-0.07  -0.278]
 [-0.062  0.081]
 [-0.233 -0.212]
 [-0.125 -0.151]]
# Step 3a: lags of Δy for the Γ blocks (let's pick k_ar_diff = 1 lag)
k_ar_diff = 1
delta_x = lag_matrix(delta_y, n_lags=k_ar_diff)
print(f"lagged Δy with n_lags={k_ar_diff} (Γ regressors, shape {delta_x.shape}):")
print(delta_x)
lagged Δy with n_lags=1 (Γ regressors, shape (6, 2)):
[[ 0.064  0.075]
 [-0.054 -0.017]
 [ 0.13   0.163]
 [-0.07  -0.278]
 [-0.062  0.081]
 [-0.233 -0.212]]
# Step 3b: one-period lag of the *levels* y for the β' y_{t-1} term
y_lag1 = lag_matrix(y_clean, n_lags=1)
print("y_{t-1} (levels lag, shape", y_lag1.shape, "):")
print(y_lag1)
y_{t-1} (levels lag, shape (7, 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]]

What’s still missing#

Notice that the three matrices above don’t all have the same number of rows yet:

  • delta_y : (T-1, K) = (7, 2)

  • delta_x : (T-1-k_ar_diff, K*k_ar_diff) = (6, 2)

  • y_lag1 : (T-1, K) = (7, 2)

To plug them into a single regression, every row needs to refer to the same time index \(t\). That trimming-and-aligning step is what notebook 02 covers: a helper called cointegration_design that wraps these three primitives and returns all three matrices aligned to the common effective sample \(T_{\text{eff}} = T - k - 1\).

But the building blocks (validate_endog, difference, lag_matrix) are already in place, tested, and (now) explained. That’s the foundation a VECM is built on.