The model#

class BayesianVECM(k_ar_diff=1, coint_rank=1, deterministic='n', priors=None, exog_lags=0, adstock=None, adstock_max_lag=8, saturation=None, contemporaneous=None, excluded=None, fading=None)[source]#

Bayesian Vector Error Correction Model.

A fixed-rank cointegrated VAR estimated by Bayesian inference. The model being targeted is

\[\Delta y_t = \alpha \beta' y_{t-1} + \sum_{i=1}^{k} \Gamma_i \, \Delta y_{t-i} + \sum_{l=0}^{L} B_l x_{t-l} + D_t \Phi + \varepsilon_t, \quad \varepsilon_t \sim \mathcal{N}(0, \Sigma),\]

where \(\alpha, \beta\) are \(K \times r\), the \(\Gamma_i\) are \(K \times K\) short-run dynamics, and \(D_t\) collects any requested deterministic terms (constants, trends, inside or outside the cointegration relation). \(x_t\) holds the exogenous regressors passed as exog to fit(), and \(L\) is exog_lags.

Parameters:
k_ar_diff

Number of lagged-difference blocks \(\Delta y_{t-1}, \dots, \Delta y_{t-k}\) to include. 0 means no short-run dynamics — a pure error-correction equation. Defaults to 1.

coint_rank

Cointegration rank \(r\). Sets the shared inner dimension of \(\alpha\) and \(\beta\). Must be at least 1 and below \(K\). Defaults to 1.

deterministic

Deterministic-term code, following the convention of statsmodels.tsa.vector_ar.vecm. Single codes only:

  • "n" — no deterministic terms (default).

  • "co" — constant outside the cointegration relation.

  • "ci" — constant inside the cointegration relation.

  • "lo" — linear trend outside the cointegration relation.

  • "li" — linear trend inside the cointegration relation.

Compound codes (Johansen cases 4 and 5) are not supported.

priors

Optional mapping from parameter name to distribution spec. Keys recognised: "alpha", "beta", "Gamma", "Sigma", "B", "adstock_alpha", "saturation_lam". With adstock or saturation, "B" sets the prior on the total effects B_total (and on the free lags of other drivers). Each value is a dict of the form {"dist": "<DistName>", **kwargs} — for example {"dist": "Normal", "mu": 0.0, "sigma": 1.0}. Any parameter omitted from the dict falls back to a weakly-informative default chosen at fit time. None (the default) means “use defaults for everything”.

exog_lags

Number of past periods of each exog driver to include, \(L\). 0 (default) keeps the same period only. Use 1 or 2 when a driver acts with a delay, for example on monthly data where spend late in a month moves next month’s average. Lags of a flighted driver are highly correlated, so read the effect summed over lags (exog_irf(), granger_causality()) rather than each lag on its own.

adstock

Drivers whose effect carries over with geometric decay (adstock), given as exog column names or positions. For each, the lag-\(l\) coefficient is \(b \, w^l / \sum_{i=0}^{L_a} w^i\): B_total (\(b\), prior Normal(0, 1)) is the total effect on each series and adstock_alpha (\(w\), prior Beta(1, 1), flat) is one decay per driver, shared across series. B keeps its usual layout, so exog_irf(), forecasts and granger_causality() read it as before. Drivers not listed keep free coefficients on lags 0..exog_lags. None (default) means no adstock.

adstock_max_lag

Length of the adstock window, \(L_a\). Defaults to 8, which suits weekly data with decays up to about 0.7 (at 0.9, lag 8 still carries 43% of the same-week weight). The first max(exog_lags, adstock_max_lag) - k_ar_diff - 1 rows are dropped so every lag exists. Ignored without adstock.

saturation

Drivers whose effect flattens as spend grows (logistic saturation), given as exog column names or positions. Their exog columns must be raw, non-negative spend, not deviations from the average; other columns are unchanged. Each acts through \(b \, [f(a_t / s) - \bar f]\), with \(a_t\) the spend after adstock (same-week spend if not adstocked), \(s\) the in-sample maximum of spend, \(f(u) = \tanh(\lambda u / 2)\) and \(\bar f\) its in-sample mean. saturation_lam (\(\lambda\), prior Gamma(2, 0.3)) sets how fast it bends. B_total (prior Normal(0, 1)) is the total effect of one more unit at mean spend, the quantity the data pin down best, and B_saturation (\(b\), the effect at full saturation) is derived from it. The return on one more unit depends on the spend level: B, exog_irf() and granger_causality() give it at mean spend, exog_irf(at=...) at another level and saturation_curve() across levels. Forecasts use the exact curve. None (default) means no saturation.

contemporaneous

Same-week links between the brand metrics to estimate, as {effect: [causes]} with endog column names, for example {"brand_consideration": ["brand_awareness"]}. The drivers then act through the structural form \(A_0 \Delta y_t = \dots + B_s x_t\) with \(A_0 = I - L\) and \(L\) holding the links (A0_links, prior Normal(0, 0.5)). B, B_total and B_saturation stay reduced form, \(A_0^{-1} B_s\), so every other method reads them as before. B_structural holds the direct effects. \(\Sigma\) stays a full covariance: the links are identified only by excluded. Links must not form a cycle. Run granger_pretest() with the same arguments first. fit() runs the same instrument check (two-stage least squares with k_ar_diff + 1 lags in levels) and warns when a link has weak instruments (first-stage F below 10) or instruments that disagree (Sargan p below 0.05). same_week_links() reports both numbers. None (default) means no links.

excluded

Drivers with no direct same-week effect on a brand metric, as {effect: [drivers]} with endog and exog column names. Their entries of \(B_s\) are zero at every lag. Each effect in contemporaneous needs at least as many excluded drivers as causes. Can be used without contemporaneous to drop effects.

fading

Drivers whose effect may fade, given as exog column names or positions. Without it a week of spend moves the brand metrics, and through them sales, for good. With it each listed driver gets a share of its lift that drains away (fade_share, \(\phi\), prior Beta(1, 1)) and a half-life for that share in periods (fade_half_life, \(h\), prior LogNormal(log 52, 0.75)): the driver’s weekly contribution \(c_t\) to growth is joined by \(-\phi (1 - \delta) \sum_{k \ge 1} \delta^{k-1} c_{t-k}\) with \(\delta = 0.5^{1/h}\). A one-week pulse lifts the levels and only the share \(1 - \phi\) stays; stopping spend for good lets the metrics fall towards a lower level instead of drifting apart for ever. B, granger_causality() and saturation_curve() give the effect in the week it lands; exog_irf() and forecasts include the fade. Five years of weekly data tell a lasting effect from one with a half-life of a year or two only weakly, so read fade_share through its interval. None (default) means every effect lasts.

Raises:
ValueError

If k_ar_diff or exog_lags is negative, coint_rank is less than 1, deterministic is not one of the recognised codes, adstock_max_lag is below 1, or adstock or saturation is empty or has duplicates. At fit time, if contemporaneous or excluded names an unknown column, the links form a cycle or a link is not identified.

TypeError

If priors is not None and not a dict.

References

[1]

Cain, P. M. (2022). Modelling short- and long-term marketing effects in the consumer purchase journey. International Journal of Research in Marketing, 39(1), 96-116. https://doi.org/10.1016/j.ijresmar.2021.06.006

[2]

Juselius, K. (2006). The Cointegrated VAR Model: Methodology and Applications. Oxford University Press.

Examples

Construct a model and inspect its configuration:

>>> from bayesian_vecm import BayesianVECM
>>> model = BayesianVECM(k_ar_diff=2, coint_rank=1, deterministic="ci")
>>> model.k_ar_diff
2
>>> model.deterministic
'ci'

Fit, then forecast with the drivers at chosen values:

>>> model.fit(endog, exog=exog)
>>> fc = model.sample_posterior_predictive(52, exog_future=x_future)
fit(endog, *, exog=None, exog_coint=None, draws=1000, tune=1000, chains=4, target_accept=0.9, random_seed=None, progressbar=True, **sample_kwargs)[source]#

Fit the model to endog by running PyMC sampling.

Parameters:
endog

Endogenous time series of shape (T, K). Accepts anything bayesian_vecm._data.validate_endog() accepts — including objects with a .to_numpy() method, such as a pandas.DataFrame. Column labels (if present) are captured into self.variable_names_.

exog

Optional exogenous regressors, shape (T, m). These enter the short-run equation as \(\sum_{l=0}^{L} B_l X_{t-l}\) with \(L\) = exog_lags. The posterior B is (K, m * (L + 1)), lag-major, with a Normal(0, 1 / sqrt(L + 1)) prior on each entry. With exog_lags > k_ar_diff + 1 the first exog_lags - k_ar_diff - 1 rows are dropped. Pass None (default) to omit.

exog_coint

Optional exogenous variables inside the cointegrating relation, shape (T, m_c). Their columns are appended to \(y_{t-1}\) before building the cointegration term — the same mechanism used by deterministic="ci" / "li". Pass None (default) to omit.

draws, tune, chains, target_accept, random_seed, progressbar

Forwarded to pm.sample(). The defaults aim at “reasonable for a small VECM”: four chains of 1000 draws after 1000 tuning iterations, with a slightly cautious target_accept=0.9.

**sample_kwargs

Additional keyword arguments forwarded to pm.sample() — for example cores, init, or nuts_sampler.

Returns:
BayesianVECM

The fitted model (self), to support method chaining.

Raises:
ValueError

If endog fails validation, if exog / exog_coint have the wrong shape, or if priors is malformed.

Posterior of each same-week link in contemporaneous.

Parameters:
threshold

Evidence at or above this is reported as a link.

ci_prob

Probability mass of the equal-tailed interval.

Returns:
pandas.DataFrame

One row per link. Columns cause, effect, mean, lower, upper, evidence, link, first_stage_f and sargan_p. evidence is as in granger_causality(): for one coefficient, 1 - 2 * min(P(> 0), P(< 0)). The last two come from the instrument check at fit time. Below an F of 10 the link leans on its prior. A small Sargan p means at least one exclusion is wrong. Both are NaN if the check could not run.

Raises:
RuntimeError

If fit() has not been called.

ValueError

If the model has no contemporaneous links.

property idata#

Posterior record from the most recent fit.

Returns:
arviz.InferenceData

The full posterior trace, including constant_data with the raw endog and the design matrices.

Raises:
RuntimeError

If fit() has not been called.

summary(**summary_kwargs)[source]#

Return a tabular summary of the headline posterior parameters.

Thin wrapper around arviz.summary(). By default reports \(\alpha\), \(\beta\), \(\Sigma\), and — when k_ar_diff > 0 — \(\Gamma\). Pass var_names=... to override; any other arviz.summary keyword (hdi_prob, round_to, etc.) is forwarded through.

Returns:
pandas.DataFrame

One row per scalar parameter, columns mean, sd, hdi_3%, hdi_97%, ess_bulk, ess_tail, r_hat (defaults from ArviZ).

Raises:
RuntimeError

If fit() has not been called.

property fittedvalues#

Posterior in-sample fitted values of \(\Delta y\).

Computes \(\hat{\Delta y}_t = \alpha\beta^\top y_{t-1} + \Gamma\Delta x_t\) for every posterior draw.

Returns:
xarray.DataArray

Shape (chain, draw, time, variable). time is zero-indexed over the \(T_{\text{eff}}\) in-sample observations. Use .mean(("chain", "draw")) for the posterior-mean fitted values.

Raises:
RuntimeError

If fit() has not been called.

property resid#

Posterior in-sample residuals \(\Delta y - \hat{\Delta y}\).

Returns:
xarray.DataArray

Shape (chain, draw, time, variable). Use .mean(("chain", "draw")) for posterior-mean residuals.

Raises:
RuntimeError

If fit() has not been called.

property var_rep#

Posterior levels VAR(\(p\)) coefficient matrices.

Reconstructs \(A_1, \dots, A_p\) from the VECM posterior using the standard VECM-to-VAR(p) conversion (\(p = k_{\text{ar\_diff}} + 1\)).

Returns:
xarray.DataArray

Shape (chain, draw, lag, response_variable, shock_variable). lag runs from 1 to p.

Raises:
RuntimeError

If fit() has not been called.

test_normality()[source]#

Jarque-Bera normality test on posterior-mean residuals.

Tests each endogenous variable independently. H0: residuals are normally distributed.

Returns:
pandas.DataFrame

One row per variable, columns jb_stat and p_value.

Raises:
RuntimeError

If fit() has not been called.

test_whiteness(*, lags=10)[source]#

Ljung-Box whiteness test on posterior-mean residuals.

Tests each endogenous variable independently for autocorrelation up to lags periods. H0: no autocorrelation.

Parameters:
lags

Lag order for the portmanteau Q-statistic. Defaults to 10.

Returns:
pandas.DataFrame

One row per variable, columns lb_stat, p_value, lags.

Raises:
RuntimeError

If fit() has not been called.

ValueError

If lags < 1.

irf(steps, *, method='girf', order=None)[source]#

Compute posterior Impulse Response Functions for steps horizons.

Returns a posterior distribution over IRF paths — the response of each variable to a unit shock in each other variable, for every posterior draw.

Two identification schemes are available:

  • "girf" (default) — Generalised IRFs (Pesaran & Shin 1998). Order-invariant. The response to a shock in variable j equals the Cholesky IRF with j ordered first, so it is structural only if j leads the other variables within the period.

  • "cholesky" — Orthogonalised IRFs (Sims 1980). Requires a defensible recursive causal ordering among the variables: a shock to one variable moves the variables after it in the same period, and not the ones before it. Set the ordering with order.

Parameters:
steps

Number of periods ahead to compute IRFs. Horizons \(h = 0, 1, \dots, \text{steps}\) are returned, giving steps + 1 entries along the horizon dimension.

method

Identification scheme — "girf" or "cholesky".

order

Cholesky ordering, listing every endogenous variable once by name or column index. None uses the column order of endog. The output keeps the column order either way. Only valid with method="cholesky". Changing the column order of endog instead would also change the normalisation of \(\beta\).

Returns:
xarray.DataArray

Shape (chain, draw, horizon, response_variable, shock_variable). horizon runs from 0 (impact) to steps. Entry [..., h, i, j] is the response of variable \(i\) to a unit shock in variable \(j\) at horizon \(h\). response_variable and shock_variable coordinates are set when self.variable_names_ is available.

Raises:
RuntimeError

If fit() has not been called.

ValueError

If steps < 1, method is unrecognised, or order is invalid.

TypeError

If order is a string or holds entries that are not names or integers.

exog_irf(steps, *, at='mean')[source]#

Posterior response of the levels to a one-period rise in each exogenous driver.

Each exogenous variable is raised by one unit for one period, with every other input at its baseline. The path is \(\Phi_h B\) for \(h = 0, \dots, \text{steps}\). No identification scheme is needed: the driver is observed, so its impact is a column of \(B\).

Use the result to value a driver. With log-transformed endog, entry [..., h, i, j] is the log change in variable \(i\) at horizon \(h\) per unit of driver \(j\). The cumulative sum over horizon is the response to a rise held for every period. In a cointegrated system the path settles at \(C B\), so a one-period rise can move the levels for good.

With exog_lags = L the lag-\(l\) block \(B_l\) acts \(l\) periods after the rise, so the path is \(\sum_{l} \Phi_{h-l} B_l\) and settles at \(C \sum_l B_l\). The result has one column per driver, with all lags included.

Without saturation the model is linear in the drivers, so the result is the same at every spend level. A saturated driver’s return on one more unit depends on how much is already spent: the result is its slope at the level set by at, carried through the same lags. For a change larger than a few units, or to see the whole curve, use saturation_curve() or a forecast.

Only exog is covered. Variables passed as exog_coint enter the cointegrating relation and have no response here.

Parameters:
steps

Number of periods ahead. steps + 1 horizons are returned, from 0 (impact) to steps.

at

Spend level at which saturated drivers are valued. "mean" (default) is the in-sample mean, "recent" the mean of the last 13 periods, and a dict maps driver names (or positions) to levels in raw units, with the mean for any left out. Ignored without saturation.

Returns:
xarray.DataArray

Shape (chain, draw, horizon, response_variable, exog_variable). Coordinates are set when variable names are available.

Raises:
RuntimeError

If fit() has not been called.

ValueError

If steps < 1 or the model was fitted without exog.

saturation_curve(driver, levels, *, marginal=False)[source]#

Posterior response curve of a saturated driver.

The total effect on each series’ weekly growth of holding the driver at each spend level for good, against its in-sample average contribution. Adstock does not change a level held for ever. The effect then passes through the rest of the system as any other shift in growth would; use a forecast for its path in the levels.

Parameters:
driver

Name or position of a saturated driver.

levels

Spend levels in raw units.

marginal

Return the slope per unit at each level (the return on one more unit) instead of the effect.

Returns:
xarray.DataArray

Shape (chain, draw, level, response_variable).

Raises:
RuntimeError

If fit() has not been called.

ValueError

If driver is not saturated or a level is negative.

fevd(steps, *, method='girf', order=None)[source]#

Compute the posterior forecast error variance decomposition.

For each variable and horizon, the share of its forecast error variance that is due to shocks in each variable.

Parameters:
steps

Longest forecast horizon. Horizons 1, ..., steps are returned.

method

"girf" (default) does not depend on the column order. Rows are rescaled to sum to 1. "cholesky" uses the column order, the same as irf().

order

Cholesky ordering, as in irf(). Only valid with method="cholesky".

Returns:
xarray.DataArray

Shape (chain, draw, horizon, response_variable, shock_variable). Each row sums to 1 over shock_variable.

Raises:
RuntimeError

If fit() has not been called.

ValueError

If steps < 1, method is unrecognised, or order is invalid.

TypeError

If order is a string or holds entries that are not names or integers.

granger_causality(*, threshold=0.95, ci_prob=0.89)[source]#

Summarise the posterior evidence on what helps predict what.

Returns four tables: short-run Granger causality from \(\Gamma\), long-run links from \(\Pi = \alpha \beta^\top\), weak exogeneity from the rows of \(\alpha\), and exogenous drivers from \(B\). Print the result for a plain-English summary.

The evidence for each link is a number between 0 and 1: the highest credible level at which zero lies outside the posterior region. These are statements about prediction, not about cause.

Parameters:
threshold

Evidence at or above this counts as a link.

ci_prob

Probability mass of the equal-tailed interval around each effect.

Returns:
CausalityResult
Raises:
RuntimeError

If fit() has not been called.

ValueError

If threshold or ci_prob is not strictly between 0 and 1.

sample_posterior_predictive(steps, *, exog_future=None, random_seed=None)[source]#

Forecast steps periods ahead from the fitted posterior.

Rolls the VECM recursion forward in levels:

\[ \begin{align}\begin{aligned}\Delta y_{T+h} = \alpha \beta' y_{T+h-1} + \sum_{i=1}^{k} \Gamma_i \, \Delta y_{T+h-i} + \sum_{l=0}^{L} B_l X_{T+h-l} + d_{T+h} + \varepsilon_{T+h}, \quad \varepsilon_{T+h} \sim \mathcal{N}(0, \Sigma)\\y_{T+h} = y_{T+h-1} + \Delta y_{T+h}\end{aligned}\end{align} \]

for \(h = 1, \dots, \text{steps}\). \(d_{T+h}\) is the constant or trend set by deterministic, continued from the fit.

Parameters:
steps

Number of periods to forecast. Must be at least 1.

exog_future

Future values of the exogenous regressors, shape (steps, m). Required when the model was fitted with exog; ignored otherwise. Must have exactly steps rows and the same number of columns as the exog passed to fit(). With exog_lags the lags of the first steps are taken from the last rows of the exog passed to fit().

random_seed

Seed for the NumPy random generator used to draw innovations. Pass an integer for reproducible forecasts; None (the default) gives a fresh unseeded generator.

Returns:
xarray.DataTree

A DataTree whose posterior_predictive child node contains:

  • y — forecast levels, shape (chain, draw, steps, K).

  • delta_y — forecast first differences, same shape.

Both arrays carry a forecast_step coordinate running from 1 to steps, and a variable coordinate if self.variable_names_ is set.

Raises:
RuntimeError

If fit() has not been called.

ValueError

If steps is less than 1, or if the model was fitted with exog but exog_future is not provided (or has the wrong shape).

Warns:
UserWarning

If the model was fitted with exog_coint. The forecast drops the exog_coint rows of \(\beta\), so the error-correction term leaves those variables out.

class CausalityResult(short_run, long_run, weak_exogeneity, exog, threshold, ci_prob, gamma_prior)[source]#

Tables of posterior evidence on what helps predict what.

Printing the result gives a plain-English summary. Each attribute is a pandas.DataFrame for further work.

Attributes:
short_runpandas.DataFrame

One row per ordered pair of endogenous variables. Columns cause, effect, evidence, mean, lower, upper. The effect size is the sum of the \(\Gamma\) coefficients over lags. Empty when k_ar_diff = 0.

long_runpandas.DataFrame

Same columns. The effect size is the entry of \(\Pi\).

weak_exogeneitypandas.DataFrame

One row per endogenous variable. Columns variable, evidence and weakly_exogenous. evidence is the evidence that the variable adjusts.

exogpandas.DataFrame or None

Same columns as short_run, with exogenous variables as causes. With same-week links (contemporaneous) two more columns split the posterior mean: direct is the driver’s own effect and via_links the part passed on through the links. None when the model was fitted without exog.

thresholdfloat

Evidence at or above this is reported as a link.

ci_probfloat

Probability mass of the equal-tailed interval in lower/upper.

gamma_priorstr

Prior family used for \(\Gamma\).