Skip to content

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:

  • "white_noise": iid draws. Demand varies week to week, so weekly reshuffling of spend can decouple from it.
  • "ar1": persistent demand, x_t = ar_coef * x_{t-1} + eps.
  • "seasonal": a pure sinusoid at season_period weeks.
  • "seasonal_ar1": season_weight * seasonal + (1 - season_weight) * ar1.
  • "trend": a random walk with drift, x_t = x_{t-1} + trend_drift + eps. A genuine non-stationary trend -- unlike "ar1", which however persistent (ar_coef < 1 is enforced) always mean-reverts. This is the sharpest test for adstock, a low-pass filter: integration concentrates a random walk's energy near zero frequency even more than a raw AR(1) does, so carryover should leave it comparatively untouched while destroying the high-frequency variation phasing adds. Depends on seed, like "white_noise"/"ar1" -- each draw is a different path, not a fixed shape.

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
def 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
    ----------
    n_obs:
        Number of observations (weeks).
    process:
        One of DEMAND_PROCESSES:

        - "white_noise": iid draws. Demand varies week to week, so weekly
          reshuffling of spend can decouple from it.
        - "ar1": persistent demand, x_t = ar_coef * x_{t-1} + eps.
        - "seasonal": a pure sinusoid at season_period weeks.
        - "seasonal_ar1": season_weight * seasonal + (1 - season_weight) * ar1.
        - "trend": a random walk with drift, x_t = x_{t-1} + trend_drift + eps.
          A genuine *non-stationary* trend -- unlike "ar1", which however
          persistent (ar_coef < 1 is enforced) always mean-reverts. This is
          the sharpest test for adstock, a low-pass filter: integration
          concentrates a random walk's energy near zero frequency even more
          than a raw AR(1) does, so carryover should leave it comparatively
          untouched while destroying the high-frequency variation phasing
          adds. Depends on `seed`, like "white_noise"/"ar1" -- each draw is a
          different path, not a fixed shape.

        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.
    seed:
        Random seed.
    ar_coef:
        AR(1) coefficient, used by "ar1" and "seasonal_ar1".
    season_period:
        Period of the seasonal component, in observations (52 = annual weekly).
    season_weight:
        Weight on the seasonal component in "seasonal_ar1", in [0, 1].
    trend_drift:
        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.

    Returns
    -------
    np.ndarray of length n_obs, standardised to sample mean 0 and sd 1.
    """
    if process not in DEMAND_PROCESSES:
        raise ValueError(f"process must be one of {DEMAND_PROCESSES}, got {process!r}")
    if not -1.0 < ar_coef < 1.0:
        raise ValueError("ar_coef must be strictly between -1 and 1 for stationarity")
    if not 0.0 <= season_weight <= 1.0:
        raise ValueError("season_weight must be between 0 and 1 inclusive")
    if season_period <= 0:
        raise ValueError("season_period must be positive")

    rng = np.random.default_rng(seed)

    def _ar1() -> np.ndarray:
        burn = 200
        eps = rng.standard_normal(n_obs + burn)
        out = np.zeros(n_obs + burn)
        for t in range(1, n_obs + burn):
            out[t] = ar_coef * out[t - 1] + eps[t]
        return out[burn:]

    def _seasonal() -> np.ndarray:
        return np.sin(2 * np.pi * np.arange(n_obs) / season_period)

    def _trend() -> np.ndarray:
        """Random walk with drift: x_t = x_{t-1} + trend_drift + eps_t, x_0 = 0.

        Deliberately NOT a deterministic ramp. A noiseless straight line is an
        unrealistic caricature of demand, and (found the hard way) it is a
        non-stationary shape squeezed through code elsewhere in this project
        that draws one series over a long window and then standardises and
        slices it -- a deterministic ramp's variance in a short sub-window is
        a tiny, geometry-dependent fraction of its full-window variance,
        which silently breaks any correlation targeting calibrated against
        the full window. A stochastic walk has the same non-stationarity (by
        design -- see the docstring above) but does not hand callers a
        pathologically clean signal.
        """
        steps = trend_drift + rng.standard_normal(n_obs)
        return np.cumsum(steps)

    if process == "white_noise":
        series = rng.standard_normal(n_obs)
    elif process == "ar1":
        series = _ar1()
    elif process == "seasonal":
        series = _seasonal()
    elif process == "trend":
        series = _trend()
    else:
        seasonal = _seasonal()
        ar = _ar1()
        seasonal = (seasonal - seasonal.mean()) / (seasonal.std() or 1.0)
        ar = (ar - ar.mean()) / (ar.std() or 1.0)
        series = season_weight * seasonal + (1 - season_weight) * ar

    sd = series.std()
    if sd == 0:
        raise ValueError(
            "demand series has zero variance -- check season_period against n_obs"
        )
    return (series - series.mean()) / sd

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 demand to simulate_sales, or a CollinearityDiagnostic / BudgetPhaser instance's own demand_ after fit()/construction.

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 quality -- it is the expectation, not a guarantee, of any one draw.

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
def simulate_demand_proxy(
    demand: np.ndarray | pd.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
    ----------
    demand:
        The true demand series to build a proxy for -- typically what was
        passed as `demand` to simulate_sales, or a CollinearityDiagnostic /
        BudgetPhaser instance's own `demand_` after fit()/construction.
    quality:
        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 `quality` -- it is the expectation, not a
        guarantee, of any one draw.
    seed:
        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.

    Returns
    -------
    np.ndarray, standardised to mean 0 / sd 1, same length as `demand`.
    """
    if not 0.0 < quality <= 1.0:
        raise ValueError("quality must be in (0, 1]")

    demand_arr = np.asarray(demand, dtype=float)

    if quality >= 1.0:
        noisy = demand_arr
    else:
        rng = np.random.default_rng([seed, _PROXY_STREAM])
        scale = np.sqrt((1 - quality**2) / quality**2)
        noisy = demand_arr + scale * rng.standard_normal(len(demand_arr))

    sd = noisy.std()
    if sd == 0:
        raise ValueError("proxy series has zero variance")
    return (noisy - noisy.mean()) / sd

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 correlation at every setting; what changes is corr(spend_c, demand) = sqrt(demand_share * correlation). The observed correlation matrix cannot reveal the split, which is why omitted-variable bias is not identifiable from spend data alone and needs either a demand proxy or a sensitivity band.

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
def simulate_spend(
    n_obs: int = 104,
    correlation: float = 0.7,
    channels: list[str] | None = None,
    seed: int = 0,
    start_date: str | None = None,
    demand: np.ndarray | pd.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
    ----------
    n_obs:
        Number of observations (weeks).
    correlation:
        Target Pearson correlation between any pair of channels.
    channels:
        List of channel names. Defaults to ["tv", "meta", "search"].
    seed:
        Random seed for reproducibility.
    start_date:
        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.
    demand:
        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.
    demand_share:
        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 `correlation` at every
        setting; what changes is corr(spend_c, demand) = sqrt(demand_share *
        correlation). **The observed correlation matrix cannot reveal the
        split**, which is why omitted-variable bias is not identifiable from
        spend data alone and needs either a demand proxy or a sensitivity band.
    return_demand:
        If True, return (spend_df, demand_series) instead of just spend_df.

    Returns
    -------
    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.
    """
    if channels is None:
        channels = _DEFAULT_CHANNELS
    if not 0.0 <= demand_share <= 1.0:
        raise ValueError("demand_share must be between 0 and 1 inclusive")

    rng = np.random.default_rng(seed)
    noise_std = _noise_std_from_correlation(correlation)

    # The internal draw ALWAYS happens, even when `demand` is supplied, so that
    # supplying a series does not shift the channel-noise draws below.
    # Changing a generator's call sequence silently moves every seeded
    # number already published from this function.
    drawn_demand = rng.standard_normal(n_obs)
    if demand is None:
        demand_arr = drawn_demand
    else:
        demand_arr = np.asarray(demand, dtype=float)
        if demand_arr.shape != (n_obs,):
            raise ValueError(
                f"demand must be a 1-D series of length n_obs={n_obs}, "
                f"got shape {demand_arr.shape}"
            )

    if demand_share < 1.0:
        # Drawn from a SEPARATE generator, deliberately. Taking it from `rng`
        # would shift every channel-noise draw below, so two demand_share
        # settings at the same seed would not be comparable draw for draw --
        # exactly the caveat nudge_shape has to carry. This way they are.
        planning = np.random.default_rng([seed, _PLANNING_STREAM]).standard_normal(
            n_obs
        )
        common = (
            np.sqrt(demand_share) * demand_arr + np.sqrt(1.0 - demand_share) * planning
        )
    else:
        common = demand_arr

    data = {}
    for ch in channels:
        mean, std = _CHANNEL_SCALE.get(ch, _DEFAULT_SCALE)
        signal = common + noise_std * rng.standard_normal(n_obs)
        data[ch] = mean + std * signal

    df = pd.DataFrame(data)
    if start_date is not None:
        df.index = pd.date_range(start=start_date, periods=n_obs, freq="W-MON")
    if return_demand:
        return df, pd.Series(demand_arr, index=df.index, name="demand")
    return df
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:

  1. f = the spend's common factor: each channel standardised, averaged across channels, then standardised again.
  2. u = simulate_demand(process=process, seed=seed), with the part explained by f regressed out and the rest standardised.
  3. 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
def link_demand_to_spend(
    spend_df: pd.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:

    1. f = the spend's common factor: each channel standardised, averaged
       across channels, then standardised again.
    2. u = simulate_demand(process=process, seed=seed), with the part
       explained by f regressed out and the rest standardised.
    3. 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
    ----------
    spend_df:
        Weekly spend, one column per channel. At least 3 rows.
    demand_spend_corr:
        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.
    process:
        One of DEMAND_PROCESSES, for the unlinked part of demand. Default
        "trend".
    seed:
        Seed for the unlinked part.
    **process_kwargs:
        Forwarded to simulate_demand (ar_coef, season_period,
        season_weight, trend_drift).

    Returns
    -------
    LinkedDemand. `demand` is standardised to mean 0 / sd 1.
    """
    if not 0.0 <= demand_spend_corr <= 1.0:
        raise ValueError("demand_spend_corr must be between 0 and 1 inclusive")
    n_obs = len(spend_df)
    if n_obs < 3:
        raise ValueError("spend_df needs at least 3 rows to link demand to it")

    values = spend_df.to_numpy(dtype=float)
    sds = values.std(axis=0)
    if np.any(sds == 0):
        flat = [c for c, s in zip(spend_df.columns, sds) if s == 0]
        raise ValueError(
            f"cannot link demand to constant spend column(s): {flat}. "
            "A channel with no variation carries no demand signal."
        )
    z = (values - values.mean(axis=0)) / sds
    factor = _standardise(z.mean(axis=1))

    n_ch = values.shape[1]
    if factor.std() == 0:
        # Channels cancel exactly: there is no common factor at all.
        mean_factor_corr = 0.0
    else:
        factor_corr = [np.corrcoef(factor, values[:, i])[0, 1] for i in range(n_ch)]
        mean_factor_corr = float(np.mean(factor_corr))
    if mean_factor_corr <= 0:
        # Channels that cancel out (mean pairwise correlation near -1/(n-1))
        # leave no common factor to link to.
        alpha, capped = 0.0, demand_spend_corr > 0
    else:
        alpha = demand_spend_corr / mean_factor_corr
        capped = alpha > 1.0
        alpha = min(alpha, 1.0)
    if capped:
        warnings.warn(
            f"demand_spend_corr={demand_spend_corr:.2f} is above what this "
            f"spend's common factor reaches ({max(mean_factor_corr, 0.0):.2f}). "
            "Demand is set to the common factor itself.",
            stacklevel=2,
        )

    raw = simulate_demand(n_obs, process=process, seed=seed, **process_kwargs)
    design = np.column_stack([np.ones(n_obs), factor])
    resid = raw - design @ np.linalg.lstsq(design, raw, rcond=None)[0]
    unlinked = _standardise(resid)

    demand = _standardise(alpha * factor + np.sqrt(1.0 - alpha**2) * unlinked)
    realised = {
        str(ch): float(np.corrcoef(values[:, i], demand)[0, 1])
        for i, ch in enumerate(spend_df.columns)
    }
    return LinkedDemand(
        demand=pd.Series(demand, index=spend_df.index, name="demand"),
        target_correlation=float(min(demand_spend_corr, max(mean_factor_corr, 0.0))),
        realised_correlation=realised,
        factor_weight=float(alpha),
        capped=bool(capped),
    )

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 true_marginal_returns, kept for backward compatibility. Raises ValueError if both are supplied. Emits a FutureWarning -- migrate to true_marginal_returns.

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 controls) and the model is correctly specified. Toggling between the two is how the bias is measured.

None
demand_coef float

Coefficient on demand. Ignored when demand is None. Get a value in practitioner-legible units from calibrate_baseline, which derives it from the baseline's share of sales and its volatility.

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 reference_spend is exactly the supplied true_marginal_returns value. So the supplied marginal return keeps its meaning -- it is the return on the next pound at the reference level, rather than an average over the curve.

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 spend_df. Supply it explicitly when comparing schedules, so that every schedule is calibrated against the SAME curve rather than against its own mean -- otherwise the curve moves with the schedule and the comparison is not like for like. Ignored when the channel is linear.

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
def simulate_sales(
    spend_df: pd.DataFrame,
    true_marginal_returns: dict[str, float] | None = None,
    base_sales: float = 1_000.0,
    revenue_noise_std: float = 26_000.0,
    seed: int = 0,
    true_elasticities: dict[str, float] | None = None,
    demand: np.ndarray | pd.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
    ----------
    spend_df:
        DataFrame with one column per channel. Can be synthetic or real.
    true_marginal_returns:
        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.
    base_sales:
        Base sales intercept.
    revenue_noise_std:
        Standard deviation of sales noise.
    seed:
        Random seed for the noise draw.
    true_elasticities:
        Deprecated alias for `true_marginal_returns`, kept for backward
        compatibility. Raises ValueError if both are supplied. Emits a
        FutureWarning -- migrate to `true_marginal_returns`.
    demand:
        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 `controls`) and the model is correctly
        specified. Toggling between the two is how the bias is measured.
    demand_coef:
        Coefficient on `demand`. Ignored when demand is None. Get a value in
        practitioner-legible units from calibrate_baseline, which derives it
        from the baseline's share of sales and its volatility.
    saturation:
        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 `reference_spend` is exactly the supplied
        `true_marginal_returns` value. So the supplied marginal return keeps
        its meaning -- it is the return on the next pound at the reference
        level, rather than an average over the curve.

        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.
    adstock:
        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.
    reference_spend:
        Spend level at which the supplied marginal returns are exact, per
        channel. Defaults to each channel's mean spend in `spend_df`. Supply
        it explicitly when comparing schedules, so that every schedule is
        calibrated against the SAME curve rather than against its own mean --
        otherwise the curve moves with the schedule and the comparison is
        not like for like. Ignored when the channel is linear.

    Returns
    -------
    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.
    """
    if true_elasticities is not None:
        if true_marginal_returns is not None:
            raise ValueError(
                "Pass only one of true_marginal_returns or the deprecated "
                "true_elasticities, not both."
            )
        warnings.warn(
            "true_elasticities is deprecated and will be removed in a "
            "future release -- these are marginal returns (£ revenue per "
            "£ spend), not elasticities. Use true_marginal_returns instead.",
            FutureWarning,
            stacklevel=2,
        )
        true_marginal_returns = true_elasticities

    if true_marginal_returns is None:
        true_marginal_returns = _DEFAULT_MARGINAL_RETURNS

    rng = np.random.default_rng(seed)
    sales = base_sales + revenue_noise_std * rng.standard_normal(len(spend_df))

    if demand is not None and demand_coef:
        demand_arr = np.asarray(demand, dtype=float)
        if demand_arr.shape != (len(spend_df),):
            raise ValueError(
                f"demand must be a 1-D series of length {len(spend_df)} to match "
                f"spend_df, got shape {demand_arr.shape}"
            )
        sales = sales + demand_coef * demand_arr

    contributions = channel_contributions(
        spend_df, true_marginal_returns, saturation, adstock, reference_spend
    )
    sales = sales + contributions.sum(axis=1).to_numpy()

    return pd.Series(sales, name="sales")

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
def apply_adstock(spend: np.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.
    """
    if decay == 0.0:
        return spend
    out = np.empty_like(spend, dtype=float)
    out[0] = spend[0]
    for t in range(1, len(spend)):
        out[t] = (1.0 - decay) * spend[t] + decay * out[t - 1]
    return out

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
def calibrate_baseline(
    spend_df: pd.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
    ----------
    spend_df:
        DataFrame with one column per channel.
    true_marginal_returns:
        ROI (£ revenue per £ spend) per channel. Defaults to the package's
        illustrative 0.5 / 1.0 / 1.5.
    baseline_share:
        Baseline (non-media) share of total sales, in [0, 1). Real MMMs
        typically report 0.6-0.8.
    baseline_cv:
        Coefficient of variation of the baseline week to week. 0.0 gives a flat
        baseline and therefore no omitted-variable bias.
    reported_shares:
        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.

    Returns
    -------
    BaselineCalibration
    """
    if true_marginal_returns is None:
        true_marginal_returns = _DEFAULT_MARGINAL_RETURNS
    if not 0.0 <= baseline_share < 1.0:
        raise ValueError("baseline_share must be in [0, 1)")
    if baseline_cv < 0.0:
        raise ValueError("baseline_cv must be non-negative")

    contributions: dict[str, float] = {}
    for ch in spend_df.columns:
        if ch not in true_marginal_returns:
            raise ValueError(
                f"Channel '{ch}' in spend_df has no entry in true_marginal_returns."
            )
        contributions[ch] = float(true_marginal_returns[ch] * spend_df[ch].mean())

    media = sum(contributions.values())
    if media <= 0:
        raise ValueError(
            "Total media contribution must be positive to calibrate a baseline."
        )
    total = media / (1.0 - baseline_share)
    level = baseline_share * total

    implied_totals: dict[str, float] = {}
    spread: float | None = None
    if reported_shares is not None:
        for ch in spend_df.columns:
            share = reported_shares.get(ch)
            if share is None:
                raise ValueError(f"reported_shares has no entry for channel '{ch}'.")
            if not 0.0 < share < 1.0:
                raise ValueError(
                    f"reported_shares['{ch}'] must be strictly between 0 and 1."
                )
            implied_totals[ch] = contributions[ch] / share
        values = np.array(list(implied_totals.values()), dtype=float)
        spread = float(100 * (values.max() - values.min()) / values.mean())

    return BaselineCalibration(
        baseline_level=float(level),
        demand_coef=float(level * baseline_cv),
        total_sales=float(total),
        channel_shares={ch: contributions[ch] / total for ch in contributions},
        contributions=contributions,
        implied_totals=implied_totals,
        share_spread_pct=spread,
    )