Data generating process¶
Synthetic demand, spend and sales simulation. Used internally by the diagnostics and the report, and exposed for anyone building their own simulation loop.
simulate_demand ¶
simulate_demand(
n_obs: int = 104,
process: str = "white_noise",
seed: int = 0,
ar_coef: float = 0.8,
season_period: float = 52.0,
season_weight: float = 0.7,
trend_drift: float = 0.15,
) -> np.ndarray
Generate a latent demand series, standardised to mean 0 / sd 1.
Standardisation is deliberate: it makes demand_coef mean the same thing
across processes, so comparing a white-noise world against a seasonal one
compares the shape of demand rather than accidentally comparing its
amplitude.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_obs
|
int
|
Number of observations (weeks). |
104
|
process
|
str
|
One of DEMAND_PROCESSES:
The distinction matters: BudgetPhaser preserves monthly totals and moves spend only within a month, so it can only attack spend-demand coupling that lives inside that window. A white-noise-only study would overstate how much phasing fixes bias. |
'white_noise'
|
seed
|
int
|
Random seed. |
0
|
ar_coef
|
float
|
AR(1) coefficient, used by "ar1" and "seasonal_ar1". |
0.8
|
season_period
|
float
|
Period of the seasonal component, in observations (52 = annual weekly). |
52.0
|
season_weight
|
float
|
Weight on the seasonal component in "seasonal_ar1", in [0, 1]. |
0.7
|
trend_drift
|
float
|
Per-step drift for "trend", in units of the step innovation's own std (each step is trend_drift + N(0, 1)). 0 gives a pure driftless random walk; larger magnitudes give a more visibly directional path. Sign sets direction -- positive for growth, negative for decline. |
0.15
|
Returns:
| Type | Description |
|---|---|
np.ndarray of length n_obs, standardised to sample mean 0 and sd 1.
|
|
Source code in src/how_wrong_is_your_mmm/_dgp.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | |
simulate_demand_proxy ¶
simulate_demand_proxy(
demand: ndarray | Series,
quality: float = 1.0,
seed: int = 0,
) -> np.ndarray
Measurement-error proxy for a true demand series.
A practitioner never has the true demand series that simulate_sales's
demand/demand_coef (or CollinearityDiagnostic/BudgetPhaser's own
demand/demand_coef) bias sales toward -- what they have, at best, is
a proxy: a category (not brand) search-trend index, a seasonality index,
or a sales baseline from an existing model. This models the classic
measurement-error case: the truth plus noise, scaled so the resulting
series correlates with the truth at exactly quality in expectation.
Assumption stated once, and it is a real one: the proxy is treated as exogenous to the advertiser's own marketing. A brand-search series would not be -- it is partly caused by the very channel being measured, and controlling for it would absorb the effect under estimation. Category- level demand indices are the intended case.
For a STRUCTURAL proxy instead -- e.g. a category index that tracks only the seasonal cycle and misses idiosyncratic shocks entirely -- there is no separate function: just call simulate_demand with a different process than the one actually driving sales (see notebooks/07 section 6's seasonal_proxy). That is a mismatched generative process, not measurement error, so it does not fit this function's quality dial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
demand
|
ndarray | Series
|
The true demand series to build a proxy for -- typically what was
passed as |
required |
quality
|
float
|
Target correlation with the truth, in (0, 1]. 1.0 (default) returns
the series standardised but otherwise unchanged. There is no
realistic default -- 0.9 is already an unusually good real-world
proxy (see notebooks/07 section 6's sweep), so pick a value you can
defend for your own data source rather than relying on this one.
A given noise draw's REALISED correlation with the truth is close
to but not exactly |
1.0
|
seed
|
int
|
Random seed for the noise draw, drawn from a stream (_PROXY_STREAM) kept separate from every other seeded draw in this module -- see _PLANNING_STREAM's docstring note for why that separation matters. |
0
|
Returns:
| Type | Description |
|---|---|
np.ndarray, standardised to mean 0 / sd 1, same length as `demand`.
|
|
Source code in src/how_wrong_is_your_mmm/_dgp.py
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
simulate_spend ¶
simulate_spend(
n_obs: int = 104,
correlation: float = 0.7,
channels: list[str] | None = None,
seed: int = 0,
start_date: str | None = None,
demand: ndarray | Series | None = None,
demand_share: float = 1.0,
return_demand: bool = False,
) -> pd.DataFrame | tuple[pd.DataFrame, pd.Series]
Generate synthetic correlated spend for N channels via a latent demand signal.
All channels track the same underlying demand index with independent noise.
The noise level is set so that all pairwise correlations equal correlation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_obs
|
int
|
Number of observations (weeks). |
104
|
correlation
|
float
|
Target Pearson correlation between any pair of channels. |
0.7
|
channels
|
list[str] | None
|
List of channel names. Defaults to ["tv", "meta", "search"]. |
None
|
seed
|
int
|
Random seed for reproducibility. |
0
|
start_date
|
str | None
|
If provided (e.g. "2023-01-02"), the DataFrame will have a weekly DatetimeIndex anchored on Mondays starting from this date. Required when using the output with BudgetPhaser. |
None
|
demand
|
ndarray | Series | None
|
Optional externally supplied latent demand series of length n_obs, e.g. from simulate_demand. Use this to pair one demand series with several spend frames -- notably a plan and its phased version, which BudgetPhaser produces and this function never sees. The internal draw still happens and is discarded, so supplying the series this function would have drawn anyway reproduces its output exactly. |
None
|
demand_share
|
float
|
Share of the channels' common variance attributable to demand, in [0, 1]. The remainder comes from an independent "planning factor" that correlates the channels but never enters sales. This separates two things the DGP previously conflated. At the default 1.0 every bit of channel-channel correlation comes from demand, which forces corr(spend_c, demand) = sqrt(correlation) -- the maximal-bias case. Lower it to represent the common real situation where channels move together because one planning cycle sets both budgets, and neither closely tracks demand. Pairwise channel correlation stays exactly |
1.0
|
return_demand
|
bool
|
If True, return (spend_df, demand_series) instead of just spend_df. |
False
|
Returns:
| Type | Description |
|---|---|
pd.DataFrame with one column per channel. If start_date is provided,
|
|
the index is a weekly DatetimeIndex; otherwise it is the default integer index.
|
|
If return_demand is True, returns (spend_df, demand_series) instead.
|
|
Source code in src/how_wrong_is_your_mmm/_dgp.py
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 | |
link_demand_to_spend ¶
link_demand_to_spend(
spend_df: DataFrame,
demand_spend_corr: float = DEFAULT_DEMAND_SPEND_CORR,
process: str = "trend",
seed: int = 0,
**process_kwargs: float,
) -> LinkedDemand
Build a latent demand series that the supplied spend tracks.
simulate_spend runs demand -> spend. A real client's spend already
exists, so this runs the other way: it builds a demand series that the
supplied spend is correlated with at demand_spend_corr. Without this
step a demand series drawn independently of the spend has no link to
it, and the omitted-variable bias the diagnostics measure is chance
correlation.
Construction:
- f = the spend's common factor: each channel standardised, averaged across channels, then standardised again.
- u = simulate_demand(process=process, seed=seed), with the part explained by f regressed out and the rest standardised.
- demand = alpha * f + sqrt(1 - alpha^2) * u, with alpha = demand_spend_corr / mean_c corr(f, spend_c).
The linked part of demand takes the shape of the spend itself.
process shapes the unlinked remainder, a share 1 - alpha^2 of
demand's variance. At the default 0.65 and a pairwise channel
correlation of 0.7 that is about 45%.
alpha is capped at 1. The mean of corr(f, spend_c) is sqrt((1 + (n - 1) * r) / n) for n channels with mean pairwise correlation r, so a request above that cannot be met. Then demand is f itself and a warning says so.
For comparison, simulate_spend's demand_share gives
corr(spend_c, demand) = sqrt(demand_share * correlation).
Call this on UNPHASED spend and hold the result fixed. Demand is exogenous to any phasing plan: rebuilding it from phased spend would let the plan move demand, which defeats the comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spend_df
|
DataFrame
|
Weekly spend, one column per channel. At least 3 rows. |
required |
demand_spend_corr
|
float
|
Target corr(spend_c, demand), averaged over channels, in [0, 1]. Default 0.65. Spend data cannot reveal the true value, so treat it as an assumption to state. Bias grows steeply with it. |
DEFAULT_DEMAND_SPEND_CORR
|
process
|
str
|
One of DEMAND_PROCESSES, for the unlinked part of demand. Default "trend". |
'trend'
|
seed
|
int
|
Seed for the unlinked part. |
0
|
**process_kwargs
|
float
|
Forwarded to simulate_demand (ar_coef, season_period, season_weight, trend_drift). |
{}
|
Returns:
| Type | Description |
|---|---|
LinkedDemand. `demand` is standardised to mean 0 / sd 1.
|
|
Source code in src/how_wrong_is_your_mmm/_dgp.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | |
simulate_sales ¶
simulate_sales(
spend_df: DataFrame,
true_marginal_returns: dict[str, float] | None = None,
base_sales: float = 1000.0,
revenue_noise_std: float = 26000.0,
seed: int = 0,
true_elasticities: dict[str, float] | None = None,
demand: ndarray | Series | None = None,
demand_coef: float = 0.0,
saturation: dict[str, float] | float | None = None,
adstock: dict[str, float] | float | None = None,
reference_spend: dict[str, float] | None = None,
) -> pd.Series
Create a synthetic sales column from a spend DataFrame.
Applies known marginal returns to the spend columns and adds noise. Works identically whether spend_df is synthetic or real.
Model: sales = base + sum(beta[c] * spend[c] for c in channels) + noise
Each beta[c] here is a marginal return (a.k.a. mROAS): £ of incremental sales per £ of spend on channel c. Because the DGP is linear in raw £ spend (no log-log transform), this is NOT an elasticity in the economic sense (%-response to %-spend) -- calling it that overstates how "typical" the numbers look to an MMM practitioner, and read as an ROI it makes even a healthy true effect look catastrophic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spend_df
|
DataFrame
|
DataFrame with one column per channel. Can be synthetic or real. |
required |
true_marginal_returns
|
dict[str, float] | None
|
Dict mapping channel name to true marginal return (£ revenue per £ spend). Defaults to {"tv": 0.5, "meta": 1.0, "search": 1.5}. All columns in spend_df must have an entry. |
None
|
base_sales
|
float
|
Base sales intercept. |
1000.0
|
revenue_noise_std
|
float
|
Standard deviation of sales noise. |
26000.0
|
seed
|
int
|
Random seed for the noise draw. |
0
|
true_elasticities
|
dict[str, float] | None
|
Deprecated alias for |
None
|
demand
|
ndarray | Series | None
|
Optional latent demand series contributing to sales. Because spend
follows demand in this DGP, a model fitted WITHOUT this term is
misspecified and its channel coefficients carry omitted-variable bias.
Fit with it (see fit_ols's |
None
|
demand_coef
|
float
|
Coefficient on |
0.0
|
saturation
|
dict[str, float] | float | None
|
Optional diminishing returns. A float applied to every channel, or a
dict of channel -> exponent b in (0, 1]; channels absent from the dict
stay linear. The contribution becomes k * spend ** b, with k chosen so
that the MARGINAL return at b = 1.0 is linear and takes the same code path as saturation=None, so it reproduces the linear output exactly rather than approximately. Curvature is only identified by variation in spend LEVEL. A plan that sits in a narrow band around its own average barely traces the curve out, which is why b is normally treated as an assumption rather than an estimate. Schedules that drive spend to zero trace out far more of it -- whether that is enough to estimate b is a question this parameter exists to let a notebook answer. |
None
|
adstock
|
dict[str, float] | float | None
|
Optional geometric carryover. A float applied to every channel, or a dict of channel -> decay in [0, 1); channels absent from the dict get no carryover. Applied BEFORE saturation, matching the convention in Robyn, Meridian and PyMC-Marketing. Normalised, so a constant spend level passes through unchanged and the supplied marginal return means the same thing at every decay -- see apply_adstock. decay = 0.0 is no carryover and takes the same code path as adstock=None, so it reproduces the no-carryover output exactly. Carryover matters to this package more than it looks. The phasing lever works by adding high-frequency spend variation that demand cannot explain; adstock is a low-pass filter and attenuates exactly that component. So it is a sensitivity that can eat the benefit, not merely another knob. |
None
|
reference_spend
|
dict[str, float] | None
|
Spend level at which the supplied marginal returns are exact, per
channel. Defaults to each channel's mean spend in |
None
|
Returns:
| Type | Description |
|---|---|
pd.Series of simulated sales values.
|
|
Notes
The demand term is added AFTER the noise draw, so supplying it does not disturb the random stream: at demand_coef=0 (or demand=None) this function reproduces its previous output exactly.
Source code in src/how_wrong_is_your_mmm/_dgp.py
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 | |
apply_adstock ¶
apply_adstock(spend: ndarray, decay: float) -> np.ndarray
Normalised geometric adstock: a[t] = (1 - decay) * x[t] + decay * a[t-1].
The (1 - decay) factor is what makes this normalised, and it matters for this package specifically. Without it, carryover inflates total adstocked spend by 1 / (1 - decay), so the supplied marginal return would silently mean something different at every decay and no two settings would be comparable. Normalised, a constant spend level passes through unchanged -- so a channel's steady-state level, and therefore the reference point the marginal return is calibrated at, does not move with decay at all.
Seeded with a[0] = x[0] rather than 0, which is the same steady-state reasoning: a zero seed injects a warm-up ramp that is an artefact of where the array happens to start, and would read as a real spend pattern.
Source code in src/how_wrong_is_your_mmm/_dgp.py
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | |
calibrate_baseline ¶
calibrate_baseline(
spend_df: DataFrame,
true_marginal_returns: dict[str, float] | None = None,
baseline_share: float = 0.7,
baseline_cv: float = 0.0,
reported_shares: dict[str, float] | None = None,
) -> BaselineCalibration
Derive a synthetic world from inputs a practitioner reads off their MMM.
The user supplies ROI per channel and the baseline's share of sales -- both standard MMM decomposition outputs -- rather than an arbitrary intercept. Everything else follows:
contribution_c = ROI_c * mean(spend_c)
total_sales = sum(contributions) / (1 - baseline_share)
baseline_level = baseline_share * total_sales
demand_coef = baseline_level * baseline_cv
Note what drives bias. baseline_share sets the level, which OLS absorbs
into the intercept and which therefore biases nothing on its own. It is
baseline_cv -- how much that baseline moves week to week -- that creates
omitted-variable bias, and because the baseline is typically the largest
term in the decomposition, small relative wobbles are large absolute swings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spend_df
|
DataFrame
|
DataFrame with one column per channel. |
required |
true_marginal_returns
|
dict[str, float] | None
|
ROI (£ revenue per £ spend) per channel. Defaults to the package's illustrative 0.5 / 1.0 / 1.5. |
None
|
baseline_share
|
float
|
Baseline (non-media) share of total sales, in [0, 1). Real MMMs typically report 0.6-0.8. |
0.7
|
baseline_cv
|
float
|
Coefficient of variation of the baseline week to week. 0.0 gives a flat baseline and therefore no omitted-variable bias. |
0.0
|
reported_shares
|
dict[str, float] | None
|
Optional per-channel shares of sales as reported by the user's own MMM. When supplied, the returned object carries the total sales each channel separately implies, and their spread -- a consistency check on the user's numbers rather than an input the simulation needs. |
None
|
Returns:
| Type | Description |
|---|---|
BaselineCalibration
|
|
Source code in src/how_wrong_is_your_mmm/_dgp.py
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | |