Simulated brand data#

Synthetic brand-marketing data with known VECM parameters.

One data-generating process (DGP), shared by the practitioner notebook, the tests and any demo: three cointegrated brand series driven by five stationary exogenous variables.

from bayesian_vecm import simulate_brand_data

data = simulate_brand_data()
data.endog   # log levels: organic_sales, brand_awareness, brand_consideration
data.exog    # brand_spend, pr_reach, sponsorship_reach, interest_rate, ...
data.truth   # the parameters that generated them

The process#

\[\Delta y_t = c + \alpha \beta' y_{t-1} + \Gamma \Delta y_{t-1} + B x_t + \varepsilon_t, \qquad \varepsilon_t \sim N(0, \Sigma).\]

The causal story is a chain, and it is the ground truth for any “what drives what” diagnostic run on this data:

marketing channels -> awareness -> consideration -> sales

  • One common trend (K = 3, cointegration rank 2). The series load on it with loading = [1.0, 0.9, 0.8] and beta is built so that beta' @ loading = 0 exactly.

  • Awareness is weakly exogenous: its row of alpha is zero, so it is the only series whose shocks last for ever. Consideration adjusts towards awareness, and sales adjust towards consideration.

  • Short-run dynamics (gamma) follow the same chain: lagged awareness growth helps predict consideration, lagged consideration growth helps predict sales.

  • Exogenous effects (b): the three marketing channels act on awareness only (brand_spend > pr_reach > sponsorship_reach); the two macro variables act on consideration only.

Trending drivers. exog_unit_root=("interest_rate",) makes the named drivers random walks (I(1)). Their effect then runs through the change, b times \(\Delta x_t\), while exog holds the level. Fit them as exog.diff(): a trending level cannot explain stationary growth, so a levels fit gives a meaningless coefficient. The default keeps all five drivers stationary.

Saturating channels. exog_saturation={"brand_spend": 5.0} returns the named channels as raw, non-negative spend (mean 1, log-normal) and makes their effect bend: the driver acts through \(b_s \, [f(a_t / s) - \bar f]\), where \(a_t\) is spend after any adstock, \(s\) is the in-sample maximum of raw spend and \(f\) is logistic saturation with the given \(\lambda\). \(b_s\) is set so the marginal effect of one unit at mean spend equals the linear b, which keeps a linear fit’s local target unchanged.

The constant c gives the system an upward drift (sales double over 260 weeks on average) and fixes the level of the two cointegrating relations. It is an unrestricted constant, so deterministic="co" is the matching specification when fitting.

Same-week links. contemporaneous={"brand_consideration": {"brand_awareness": 0.2}} adds a same-week effect of awareness growth on consideration growth. The drivers act through the structural form \(A_0 \Delta y_t = \dots + B_s x_t\), so the reduced form has \(B = A_0^{-1} B_s\): the channels now reach consideration in the same week through awareness. \(\alpha\), \(\Gamma\), \(\Sigma\) and the constant are reduced-form and unchanged. The default has no links.

Total sales. total_sales=True adds the series an analyst actually sees: weekly sales in £ that add up, week by week, as

\[S_t = \underbrace{e^{y_{1t}}}_{\text{base}} + \text{brand}_t + \text{search}_t + \text{social}_t + \text{promo}_t + \text{season}_t + u_t .\]

The base is exp(organic_sales), the brand system above. On top of it sit short-term effects that the brand system never sees: a same-week hit from brand spend (centred on its average), two performance channels paid_search and paid_social (raw spend with mean 1, no effect on the brand metrics), a promotion flag on about 8% of weeks, annual seasonality, and weekly noise \(u_t\) with standard deviation sales_noise times the reference level. By default every short-term effect is linear and in the same week, which a UCM with regressors can fit exactly. sales_adstock and sales_saturation add geometric carryover and logistic saturation to them. paid_search_follows makes paid search spend rise and fall with demand: its log spend gets a term in the standardised four-week growth of consideration, as when search volume (and so spend) goes up with interest in the brand. Sizes are set against a reference level of 1.44 * start_levels[0], the average of a level that doubles. The extra series use their own random numbers, so endog, exog and truth are unchanged by the option.

simulate_brand_data(n_obs=260, *, seed=14, start_levels=(1000.0, 20.0, 10.0), exog_lag_share=0.0, exog_unit_root=(), exog_adstock=None, exog_saturation=None, spend_log_sd=0.3, contemporaneous=None, total_sales=False, sales_noise=0.0, sales_adstock=None, sales_saturation=None, paid_search_follows=0.0, seasonal_drift=0.0, exog_fade=None, exog_fade_share=1.0, exog_dark=None, exog_plan=None)[source]#

Simulate weekly brand data from a VECM with known parameters.

Parameters:
n_obs

Number of weekly observations. Defaults to 260 (five years).

seed

Seed for the random number generator. The same seed always gives the same data.

start_levels

Starting values of sales, awareness and consideration in original units (not logs). Awareness and consideration are percentages; start them low enough to leave room to grow.

exog_lag_share

Share of each exogenous effect that arrives one week late, between 0 and 1. 0 (default) puts the whole effect in the same week. The same-week coefficients become (1 - share) * b and the lagged ones share * b, so the long-run effect of each driver is unchanged.

exog_unit_root

Names of drivers to simulate as random walks (I(1)), for example ("interest_rate",). Their weekly changes have the same innovations as the stationary version, and their effect acts through the change, so exog[name].diff() is the right regressor. Empty (default) keeps every driver stationary.

exog_adstock

Geometric adstock decay per driver, for example {"brand_spend": 0.5}. The driver acts through \(a_t = (1 - w) x_t + w a_{t-1}\), so its effect at lag \(l\) is \(b (1 - w) w^l\) and the total effect is unchanged. Decays must be in [0, 1). Cannot be combined with exog_lag_share. None (default) means no carryover.

exog_saturation

Logistic saturation \(\lambda\) per marketing channel, for example {"brand_spend": 5.0}. The channel is returned as raw spend, exp(d - spend_log_sd**2 / 2) for the stationary deviation d, so its mean is 1. It acts through \(b_s [f(a_t / s) - \bar f]\) after any adstock, with \(s\) the in-sample maximum of spend. \(b_s\) is set so one more unit at mean spend has the linear effect. Only the three channels can saturate. None (default) keeps every driver linear.

spend_log_sd

Standard deviation of log spend for saturated channels. Defaults to 0.30 (spend mostly between half and twice its mean). Larger values spread spend over more of the curve. Ignored without exog_saturation.

contemporaneous

Same-week links between the brand metrics, as {effect: {cause: coefficient}}. For example {"brand_consideration": {"brand_awareness": 0.2}} makes 1% more awareness growth add 0.2% to consideration growth in the same week. The links must not form a cycle. Every driver effect at every lag passes through them: the reduced-form b is inv(a0) @ b_structural. None (default) means no links.

total_sales

Also return total sales in £ (sales), the drivers that act on it only (sales_drivers) and its parts (truth.sales_parts). The base is exp(organic_sales). False (default) leaves them None.

sales_noise

Standard deviation of the weekly noise in total sales that is not part of the brand system, as a share of the reference level (for example 0.02 for 2%). Defaults to 0.0. Needs total_sales=True.

sales_adstock

Geometric adstock decay of the short-term effects on total sales, for example {"paid_search": 0.3}. Keys from brand_spend, paid_search and paid_social; decays in [0, 1). Separate from exog_adstock, which acts on the brand metrics. None (default) keeps every short-term effect in the same week. Needs total_sales=True.

sales_saturation

Logistic saturation \(\lambda\) of the performance channels’ effect on total sales, for example {"paid_search": 3.0}. The coefficient is set so the effect at mean spend is unchanged. None (default) keeps them linear. Needs total_sales=True.

paid_search_follows

How strongly paid search spend follows demand. Log spend gets paid_search_follows * z_t, where \(z_t\) is the four-week growth in log consideration, standardised. Spend is then rescaled to mean 1. The other paid channel is unchanged. 0.0 (default) keeps search spend independent of the brand. Must not be negative. Needs total_sales=True.

seasonal_drift

Lets the seasonal pattern in total sales change from year to year. The sine and cosine weights of each harmonic follow random walks whose weekly steps have standard deviation seasonal_drift times that harmonic’s amplitude. 0.0 (default) keeps the pattern fixed. Must not be negative. Needs total_sales=True.

exog_fade

Half-life in weeks of the effect of a driver that fades, for example {"brand_spend": 52.0}. Without it a week of spend moves the brand metrics for good. With it the share exog_fade_share of the lift decays at weekly rate \(\delta = 0.5^{1/h}\): the driver’s contribution \(c_t\) to growth becomes \(c_t - \phi (1 - \delta) S_t\) with \(S_t = \sum_{k \ge 1} \delta^{k-1} c_{t-k}\). A campaign then lifts the metrics and the lift drains away, and stopping spend for good lets them fall towards a lower level. None (default) keeps every effect permanent. Cannot be combined with exog_lag_share.

exog_fade_share

Share \(\phi\) of a faded driver’s effect that fades, in (0, 1]. 1.0 (default) fades all of it; 0.5 leaves half for good. Ignored without exog_fade.

exog_dark

Weeks when a channel is switched off, as {name: (start, length)}, for example {"brand_spend": (130, 26)} for half a year off from week 130. A saturated channel’s raw spend is set to 0. A linear channel is a deviation from an average of one unit, so off is a deviation of -1. None (default) keeps every channel on.

exog_plan

Weekly multiplier of a channel’s spend, as {name: array} with one non-negative value per week. For example a value of 2 for 26 weeks a year and 0 for the rest runs the same budget in pulses. Applied after exog_dark. A saturated channel’s raw spend is multiplied; a linear channel’s level 1 + x is multiplied, so 0 gives -1 as in exog_dark. A saturated channel keeps the curve it would have had without the plan: its scale is the in-sample maximum before the plan. None (default) leaves spend as drawn.

Returns:
BrandData

endog (log levels), exog and truth.

Raises:
ValueError

If n_obs is less than 3, any starting level is not positive, exog_lag_share is outside [0, 1], exog_unit_root or exog_adstock names an unknown driver, an adstock decay is outside [0, 1), exog_adstock or exog_saturation is combined with exog_lag_share, exog_saturation names anything but a channel or a channel in exog_unit_root, a saturation value is not positive, spend_log_sd is not positive, or contemporaneous names an unknown series, links a series to itself or has a cycle, sales_noise is negative, sales_adstock or sales_saturation names an unknown driver or has an invalid value, paid_search_follows or seasonal_drift is negative, or any of these is set without total_sales.

class BrandData(endog, exog, truth, sales=None, sales_drivers=None)[source]#

Simulated brand data and the parameters behind it.

Attributes:
endogpandas.DataFrame, shape (n_obs, 3)

Log levels of organic_sales, brand_awareness and brand_consideration, weekly. Use np.exp for original units.

exogpandas.DataFrame, shape (n_obs, 5)

brand_spend, pr_reach, sponsorship_reach, interest_rate and consumer_confidence, as stationary deviations from their long-run averages. A driver named in exog_unit_root is a random walk instead, starting near zero. A channel named in exog_saturation is raw, non-negative spend with mean 1.

truthBrandTruth

The generating parameters.

salespandas.DataFrame or None

With total_sales=True: one column, total_sales, weekly sales in £ (not logs). None otherwise.

sales_driverspandas.DataFrame or None

With total_sales=True: paid_search and paid_social (raw spend, mean 1) and promo (0 or 1). These drive total sales only. None otherwise.

class BrandTruth(alpha, beta, gamma, b, sigma, const, loading, growth, b_lag, differenced=(), adstock=<factory>, saturation=<factory>, spend_scale=<factory>, b_saturation=<factory>, saturation_mean=<factory>, a0=<factory>, b_structural=<factory>, sales_parts=None, sales_short_term=None, fade_half_life=<factory>, fade_share=0.0)[source]#

The parameters that generated a BrandData set.

Shapes use K = 3 endogenous variables, r = 2 cointegrating relations and m = 5 exogenous variables. Row and column order follows BrandData.endog and BrandData.exog.

Attributes:
alphanp.ndarray, shape (K, r)

Adjustment speeds. The awareness row is zero (weakly exogenous).

betanp.ndarray, shape (K, r)

Cointegrating vectors, top r x r block the identity.

gammanp.ndarray, shape (K, K)

Coefficients on \(\Delta y_{t-1}\).

bnp.ndarray, shape (K, m)

Coefficients on the same-period exogenous variables. With adstock this is the same-week share (1 - w) * b_total.

sigmanp.ndarray, shape (K, K)

Innovation covariance.

constnp.ndarray, shape (K,)

Unrestricted constant, what deterministic="co" estimates. Depends on the starting levels.

loadingnp.ndarray, shape (K,)

How each series loads on the common trend. beta.T @ loading is zero.

growthnp.ndarray, shape (K,)

Expected log growth per period of each series.

b_lagnp.ndarray, shape (K, m)

Coefficients on the exogenous variables one period back. Zero unless exog_lag_share is set. The long-run effect of a driver depends on b + b_lag only.

differencedtuple of str

Drivers simulated as random walks (exog_unit_root). For these, b and b_lag act on the change \(\Delta x_t\), not the level. Empty by default.

adstocknp.ndarray, shape (m,)

Geometric adstock decay \(w\) of each driver (exog_adstock). The effect at lag \(l\) is b_total * (1 - w) * w**l. Zero (no carryover) by default.

saturationnp.ndarray, shape (m,)

Logistic saturation \(\lambda\) of each driver (exog_saturation). Zero (linear) by default. For a saturated driver b and b_total are the marginal effects of one unit at mean spend (1.0).

spend_scalenp.ndarray, shape (m,)

In-sample maximum of raw spend for saturated drivers, the scale \(s\) in \(f(a_t / s)\). One for the others.

b_saturationnp.ndarray, shape (K, m)

Coefficient on the saturated, centred regressor \(f(a_t / s) - \bar f\): the effect at full saturation. Zero for linear drivers.

saturation_meannp.ndarray, shape (m,)

In-sample mean \(\bar f\) of the saturated regressor. Zero for linear drivers.

a0np.ndarray, shape (K, K)

Same-week structure \(A_0\): ones on the diagonal and minus each same-week link off it, so a0[i, j] = -0.2 means growth in j raises growth in i by 0.2 in the same week. The identity unless contemporaneous is set.

b_structuralnp.ndarray, shape (K, m)

Direct same-week effects \(B_s\), before the links pass them on. b is inv(a0) @ b_structural. Equal to b without links.

fade_half_lifenp.ndarray, shape (m,)

Half-life in weeks of the fading part of each driver’s effect, from exog_fade. inf for drivers whose effect does not fade.

fade_sharefloat

Share of a faded driver’s effect that fades, from exog_fade_share. 0.0 without exog_fade.

sales_partspandas.DataFrame or None

With total_sales=True: each part of total sales in £ per week, columns SALES_PART_NAMES. They sum to BrandData.sales["total_sales"]. None otherwise.

sales_short_termdict or None

With total_sales=True: the short-term settings, keys "reference" (£), "adstock", "saturation", "spend_scale", "coef" (£ per unit of the transformed driver), "paid_search_follows" and "seasonal_drift". None otherwise.

property fade_decay#

Weekly decay of the fading part of each driver’s effect.

0.5 ** (1 / half_life); 1 for drivers whose effect does not fade.

Same-week links, links[i, j] = effect of growth in j on i.

I - a0. Zero without contemporaneous.

property b_total#

Total (long-run summed) effect of each driver, shape (K, m).

For a saturated driver this is the marginal effect of one unit at mean spend.

response(driver, level)[source]#

Total effect on each series’ growth of holding driver at level.

Relative to the driver’s in-sample average contribution, so a linear driver held at 0 (its average) gives zero. Adstock does not change a level held for ever.

Returns shape level.shape + (K,).

marginal_effect(driver, level)[source]#

Total effect of one more unit of driver held at level.

The slope of response(). Constant for a linear driver. Returns shape level.shape + (K,).