Weekly orders under repeated offers: longitudinal TMLE#

At a glance#

A subscription retailer decides each week, for three weeks, whether to send a customer a free-shipping code, and records every week whether the customer ordered. How would the share of customers ordering each week change under a code every week, or a code only after a week without an order (win-back), compared with no codes? And what if the retailer doubled each customer’s odds of a code under its current way of choosing?

Codes raise ordering, and the effect fades over the weeks. A code every week raises the share ordering in week 1 by 0.168, about 17 more customers ordering per 100 (95% confidence interval 0.151 to 0.185), fading to 0.076 by week 3 (0.030 to 0.121). Over the three weeks, a code every week adds 0.355 orders per customer (0.294 to 0.417) and win-back 0.228 (0.183 to 0.274). Against the current way of choosing, doubling the odds of a code adds 0.0248 in week 1 (interval 0.0223 to 0.0273) and 0.0114 by week 3 (0.0060 to 0.0166).

The answer assumes that the retailer’s records hold everything that drove both who got a code, or who stopped allowing the retailer to track their orders, and who ordered. The data cannot check that.

The data are simulated, so we know the true effects. A code every week has true effects of 0.178, 0.122, and 0.110, and each interval contains its value. Win-back’s week-3 interval and its total’s interval miss their true values (0.091 and 0.28); among many intervals, a few misses are expected by chance.

The question#

The retailer’s scoring system draws each week who gets the code, favoring customers who did not order the week before and customers who are not engaged (a score recorded before each send). The marketing lead wants the weekly order curve under three policies: never (no code), always (a code every week), and win_back (a code only after a week without an order). For each policy and week, the quantity we want is the share of customers who would order that week had all of them received that policy’s codes and stayed tracked, minus the same share under never.

