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#
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 withloading = [1.0, 0.9, 0.8]andbetais built so thatbeta' @ loading = 0exactly.Awareness is weakly exogenous: its row of
alphais 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
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) * band the lagged onesshare * 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, soexog[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 withexog_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 deviationd, 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 withoutexog_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-formbisinv(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 isexp(organic_sales).False(default) leaves themNone.- 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.02for 2%). Defaults to0.0. Needstotal_sales=True.- sales_adstock
Geometric adstock decay of the short-term effects on total sales, for example
{"paid_search": 0.3}. Keys frombrand_spend,paid_searchandpaid_social; decays in[0, 1). Separate fromexog_adstock, which acts on the brand metrics.None(default) keeps every short-term effect in the same week. Needstotal_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. Needstotal_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. Needstotal_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_drifttimes that harmonic’s amplitude.0.0(default) keeps the pattern fixed. Must not be negative. Needstotal_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 shareexog_fade_shareof 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 withexog_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.5leaves half for good. Ignored withoutexog_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 afterexog_dark. A saturated channel’s raw spend is multiplied; a linear channel’s level1 + xis multiplied, so 0 gives-1as inexog_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),exogandtruth.
- Raises:
- ValueError
If
n_obsis less than 3, any starting level is not positive,exog_lag_shareis outside[0, 1],exog_unit_rootorexog_adstocknames an unknown driver, an adstock decay is outside[0, 1),exog_adstockorexog_saturationis combined withexog_lag_share,exog_saturationnames anything but a channel or a channel inexog_unit_root, a saturation value is not positive,spend_log_sdis not positive, orcontemporaneousnames an unknown series, links a series to itself or has a cycle,sales_noiseis negative,sales_adstockorsales_saturationnames an unknown driver or has an invalid value,paid_search_followsorseasonal_driftis negative, or any of these is set withouttotal_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_awarenessandbrand_consideration, weekly. Usenp.expfor original units.- exogpandas.DataFrame, shape (n_obs, 5)
brand_spend,pr_reach,sponsorship_reach,interest_rateandconsumer_confidence, as stationary deviations from their long-run averages. A driver named inexog_unit_rootis a random walk instead, starting near zero. A channel named inexog_saturationis 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).Noneotherwise.- sales_driverspandas.DataFrame or None
With
total_sales=True:paid_searchandpaid_social(raw spend, mean 1) andpromo(0 or 1). These drive total sales only.Noneotherwise.
- 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
BrandDataset.Shapes use
K = 3endogenous variables,r = 2cointegrating relations andm = 5exogenous variables. Row and column order followsBrandData.endogandBrandData.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 rblock 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 @ loadingis 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_shareis set. The long-run effect of a driver depends onb + b_lagonly.- differencedtuple of str
Drivers simulated as random walks (
exog_unit_root). For these,bandb_lagact 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\) isb_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 driverbandb_totalare 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.2means growth injraises growth iniby 0.2 in the same week. The identity unlesscontemporaneousis set.- b_structuralnp.ndarray, shape (K, m)
Direct same-week effects \(B_s\), before the links pass them on.
bisinv(a0) @ b_structural. Equal tobwithout links.- fade_half_lifenp.ndarray, shape (m,)
Half-life in weeks of the fading part of each driver’s effect, from
exog_fade.inffor drivers whose effect does not fade.- fade_sharefloat
Share of a faded driver’s effect that fades, from
exog_fade_share.0.0withoutexog_fade.- sales_partspandas.DataFrame or None
With
total_sales=True: each part of total sales in £ per week, columnsSALES_PART_NAMES. They sum toBrandData.sales["total_sales"].Noneotherwise.- 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".Noneotherwise.
- 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.
- property links#
Same-week links,
links[i, j]= effect of growth injoni.I - a0. Zero withoutcontemporaneous.
- 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
driveratlevel.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
driverheld atlevel.The slope of
response(). Constant for a linear driver. Returns shapelevel.shape + (K,).