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
exogtofit(), and \(L\) isexog_lags.- Parameters:
- k_ar_diff
Number of lagged-difference blocks \(\Delta y_{t-1}, \dots, \Delta y_{t-k}\) to include.
0means no short-run dynamics — a pure error-correction equation. Defaults to1.- coint_rank
Cointegration rank \(r\). Sets the shared inner dimension of \(\alpha\) and \(\beta\). Must be at least
1and below \(K\). Defaults to1.- 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". Withadstockorsaturation,"B"sets the prior on the total effectsB_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 atfittime.None(the default) means “use defaults for everything”.- exog_lags
Number of past periods of each
exogdriver to include, \(L\).0(default) keeps the same period only. Use1or2when 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
exogcolumn names or positions. For each, the lag-\(l\) coefficient is \(b \, w^l / \sum_{i=0}^{L_a} w^i\):B_total(\(b\), priorNormal(0, 1)) is the total effect on each series andadstock_alpha(\(w\), priorBeta(1, 1), flat) is one decay per driver, shared across series.Bkeeps its usual layout, soexog_irf(), forecasts andgranger_causality()read it as before. Drivers not listed keep free coefficients on lags0..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 firstmax(exog_lags, adstock_max_lag) - k_ar_diff - 1rows are dropped so every lag exists. Ignored withoutadstock.- saturation
Drivers whose effect flattens as spend grows (logistic saturation), given as
exogcolumn names or positions. Theirexogcolumns 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\), priorGamma(2, 0.3)) sets how fast it bends.B_total(priorNormal(0, 1)) is the total effect of one more unit at mean spend, the quantity the data pin down best, andB_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()andgranger_causality()give it at mean spend,exog_irf(at=...)at another level andsaturation_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]}withendogcolumn 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, priorNormal(0, 0.5)).B,B_totalandB_saturationstay reduced form, \(A_0^{-1} B_s\), so every other method reads them as before.B_structuralholds the direct effects. \(\Sigma\) stays a full covariance: the links are identified only byexcluded. Links must not form a cycle. Rungranger_pretest()with the same arguments first.fit()runs the same instrument check (two-stage least squares withk_ar_diff + 1lags 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]}withendogandexogcolumn names. Their entries of \(B_s\) are zero at every lag. Each effect incontemporaneousneeds at least as many excluded drivers as causes. Can be used withoutcontemporaneousto drop effects.- fading
Drivers whose effect may fade, given as
exogcolumn 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\), priorBeta(1, 1)) and a half-life for that share in periods (fade_half_life, \(h\), priorLogNormal(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()andsaturation_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 readfade_sharethrough its interval.None(default) means every effect lasts.
- Raises:
- ValueError
If
k_ar_difforexog_lagsis negative,coint_rankis less than1,deterministicis not one of the recognised codes,adstock_max_lagis below1, oradstockorsaturationis empty or has duplicates. At fit time, ifcontemporaneousorexcludednames an unknown column, the links form a cycle or a link is not identified.- TypeError
If
priorsis notNoneand not adict.
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
endogby running PyMC sampling.- Parameters:
- endog
Endogenous time series of shape
(T, K). Accepts anythingbayesian_vecm._data.validate_endog()accepts — including objects with a.to_numpy()method, such as apandas.DataFrame. Column labels (if present) are captured intoself.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 posteriorBis(K, m * (L + 1)), lag-major, with aNormal(0, 1 / sqrt(L + 1))prior on each entry. Withexog_lags > k_ar_diff + 1the firstexog_lags - k_ar_diff - 1rows are dropped. PassNone(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 bydeterministic="ci"/"li". PassNone(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 cautioustarget_accept=0.9.- **sample_kwargs
Additional keyword arguments forwarded to
pm.sample()— for examplecores,init, ornuts_sampler.
- Returns:
- BayesianVECM
The fitted model (
self), to support method chaining.
- Raises:
- ValueError
If
endogfails validation, ifexog/exog_cointhave the wrong shape, or ifpriorsis malformed.
- same_week_links(*, threshold=0.95, ci_prob=0.89)[source]#
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_fandsargan_p.evidenceis as ingranger_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 areNaNif the check could not run.
- Raises:
- RuntimeError
If
fit()has not been called.- ValueError
If the model has no
contemporaneouslinks.
- property idata#
Posterior record from the most recent
fit.- Returns:
- arviz.InferenceData
The full posterior trace, including
constant_datawith the rawendogand 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 — whenk_ar_diff > 0— \(\Gamma\). Passvar_names=...to override; any otherarviz.summarykeyword (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).timeis 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).lagruns from1top.
- 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_statandp_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
lagsperiods. 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 withorder.
- Parameters:
- steps
Number of periods ahead to compute IRFs. Horizons \(h = 0, 1, \dots, \text{steps}\) are returned, giving
steps + 1entries along thehorizondimension.- method
Identification scheme —
"girf"or"cholesky".- order
Cholesky ordering, listing every endogenous variable once by name or column index.
Noneuses the column order ofendog. The output keeps the column order either way. Only valid withmethod="cholesky". Changing the column order ofendoginstead would also change the normalisation of \(\beta\).
- Returns:
- xarray.DataArray
Shape
(chain, draw, horizon, response_variable, shock_variable).horizonruns from0(impact) tosteps. Entry[..., h, i, j]is the response of variable \(i\) to a unit shock in variable \(j\) at horizon \(h\).response_variableandshock_variablecoordinates are set whenself.variable_names_is available.
- Raises:
- RuntimeError
If
fit()has not been called.- ValueError
If
steps < 1,methodis unrecognised, ororderis invalid.- TypeError
If
orderis 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 overhorizonis 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 = Lthe 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
saturationthe 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 byat, carried through the same lags. For a change larger than a few units, or to see the whole curve, usesaturation_curve()or a forecast.Only
exogis covered. Variables passed asexog_cointenter the cointegrating relation and have no response here.- Parameters:
- steps
Number of periods ahead.
steps + 1horizons are returned, from0(impact) tosteps.- 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 withoutsaturation.
- 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 < 1or the model was fitted withoutexog.
- 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
driveris 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:
- Returns:
- xarray.DataArray
Shape
(chain, draw, horizon, response_variable, shock_variable). Each row sums to 1 overshock_variable.
- Raises:
- RuntimeError
If
fit()has not been called.- ValueError
If
steps < 1,methodis unrecognised, ororderis invalid.- TypeError
If
orderis 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
thresholdorci_probis not strictly between 0 and 1.
- sample_posterior_predictive(steps, *, exog_future=None, random_seed=None)[source]#
Forecast
stepsperiods 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 withexog; ignored otherwise. Must have exactlystepsrows and the same number of columns as theexogpassed tofit(). Withexog_lagsthe lags of the first steps are taken from the last rows of theexogpassed tofit().- 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_predictivechild node contains:y— forecast levels, shape(chain, draw, steps, K).delta_y— forecast first differences, same shape.
Both arrays carry a
forecast_stepcoordinate running from1tosteps, and avariablecoordinate ifself.variable_names_is set.
- Raises:
- RuntimeError
If
fit()has not been called.- ValueError
If
stepsis less than1, or if the model was fitted withexogbutexog_futureis not provided (or has the wrong shape).
- Warns:
- UserWarning
If the model was fitted with
exog_coint. The forecast drops theexog_cointrows 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.DataFramefor 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 whenk_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,evidenceandweakly_exogenous.evidenceis 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:directis the driver’s own effect andvia_linksthe part passed on through the links.Nonewhen the model was fitted withoutexog.- 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\).