A customer who orders in week 1 may not order in week 2. In the graph, an arrow means “causes”, drawn for one week \(t\). \(W\) is tenure, \(L_t\) engagement, \(A_t\) the code, \(C_t\) staying tracked after the send, \(Y_t\) that week’s order (\(Y_0\) is the order in the week before the campaign), and \(U\) an unrecorded cause.

 W (tenure)  -->  L_t, A_t, C_t, Y_t

 One week t (t = 1, 2, 3):

   Y_{t-1}  -->  L_t  -->  A_t  -->  Y_t  -->  next week's L, A, and Y
       |                    ^         ^
       +--------------------+---------+        (last week's order drives the code and the order)
   A_{t-1}  -->  L_t, A_t, Y_t                 (two codes in a row work less well)
   L_t, A_t  -->  C_t                          (C_t does not read Y_t)

 U (unrecorded cause)  - - ->  A_t, C_t, and Y_t   (assumed absent)

Last week’s order is the trap. It is a confounder of this week’s code, a cause of both the code and the order, so each week’s code must be compared among customers with the same earlier orders. But the earlier codes changed those orders: part of a week-1 code’s effect on week-3 orders runs through the week-1 and week-2 orders. One regression of the week-3 order on all codes and all earlier orders would hold those orders fixed and cut off that part of the effect.

Details: what each arrow and missing arrow asserts

arrow or absent arrow

what it asserts

role

W to L_t, A_t, C_t, Y_t

tenure shifts engagement, the scoring, staying tracked, and ordering

baseline confounder

Y_{t-1} to A_t and Y_t

the scoring favors customers who did not order last week, and ordering persists

an earlier outcome that confounds the next code

A_{t-1} to L_t and Y_t

a code raises next week’s engagement, and a second code in a row works less well

the treatment changes a later confounder

L_t to A_t, C_t, Y_t

engaged customers get fewer codes, stay tracked more, and order more

a weekly confounder

no Y_t to C_t

whether a customer stops being tracked does not depend on that week’s order, given the record

tracking loss explained by recorded causes

W to Y_0; L_{t-1} to L_t; A_{t-1} to A_t

tenure shifts the pre-campaign order, engagement persists from week to week, and the scoring reads last week’s code

parts of the record the analysis adjusts for

U absent

nothing unrecorded drives both the code, or tracking loss, and the order

the assumption the data cannot check

Load the tools#

Every fit sets its seeds, so a rerun prints the same numbers. Another version of cleverly can print slightly different numbers. The figures on this page need matplotlib: pip install "cleverly[plot]".

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression, LogisticRegression

import cleverly

pd.set_option("display.width", 130)
pd.set_option("display.max_columns", 20)
print("cleverly", cleverly.__version__)
cleverly 0.2.4

The data#

make_weekly_orders draws 12,000 simulated customers and also returns the true values, which real data never give you. The seed, 3000, was fixed before the page first ran, so the page could not pick a flattering draw.

from cleverly.datasets import make_weekly_orders

# With your own data, load a wide table here: one row per customer, with the baseline columns,
# then for each week the engagement score, the offer (1 sent, 0 not), a flag for still being
# tracked after the send, and that week's order (1 or 0, missing once tracking stops).
# Real data have no `truth`, so drop every line that uses it.
frame, truth = make_weekly_orders(12_000, seed=3000)
print("rows and columns:", frame.shape)
print(list(frame.columns))
print(frame.head(5).to_string())
print()
for week in (1, 2, 3):
    tracked = frame[f"tracked_{week}"].eq(1)
    print(
        f"week {week}: tracked {int(tracked.sum())} of {len(frame)},",
        f"offered {frame[f'offer_{week}'].mean():.3f},",
        f"ordered {frame.loc[tracked, f'order_{week}'].mean():.3f} of those tracked",
    )
print()
print("true values of the simulated data:")
for name in (
    "ate_regimen[always vs never @ t=1]",
    "ate_regimen[always vs never @ t=2]",
    "ate_regimen[always vs never @ t=3]",
    "ate_regimen[win_back vs never @ t=1]",
    "ate_regimen[win_back vs never @ t=2]",
    "ate_regimen[win_back vs never @ t=3]",
):
    print(f"  {name:38s} {truth[name]:.4f}")
rows and columns: (12000, 14)
['tenure', 'order_0', 'engaged_1', 'offer_1', 'tracked_1', 'order_1', 'engaged_2', 'offer_2', 'tracked_2', 'order_2', 'engaged_3', 'offer_3', 'tracked_3', 'order_3']
   tenure  order_0  engaged_1  offer_1  tracked_1  order_1  engaged_2  offer_2  tracked_2  order_2  engaged_3  offer_3  tracked_3  order_3
0     2.0      1.0        0.0      0.0        1.0      0.0        0.0      1.0        1.0      1.0        0.0      0.0        1.0      0.0
1     1.0      0.0        0.0      1.0        1.0      0.0        1.0      1.0        1.0      1.0        1.0      1.0        1.0      1.0
2     0.0      0.0        1.0      1.0        1.0      0.0        0.0      1.0        1.0      0.0        1.0      1.0        1.0      0.0
3     0.0      0.0        1.0      0.0        1.0      0.0        0.0      1.0        0.0      NaN        NaN      NaN        NaN      NaN
4     0.0      1.0        1.0      0.0        1.0      1.0        1.0      0.0        1.0      1.0        0.0      0.0        1.0      0.0

week 1: tracked 11392 of 12000, offered 0.487, ordered 0.601 of those tracked
week 2: tracked 10841 of 12000, offered 0.469, ordered 0.613 of those tracked
week 3: tracked 10321 of 12000, offered 0.465, ordered 0.622 of those tracked

true values of the simulated data:
  ate_regimen[always vs never @ t=1]     0.1784
  ate_regimen[always vs never @ t=2]     0.1216
  ate_regimen[always vs never @ t=3]     0.1105
  ate_regimen[win_back vs never @ t=1]   0.1007
  ate_regimen[win_back vs never @ t=2]   0.0890
  ate_regimen[win_back vs never @ t=3]   0.0907

Each row is one customer: tenure (0, 1, or 2 for the longest) and order_0, an order in the week before the campaign. Then come, for each week, the engaged score, the offer (1 when the code was sent), tracked (1 while the customer allows tracking), and the week’s order. Once a customer stops being tracked, their later columns are missing, as in row 3; keep these customers, because the fit uses their early weeks. About half of the customers get a code each week. A name such as ate_regimen[always vs never @ t=1] reads: the average effect (ate) of the plan (regimen) always against never, in week 1.

Why a simple comparison misleads#

A quick analysis would compare, among customers still tracked, those whose codes happened to match a policy so far with those who happened to get no code at all.

from cleverly.datasets import ORDER_PLANS

# This cell only shows why a simple comparison misleads, so you can skip it on your own data.
week_two = frame[frame["tracked_1"] == 1]
print("share offered a code in week 2, by the week-1 order:")
print(week_two.groupby("order_1")["offer_2"].mean().round(3).to_string())
print()

rows = []
for week in (1, 2, 3):
    kept = frame[frame[f"tracked_{week}"] == 1]
    follows = {}
    for name, plan_rule in ORDER_PLANS.items():
        # A customer follows a plan when every offer so far is the plan's offer.
        followed = np.ones(len(kept), dtype=bool)
        for t in range(1, week + 1):
            wanted = plan_rule(kept[f"order_{t - 1}"].to_numpy())
            followed &= kept[f"offer_{t}"].to_numpy() == wanted
        follows[name] = kept.loc[followed, f"order_{week}"].mean()
    for name in ("always", "win_back"):
        key = f"ate_regimen[{name} vs never @ t={week}]"
        rows.append(
            {
                "plan": name,
                "week": week,
                "crude_vs_never": follows[name] - follows["never"],
                "true_vs_never": truth[key],
            }
        )
crude = pd.DataFrame(rows).set_index(["plan", "week"])
print(crude.round(3).to_string())
share offered a code in week 2, by the week-1 order:
order_1
0.0    0.668
1.0    0.337

               crude_vs_never  true_vs_never
plan     week                               
always   1              0.047          0.178
win_back 1              0.035          0.101
always   2             -0.041          0.122
win_back 2              0.007          0.089
always   3             -0.084          0.110
win_back 3             -0.016          0.091

Customers who did not order in week 1 got a code in week 2 twice as often (0.668, against 0.337). So the customers who happened to get a code every week include more customers who were not ordering, and those customers would order less under any policy. The simple comparison (crude_vs_never) therefore understates every effect, and for a code every week it has the wrong sign by week 3.

Write down the study design#

The study description (StudyProtocol) says who is in the study, when follow-up starts, the policies, the outcome, and how customers who stop being tracked count. It is optional; CausalStudy stores it with every result, so a later reader sees what was estimated.

from cleverly.datasets import weekly_orders_protocol

# For your own study, build cleverly.StudyProtocol(target_population=..., eligibility=(...),
# time_zero=..., treatment_strategies=(...), treatment_versions=(...), outcome=..., horizon=...,
# intercurrent_event_handling=(...), interference_unit=..., assumption_rationale=(...)), with text
# for each field in the order the output prints them.
protocol = weekly_orders_protocol()
print("\n".join(protocol.summary_lines()))
Population: Active subscribers at the start of the campaign window
Eligibility: Active subscription at the first weekly send; Marketing consent at the first weekly send; At least one prior order; One account per customer, so shared-household accounts are excluded; A subscription term that is fixed at the first weekly send and runs through week 3
Follow-up starts: The first weekly send, after the week-1 engagement score and before the first offer
Strategies: Send no code in weeks 1 to 3; Send the free-shipping code every week; Win-back: send the code in a week only when the customer did not order the week before; Keep the scoring system's chance of a code each week; Double the odds of a code under the scoring system each week
Versions: No code sent; The declared free-shipping code, one send per week, valid until the end of that week; The declared free-shipping code after a week without an order, no code otherwise; The scoring system's draw of the declared code; A draw of the declared code with the odds of the scoring system's chance doubled
Outcome: An order in each week, recorded weekly; a customer can order in any week
Horizon: Weeks 1 to 3, each week ending after its send
Intercurrent events: Tracking-consent withdrawal censors the customer from that week on. The strategy is hypothetical: the orders had tracking continued; Each code expires at the end of its week; None: the term runs through week 3, so no account closes before the last week
Interference unit: Individual customer
Rationale: The scoring system reads tenure, the week's engagement score, and last week's order and code, all recorded, which gives sequential exchangeability for the codes; Tenure, weekly engagement, and the week's code are the recorded causes of consent loss; Declared code templates, one send per week, support that each weekly offer is one well-defined action, so a customer's recorded outcome is the outcome they would have had under the offers they got; One account per customer and per-customer codes support no interference

Follow-up starts before the first send, so no code changes who is in the study, and the interference unit says each customer’s codes affect only their own orders. “Versions” say exactly what each code is. Withdrawing tracking consent is an intercurrent event, one after the start that changes what is observed: it “censors” a customer, so their later data are missing, and the “hypothetical” strategy asks for the orders they would have placed had tracking continued. In the rationale, “sequential exchangeability” is the no-hidden-cause condition of the next section and “one well-defined action” the one-declared-code condition (called consistency).

Columns, policies, and what must hold#

LongitudinalTreatment names the columns of the wide table, and Repeated([...]) lists one outcome column per week. A policy is a tuple with one code per week, or a rule (DynamicRegimen) that reads the customer’s record that week (the columns recorded up to then). study.identify lists what must hold for the answer to be causal.

from cleverly import CausalStudy, LongitudinalTreatment, RegimeContrast, Repeated
from cleverly.datasets import offer_after_no_order
from cleverly.longitudinal import DynamicRegimen

WEEKS = (1, 2, 3)  # For your own data, your decision weeks.


def weekly_design(*, baseline=("tenure", "order_0"), engagement=True):
    # For your own data, change the column names. Repeated(...) lists one outcome column per
    # week, in time order.
    return LongitudinalTreatment(
        outcome=Repeated([f"order_{week}" for week in WEEKS]),
        treatment=tuple(f"offer_{week}" for week in WEEKS),
        baseline=baseline,
        time_varying=tuple(((f"engaged_{week}",) if engagement else ()) for week in WEEKS),
        censoring=tuple(f"tracked_{week}" for week in WEEKS),
    )


# The win-back rule reads last week's order from the customer's record. A rule gets `history`, a
# DataFrame with one row per customer and one column per recorded variable up to that week, and
# returns the code (1 or 0) for each row. offer_after_no_order returns 1 where last week's order
# is 0 and 0 otherwise; write your own rule the same way. rule_kind="known" says the rule was
# fixed in advance, not learned from these data.
win_back = DynamicRegimen(
    "win_back",
    tuple(
        (lambda history, last=f"order_{week - 1}": offer_after_no_order(history[last]))
        for week in WEEKS
    ),
    rule_kind="known",
)
plans = {"never": (0, 0, 0), "always": (1, 1, 1), "win_back": win_back}
study = CausalStudy(frame, design=weekly_design(), protocol=protocol)
effect = study.identify(RegimeContrast(plans, reference="never"))
print(effect.summary())
print()
print("adjusted for at offer_3:", ", ".join(study.data.history_names(3)))
                         Causal question (ate_regime)
==============================================================================
Question:   contrast of each regime     Rows:                           12,000
            against the reference       Answered by:     adjusting for history
Outcome:    order_1, order_2, order_3
            (binary), measured at each
            time point
Treatment:  offer_1, offer_2, offer_3
Baseline:   tenure, order_0
==============================================================================
What each treatment time adjusts for
treatment   adjusted for
------------------------------------------------------------------------------
offer_1     tenure, order_0, engaged_1
offer_2     tenure, order_0, engaged_1, order_1, engaged_2, offer_1
offer_3     tenure, order_0, engaged_1, order_1, engaged_2, order_2 and 3 more
==============================================================================
Conditions the answer rests on
condition                            checkable   what it says
------------------------------------------------------------------------------
well-defined treatment               no          Each unit's observed outcomes
                                                 are the ones it would have
                                                 had under the treatments it
                                                 actually received over time.
                                                 This needs each treatment to
                                                 be well defined: every way of
                                                 getting the same treatment
                                                 has the same effect.
no interference                      no          One unit's treatment does not
                                                 change another unit's
                                                 outcome.
no hidden confounding at each time   no          At each time, among units
                                                 with the same recorded
                                                 history, which treatment a
                                                 unit got and whether it stays
                                                 in follow-up are unrelated to
                                                 the outcomes it would have
                                                 had.
overlap at each time                 partly      At each time, units with
                                                 every history that following
                                                 the compared regimens can
                                                 produce had some chance of
                                                 the treatment a regimen
                                                 assigns and of staying in
                                                 follow-up.
==============================================================================
Methods
method   name
------------------------------------------------------------------------------
tmle     targeted maximum likelihood (TMLE)
sdr      sequentially doubly robust regression (SDR)
ipsi     incremental propensity score intervention (IPSI)
==============================================================================
Notes:
[1] The data cannot confirm these conditions. Overlap (marked partly) can be
    probed: after a fit, result.diagnostics.support() shows where the fitted
    treatment model gives units little chance of a compared treatment. That
    check reads a fitted model, so a clean result does not prove overlap.
[2] The methods table lists the methods that fit. 9 other methods cannot
    estimate this question; the full summary says why.

adjusted for at offer_3: tenure, order_0, engaged_1, order_1, engaged_2, order_2, engaged_3

The week-2 code is adjusted for order_1, and the week-3 code for order_1 and order_2 (last line). Repeated adds each week’s order to the next week’s record, so you do not list them yourself.

In this page’s words, the conditions are that each code is one declared code (every customer sent a code got the same free-shipping offer), and that one customer’s codes do not change another’s orders. Each week, given the record so far, nothing unrecorded may drive both the code, or tracking loss, and the order. Overlap means every kind of customer had a real chance of each policy’s code and of staying tracked each week. The first three need judgment; “Check the weights and the models” measures overlap. The methods table lists the three methods that can fit this question.

Estimate the weekly order curve#

The method, longitudinal targeted maximum likelihood estimation (LTMLE), uses each earlier order only to adjust the codes after it. It works backward from the last week. A week-3 model predicts each customer’s week-3 order from their full record, with the week-3 code set to the plan’s value. A week-2 model then takes those predictions as its outcome and leaves out the week-2 order, so it averages over the week-2 orders the plan would cause; the same step repeats for week 1. Every route from an early code to a later order stays in the answer.

A correction step then removes the bias the outcome models leave when the offer and tracking models are right: it weights each customer who followed the plan by one over their chance of following it and staying tracked, from those models (each week’s chance of a code and of staying tracked). The estimate stays on target in large samples if either the outcome models or the offer and tracking models are right; the interval is simplest to trust when both are accurate.

from cleverly import CrossFitting, ModelSpec, Runtime, TMLEMethod

# For your own data, swap in your learners. With flexible learners such as gradient boosting,
# use CrossFitting(n_folds=5), so each row's predictions come from models trained without it.
logistic = LogisticRegression(max_iter=1000, random_state=42)
models = ModelSpec(
    outcome_learner=logistic,  # each week's order (0 or 1) from the record so far
    pseudo_learner=LinearRegression(),  # earlier weeks; a regressor, as targets are predictions
    treatment_learner=logistic,  # the chance of an offer each week
    censoring_learner=logistic,  # the chance of staying tracked each week
)
ltmle = TMLEMethod(
    models=models,
    cross_fitting=CrossFitting(enabled=False),  # fit these simple models on all rows
    runtime=Runtime(random_state=42, n_jobs=1),  # fix the seed
)
result = effect.estimate(method=ltmle)
print(result.summary())


# against_truth needs the true values, so on your own data read result.summary() instead.
def against_truth(fit, reference="never"):
    rows = []
    for key, estimate in fit.estimates.items():
        low, high = estimate.ci
        plan, week = key.removeprefix("ate_regimen[").removesuffix("]").split(" @ t=")
        rows.append(
            {
                "plan": plan.removesuffix(f" vs {reference}"),
                "week": int(week),
                "estimate": estimate.psi,
                "ci_low": low,
                "ci_high": high,
                "truth": truth[key],
                "covers": bool(low <= truth[key] <= high),
            }
        )
    return pd.DataFrame(rows).set_index(["plan", "week"])


print()
print(against_truth(result).round(3).to_string())

ltmle_fig = result.plot(
    time_label="Week",
    title="How does the effect of each plan change by week?",
    outcome_label="order share",
    truth={key: truth[key] for key in result.estimates},
)
                        Longitudinal estimate (LTMLE)
==============================================================================
Question:      the outcome at each      Rows:                           12,000
               time point under each    Time points:                         3
               plan; each row is        Out-of-fold predictions:            no
               defined below            Outcome model:    logistic regression;
Outcome:       order_1, order_2,                         linear regression for
               order_3, measured at                        earlier time points
               each time point          Treatment model:   logistic regression
Treatment:     offer_1, offer_2,        Censoring model:   logistic regression
               offer_3                  Probability limits:          [0.01, 1]
Adjusted for:  tenure, order_0; later:
               engaged_1, order_1,
               engaged_2, order_2,
               engaged_3
Censoring:     tracked_1, tracked_2,
               tracked_3; each plan
               keeps every unit
               observed
Method:        longitudinal targeted
               maximum likelihood
               (LTMLE)
==============================================================================
                               estimate  std. error            95% CI  p-value
------------------------------------------------------------------------------
ate_regimen[always vs never      0.1680      0.0086  [0.1511, 0.1848]  <0.0001
@ t=1]
ate_regimen[always vs never      0.1111      0.0146  [0.0822, 0.1396]  <0.0001
@ t=2]
ate_regimen[always vs never      0.0761      0.0233  [0.0302, 0.1215]   0.0012
@ t=3]
ate_regimen[win_back vs never    0.0975      0.0066  [0.0847, 0.1103]  <0.0001
@ t=1]
ate_regimen[win_back vs never    0.0850      0.0111  [0.0632, 0.1067]  <0.0001
@ t=2]
ate_regimen[win_back vs never    0.0458      0.0174  [0.0118, 0.0800]   0.0081
@ t=3]
==============================================================================
What each row estimates
                                       meaning
------------------------------------------------------------------------------
ate_regimen[always vs never @ t=1]     mean order_1 if every unit followed
                                       plan always, minus that mean under plan
                                       never
ate_regimen[always vs never @ t=2]     mean order_2 if every unit followed
                                       plan always, minus that mean under plan
                                       never
ate_regimen[always vs never @ t=3]     mean order_3 if every unit followed
                                       plan always, minus that mean under plan
                                       never
ate_regimen[win_back vs never @ t=1]   mean order_1 if every unit followed
                                       plan win_back, minus that mean under
                                       plan never
ate_regimen[win_back vs never @ t=2]   mean order_2 if every unit followed
                                       plan win_back, minus that mean under
                                       plan never
ate_regimen[win_back vs never @ t=3]   mean order_3 if every unit followed
                                       plan win_back, minus that mean under
                                       plan never
==============================================================================
What each plan assigns and who followed it to the end
plan             followed  max weight  effective size  assigns
------------------------------------------------------------------------------
never     1,623 of 12,000        45.1             888  0 at every time point
always    1,150 of 12,000        44.2             693  1 at every time point
win_back  3,128 of 12,000         6.0           3,071  a declared rule at
                                                       every time point
==============================================================================
Simultaneous 95% bands
                                                   band
------------------------------------------------------------------------------
ate_regimen[always vs never @ t=1]     [0.1456, 0.1903]
ate_regimen[always vs never @ t=2]     [0.0728, 0.1490]
ate_regimen[always vs never @ t=3]     [0.0153, 0.1364]
ate_regimen[win_back vs never @ t=1]   [0.0804, 0.1145]
ate_regimen[win_back vs never @ t=2]   [0.0561, 0.1137]
ate_regimen[win_back vs never @ t=3]   [0.0004, 0.0910]
==============================================================================
Notes:
[1] The interval of ate_regimen[always vs never @ t=1], ate_regimen[always vs
    never @ t=2], ate_regimen[always vs never @ t=3], ate_regimen[win_back vs
    never @ t=1], ate_regimen[win_back vs never @ t=2], ate_regimen[win_back
    vs never @ t=3], a difference of two proportions, is built from the two
    proportions' log-odds intervals, so it need not be centred on the
    estimate. The p-value is the level at which the interval would just reach
    the null value.
[2] The bands cover all 6 rows at once with 95% probability; use them when you
    read several rows together. No validation study covers the bands for this
    kind of fit, so cleverly marks them experimental.

               estimate  ci_low  ci_high  truth  covers
plan     week                                          
always   1        0.168   0.151    0.185  0.178    True
         2        0.111   0.082    0.140  0.122    True
         3        0.076   0.030    0.121  0.110    True
win_back 1        0.098   0.085    0.110  0.101    True
         2        0.085   0.063    0.107  0.089    True
         3        0.046   0.012    0.080  0.091   False
../_images/319b72d8ceef995c6958cb8a910cfc0f0d268452352aa1322763e536a1f7c415.png

Each row of the estimate table is one policy against never in one week (@ t=2 is week 2). The effect of a code every week fades as customers get codes in a row, and win-back gains less with fewer codes. “Each plan keeps every unit observed” means each answer is the order share had nobody stopped being tracked. The plan table’s weight columns are read in “Check the weights and the models”; “probability limits” cap every weight at 100. In the figure the crosses mark the true values, the darker shading is each 95% interval, and the lighter shading is the simultaneous band read below. Both widen toward week 3, as fewer customers stay on each plan and tracked (the counts under the figure).

Against the truth (last table), five of the six intervals hold. Win-back’s week-3 interval, 0.012 to 0.080, misses the true 0.091, which is ordinary sampling variation for one interval among six (Details). To read the whole curve at once, use the simultaneous bands at the bottom of the summary, which are built to cover all six rows together with 95% probability; win-back’s week-3 band, 0.0004 to 0.0910, holds the truth. They are marked experimental, because no study checks a band over just these six rows.

Details: the models, and the page’s 400 repeated draws

The outcome models are logistic regressions on main terms, so they miss the interaction of two codes in a row, and the earlier weeks’ linear regressions approximate their targets. The offer and tracking models are logistic regressions on the record, which match how the simulation draws codes and tracking loss. With a wrong outcome model, offer and tracking models that are right and fitted by maximum likelihood, and no weight at the cap, the interval stays valid in large samples and can be conservative (wider than it needs to be); the technical reference gives the argument.

A simulation we ran for this page (script reviews/notebook-review/probes/weekly-outcomes/sweep.py in the repository) repeats the page’s fits on 400 draws, seeds 3000 to 3399. Each of the six intervals above held its true value on 373 to 389 of 400 draws (95% would be 380), and the average error of each estimate was within 0.0006 of zero, which the simulation cannot tell apart from zero.

What goes wrong when earlier orders are left out#

A natural shortcut is to answer each week separately with the same method: fit week 1’s order on week 1’s code, week 2’s order on the first two codes, and so on, adjusting for tenure, the week-0 order, and the engagement scores. Each separate fit leaves the earlier weeks’ orders out of the record, even though the scoring system reads them.

# This check needs the true effects, so it runs only on simulated data.
rows = []
for week in WEEKS:
    # A separate fit for each week: that week's order is the only outcome, and the earlier
    # weeks' orders are not part of the record the offers are adjusted for.
    separate_design = LongitudinalTreatment(
        outcome=f"order_{week}",
        treatment=tuple(f"offer_{t}" for t in range(1, week + 1)),
        baseline=("tenure", "order_0"),
        time_varying=tuple((f"engaged_{t}",) for t in range(1, week + 1)),
        censoring=tuple(f"tracked_{t}" for t in range(1, week + 1)),
    )
    separate = (
        CausalStudy(frame, design=separate_design)
        .identify(RegimeContrast({"never": (0,) * week, "always": (1,) * week}, reference="never"))
        .estimate(method=ltmle)
    )
    key = f"ate_regimen[always vs never @ t={week}]"
    estimate = separate["ate_regimen[always vs never]"]
    rows.append(
        {
            "week": week,
            "separate_fits": estimate.psi,
            "separate_low": estimate.ci[0],
            "separate_high": estimate.ci[1],
            "weekly_curve": result[key].psi,
            "truth": truth[key],
        }
    )
print("always minus never:")
print(pd.DataFrame(rows).set_index("week").round(3).to_string())
always minus never:
      separate_fits  separate_low  separate_high  weekly_curve  truth
week                                                                 
1             0.168         0.151          0.185         0.168  0.178
2             0.051         0.022          0.079         0.111  0.122
3             0.008        -0.034          0.050         0.076  0.110

Week 1 agrees (0.168 in both), because the order before week 1 is a baseline column in both analyses. From week 2 on the separate fits fall far short of the truth, and their intervals miss. Customers who did not order last week got more codes and order less this week anyway, so without last week’s order in the record, the code looks weaker than it is.

The weekly curve is the same separate fit for each week with every earlier order added to the record, and its backward fit uses each order only to adjust the codes after it. A single regression on all codes and earlier orders would instead cut off part of the earlier codes’ effect, as “The question” explains.

Details: the separate fits over 400 draws

In the page’s simulation, the separate fits fell below the truth on all 400 draws in weeks 2 and 3, by 0.071 and 0.098 on average.

Total orders over the three weeks#

How many extra orders does a policy bring per customer over the campaign? That is the sum of the three weekly gains. The weekly gains are estimated on the same customers, so their errors are related, and result.contrast(...) takes that into account. Adding the weekly variances does not.

rows = []
for name in ("always", "win_back"):
    keys = [f"ate_regimen[{name} vs never @ t={week}]" for week in WEEKS]
    # contrast() adds the three weekly effects and uses their joint uncertainty.
    total = result.contrast(lambda values: values[0] + values[1] + values[2], keys, name=name)
    added_up = float(np.sqrt(sum(result[key].std_error ** 2 for key in keys)))
    rows.append(
        {
            "plan": name,
            "extra_orders": total.psi,
            "ci_low": total.ci[0],
            "ci_high": total.ci[1],
            "std_error": total.std_error,
            "if_weeks_independent": added_up,
            "truth": sum(truth[key] for key in keys),
        }
    )
print("extra orders per customer over weeks 1 to 3, against never:")
print(pd.DataFrame(rows).set_index("plan").round(3).to_string())
extra orders per customer over weeks 1 to 3, against never:
          extra_orders  ci_low  ci_high  std_error  if_weeks_independent  truth
plan                                                                           
always           0.355   0.294    0.417      0.031                 0.029   0.41
win_back         0.228   0.183    0.274      0.023                 0.022   0.28

Win-back’s interval just misses its true total, because of its week-3 miss. The standard error from contrast is larger than the one from treating the weeks as independent, because a customer who orders more than expected one week tends to do so the next. Report the interval from contrast.

Details: the two intervals over 400 draws

In the page’s simulation, the interval from contrast held the true total on 378 of 400 draws for always, and the other interval on 367.

A softer policy: double each customer’s odds of a code#

An incremental policy keeps the scoring system but multiplies each customer’s odds of a code by a factor, here 2: a 50% chance becomes 67%. It is compared with the “natural course”, the current scoring with every customer kept tracked. The method that fits it (IPSIMethod, incremental propensity score interventions; the propensity score is the chance of a code) needs no overlap for the codes, because it never asks for a code a customer could not get. It still needs every customer to have a real chance of staying tracked, and it needs the offer and tracking models to be right.

from cleverly import IncrementalEffect, IPSIMethod
from cleverly.interventions import Incremental

# Incremental(2.0) doubles the odds of a code that the scoring system gave each customer each
# week; Incremental(1.0) keeps the scoring system as it is ("natural course").
nudge = study.identify(
    IncrementalEffect([Incremental(1.0), Incremental(2.0)], reference="natural course")
)
nudge_result = nudge.estimate(
    method=IPSIMethod(models=models, cross_fitting=ltmle.cross_fitting, runtime=ltmle.runtime)
)
print(against_truth(nudge_result, reference="natural course").round(4).to_string())
print()
print("support:", sorted({estimate.support.label for estimate in nudge_result.estimates.values()}))
              estimate  ci_low  ci_high   truth  covers
plan    week                                           
odds x2 1       0.0248  0.0223   0.0273  0.0262    True
        2       0.0139  0.0098   0.0180  0.0148    True
        3       0.0114  0.0060   0.0166  0.0129    True

support: ['supported']

Doubling the odds brings about 25 more customers per 1,000 ordering in week 1, and each interval holds its true value. The gains are smaller than those of a code every week because the comparison is with the current scoring, under which about half of the customers already get a code, and the policy only raises each customer’s chance. Every row reads supported: a simulation study checks this kind of fit, with outcome models that are right for its data. This page’s outcome models are rougher, so the theory gives no interval guarantee here; report the intervals with that caveat, which the page’s own simulation supports (Details).

Details: what this estimate relies on

The incremental estimate is consistent when the offer and tracking models are right, whatever the outcome models are, and a good outcome model cannot rescue a wrong offer model. Its interval also needs the outcome models to be reasonably accurate (IPSI on a repeated outcome). This page’s outcome models miss the interaction of two codes in a row, so here the theory gives no interval guarantee. On your own data, use outcome learners flexible enough to fit well, with CrossFitting(n_folds=5). In the page’s simulation, the three intervals held their true values on 384 to 389 of 400 draws.

Check the weights and the models#

assess() reads how heavy each policy’s weights are and how well the offer and tracking models predict. A heavy weight means few similar customers back the estimate.

assessment = result.assess()
attention = tuple(item.name for item in assessment.attention)
print("checks that need attention:", attention or "none")
print()
support = assessment.report("support").to_frame()
labels = {
    "n_followed": "followers",
    "max_weight": "largest weight",
    "effective_n": "effective sample size",
    "share_truncated": "share at the cap",
}
# The week-3 curve needs customers who followed the plan in all three weeks.
last = support[(support["horizon"] == 3) & (support["time"] == 3)].set_index("regimen")
shown = last[list(labels)].rename(columns=labels)
shown["effective sample size"] = shown["effective sample size"].round().astype(int)
print("customers who followed each plan in all three weeks:")
print(shown.round({"largest weight": 1, "share at the cap": 3}).to_string())
print()
nuisance = assessment.report("nuisance_models").to_frame()
print("offer and tracking models, measured on the rows they were fitted on:")
for _, row in nuisance[nuisance["role"].isin(["treatment", "censoring"])].iterrows():
    name = "offer" if row["role"] == "treatment" else "tracking"
    print(
        f"  week {row['time']} {name:8s}: AUC {row['auc']:.3f},",
        f"calibration slope {row['calibration_slope']:.3f}",
    )
checks that need attention: none

customers who followed each plan in all three weeks:
          followers  largest weight  effective sample size  share at the cap
regimen                                                                     
never          1623            45.1                    888               0.0
always         1150            44.2                    693               0.0
win_back       3128             6.0                   3071               0.0

offer and tracking models, measured on the rows they were fitted on:
  week 1 offer   : AUC 0.693, calibration slope 1.001
  week 1 tracking: AUC 0.608, calibration slope 1.013
  week 2 offer   : AUC 0.683, calibration slope 1.002
  week 2 tracking: AUC 0.626, calibration slope 1.006
  week 3 offer   : AUC 0.690, calibration slope 1.002
  week 3 tracking: AUC 0.603, calibration slope 1.007

Nothing needs attention. Win-back keeps the most followers and the lightest weights, because the scoring system already favors its codes. never and always go against the scoring for part of the customers, so their weights reach about 45, but no customer reaches the cap. Their effective sample sizes (the number of equally weighted customers that carry the same information) are about 55% to 60% of their followers, which is healthy.

The offer models separate customers moderately (AUC about 0.69), the tracking models weakly (about 0.61), and every calibration slope sits near the ideal of 1. Both are measured on the fitting rows, so they cannot show the models are right. On your own data, watch for many customers at the cap or an effective sample size of a few percent.

Try to break the result#

These checks change the data in a known way and refit the week-3 effect of a code every week 20 times each. The placebo swaps in random codes, so the estimate should be about zero. The random common cause adds a column of pure noise, so the estimate should barely move. The subset check refits on random 70% samples, whose estimates should spread as the standard error predicts. None of them can detect a hidden cause.

from cleverly.validation import refute

refutation = refute(
    result,
    estimand="ate_regimen[always vs never @ t=3]",
    tests=("placebo", "subset", "random_common_cause"),
    n_replicates=20,
)
columns = ["test", "original", "refuted_mean", "refuted_sd", "expectation", "verdict"]
print(refutation.to_frame()[columns].round(4).to_string(index=False))
print()
for test in refutation.tests:
    if test.statistic_name:
        print(f"{test.name}: {test.statistic_name} = {test.statistic:.4f}")
               test  original  refuted_mean  refuted_sd       expectation     verdict
            placebo    0.0761       -0.0004      0.0186               ~ 0 descriptive
             subset    0.0761        0.0724      0.0122 scatter ~ 0.01526 descriptive
random_common_cause    0.0761        0.0762      0.0009         ~ 0.07614 descriptive

placebo: t = -0.0960
subset: scatter ratio rho = 0.7964
random_common_cause: paired shift in standard errors = 0.0026

None of the three checks raises a concern. The placebo refits average about zero: their t, the average over its own standard error, is -0.10, well inside 2. The noise column barely moves the estimate. The 70% refits spread a little less than predicted (rho 0.80, ideal 1), a gap that 20 refits cannot resolve. descriptive in the verdict column means no simulation study backs a pass or fail here, so you judge the numbers yourself.

What if a confounder is missing?#

A bound would say how strong a hidden cause must be to change the answer; cleverly has none for a repeated outcome, so the code drops one recorded covariate at a time and reports how far each effect moves, in standard errors.

# For your own data, drop each recorded covariate in turn. The earlier orders stay: the
# weekly outcome always enters the record of the next week.
reduced_designs = {
    "without tenure": weekly_design(baseline=("order_0",)),
    "without engagement": weekly_design(engagement=False),
}
rows = []
for label, design in reduced_designs.items():
    reduced = (
        CausalStudy(frame, design=design, protocol=protocol)
        .identify(RegimeContrast(plans, reference="never"))
        .estimate(method=ltmle)
    )
    for key, estimate in result.estimates.items():
        move = reduced[key].psi - estimate.psi
        plan, week = key.removeprefix("ate_regimen[").removesuffix("]").split(" @ t=")
        rows.append(
            {
                "dropped": label,
                "plan": plan.removesuffix(" vs never"),
                "week": int(week),
                "move": move,
                "move_in_se": move / estimate.std_error,
            }
        )
moves = pd.DataFrame(rows).pivot(index=["plan", "week"], columns="dropped", values="move_in_se")
print("move of each effect, in standard errors of the full fit:")
print(moves.round(2).to_string())
move of each effect, in standard errors of the full fit:
dropped        without engagement  without tenure
plan     week                                    
always   1                  -2.28            0.35
         2                  -1.64            0.58
         3                  -1.21            0.83
win_back 1                  -1.89            0.29
         2                  -1.28            0.39
         3                  -0.69            0.80

Dropping engagement moves every effect down, from -0.69 to -2.28 standard errors: engaged customers get fewer codes and order more, so leaving engagement out hides part of the code’s effect. Dropping tenure moves the effects up by at most 0.83. Even the largest move leaves every estimate positive. The comparison gives no bound. A hidden cause as strong as engagement could move the estimates about as far, and someone who knows how the scoring system was built must judge whether one exists.

Details: the sensitivity tools that do not apply here

The simulated hidden-confounder replay shifts or flips an end-of-study outcome, and a weekly outcome is a time-indexed process for which that shift is not defined, so cleverly refuses it for this fit. It refuses the replay for the incremental fit for another reason: no rule yet says how a hidden cause enters the doubled odds. The omitted-variable bound, its robustness value, and the E-value have no derivation for treatments repeated over time, so cleverly refuses them too.

What we can and can’t conclude#

Had every active subscriber stayed tracked, a free-shipping code every week would raise ordering most, fading over the weeks, and add about a third of an order per customer over three weeks. Win-back adds less with fewer codes, and doubling the odds of a code adds little. Whether a policy pays depends on the cost of a code, which these data do not hold.

The intervals cover sampling variation only. They assume that each week’s record holds everything that drove both the code, or tracking loss, and the order, that each code is the declared code, and that one customer’s codes do not change another’s orders. They also need good enough models: for a code every week, the outcome models or the offer and tracking models must be right, and for doubling the odds, the offer and tracking models must be right. The data cannot check the first three conditions, and the weight and model checks only partly check overlap and the models.

This is one simulated sample with a known answer, so it says nothing about real customers or about how the methods perform in general.

Go deeper#

How we know the method works#

Three simulation studies check the methods on this page on other simulated data with three weeks, a weekly 0-or-1 outcome, and tracking loss.

fit on this page

simulation study

what it covers

the weekly curve (LTMLE, all rows)

repeated-outcome longitudinal TMLE

other simulated data: mainly 3,000 rows with the offer and tracking chances known, plus checks at 8,000 rows on all rows with fitted offer and tracking models and logistic outcome models, the closest to this page. Given the same offer and tracking chances, the R package ltmle gives the same estimates on the same simulated data

the curve by SDR

repeated-outcome SDR

other simulated data, with outcome models that average within groups of identical records: five folds at 8,000 rows with fitted offer and tracking models, for week 3. On draws with known offer and tracking chances, it agrees with the R package lmtp

doubling the odds (IPSI)

repeated-outcome IPSI

other simulated data, 8,000 rows, with correct offer and tracking models and outcome models that are right for those data. No other package fits this quantity

None of the studies uses this page’s data or its outcome models, which miss the interaction of two codes in a row and use linear regressions for the earlier weeks. The page’s own simulation checks the numbers this page reports; it does not validate the methods. The technical entry lists the method’s evidence and limits, and its section on repeated outcomes states the estimator.

A second method: sequentially doubly robust estimation#

Sequentially doubly robust estimation (SDR, SDRMethod) estimates the same curve with different weak spots, so a large disagreement would show that one of the two is off. It replaces the correction step with a transform of each week’s target, and it stays on target when, at each week, either that week’s outcome model or that week’s offer and tracking models are right. Here it runs with out-of-fold predictions (five folds), the form its simulation study checks at 8,000 rows. With outcome models that average within groups of identical records, fitted on all rows, the study found the interval too narrow in smaller samples, and it checks that form at 32,000 rows (repeated-outcome SDR).

from cleverly import SDRMethod

sdr_result = effect.estimate(
    method=SDRMethod(
        models=models,
        cross_fitting=CrossFitting(n_folds=5),  # out-of-fold predictions
        runtime=ltmle.runtime,
    )
)
comparison = against_truth(sdr_result)[["estimate", "ci_low", "ci_high", "covers"]]
comparison.insert(0, "ltmle", against_truth(result)["estimate"])
print(comparison.round(3).to_string())
print()
print("support:", sorted({estimate.support.label for estimate in sdr_result.estimates.values()}))
               ltmle  estimate  ci_low  ci_high  covers
plan     week                                          
always   1     0.168     0.168   0.151    0.185    True
         2     0.111     0.110   0.081    0.139    True
         3     0.076     0.074   0.028    0.120    True
win_back 1     0.098     0.098   0.085    0.110    True
         2     0.085     0.085   0.063    0.106    True
         3     0.046     0.045   0.011    0.080   False

support: ['supported']

SDR’s estimates match LTMLE’s to within a few thousandths in every row, and SDR’s intervals hold the same five true values and miss win-back’s week 3, as LTMLE’s do. Both methods read the same models, so in this sample they make the same error. So agreement is reassuring but cannot show both are right.

Details: SDR over 400 draws

In the page’s simulation, SDR’s six intervals held their true values on 374 to 388 of 400 draws.

Where to go next#

The sequential offers example compares three-level offer policies on a single week-4 outcome in the same retailer program, and the sequential pricing example studies a price changed each month. The longitudinal user guide shows how to declare a repeated outcome on your own table. The examples index lists every example.