Skip to content

49. Causal inference, GLMs and advanced experimentation

Prediction answers “what is likely to happen next?” Decision-making asks a harder question: “what happens if we intervene?” Customers who use autopay churn at 16.9%, while customers without autopay churn at 21.9%. Does turning on autopay cause a 5-percentage-point drop in churn, or do stable credit-card customers simply enroll in autopay more often? A predictive model cannot tell those two stories apart. Causal inference and modern experimentation give you the framework and estimators to answer intervention questions reliably.

This module completes the statistical toolkit you started in module 29. You move from classic fixed-horizon A/B tests and OLS to the tools data scientists reach for every week in production: causal diagrams, Sample Ratio Mismatch checks, CUPED variance reduction, multi-armed bandits, propensity score weighting, Difference-in-Differences, Generalized Linear Models for counts and binary outcomes, and Kaplan–Meier survival analysis for customer retention.

  • Define potential outcomes, ATE and ATT, draw causal DAGs to separate confounders, mediators and colliders, and diagnose Simpson’s paradox.
  • Catch broken experiments with Sample Ratio Mismatch (SRM) checks, explain why optional stopping (peeking) inflates false positives, reduce variance with CUPED, and compare fixed A/B tests with multi-armed bandits (epsilon-greedy, UCB1 and Thompson sampling).
  • Estimate causal effects from observational data using propensity scores, Inverse Probability Weighting (IPW) with covariate balance checks, and Difference-in-Differences (DiD) with parallel-trends tests.
  • Fit Generalized Linear Models (GLMs) (logistic, Poisson and Negative Binomial) in statsmodels, diagnose overdispersion and compare models with AIC and BIC.
  • Build Kaplan–Meier retention curves and Greenwood confidence intervals in NumPy and pandas to handle right-censored customer tenure data cleanly.

All runnable Python blocks on this page execute in one session from top to bottom. Start by importing the libraries and fixing display options:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from scipy import stats
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
print("statsmodels", sm.__version__, "| pandas", pd.__version__)
Output
statsmodels 0.15.0 | pandas 3.1.1

For every customer ii and binary intervention Ti∈{0,1}T_i \in \{0, 1\} (for example, Ti=1T_i = 1 means enrolling in autopay, Ti=0T_i = 0 means not enrolling), imagine two potential outcomes:

  • Yi(1)Y_i(1): the outcome customer ii would have if treated.
  • Yi(0)Y_i(0): the outcome customer ii would have if untreated.

Customer ii‘s individual treatment effect is τi=Yi(1)−Yi(0)\tau_i = Y_i(1) - Y_i(0). The fundamental problem of causal inference is that for any single unit at a given time, you observe at most one of the two potential outcomes:

Yi=Ti Yi(1)+(1−Ti) Yi(0)Y_i = T_i \, Y_i(1) + (1 - T_i) \, Y_i(0)

The unobserved outcome is the counterfactual. Because you never see both outcomes for the same customer, you target population averages instead:

  • Average Treatment Effect (ATE): the mean effect across the entire population:
ATE=E[Y(1)−Y(0)]\text{ATE} = \mathbb{E}[Y(1) - Y(0)]
  • Average Treatment Effect on the Treated (ATT): the mean effect specifically among the units that actually received the treatment:
ATT=E[Y(1)−Y(0)∣T=1]\text{ATT} = \mathbb{E}[Y(1) - Y(0) \mid T = 1]

When you take a naive difference in observed group means, E[Y∣T=1]−E[Y∣T=0]\mathbb{E}[Y \mid T=1] - \mathbb{E}[Y \mid T=0], algebra splits it into two pieces:

E[Y∣T=1]−E[Y∣T=0]⏟Observed difference=E[Y(1)−Y(0)∣T=1]⏟ATT+E[Y(0)∣T=1]−E[Y(0)∣T=0]⏟Selection bias\underbrace{\mathbb{E}[Y \mid T=1] - \mathbb{E}[Y \mid T=0]}_{\text{Observed difference}} = \underbrace{\mathbb{E}[Y(1) - Y(0) \mid T=1]}_{\text{ATT}} + \underbrace{\mathbb{E}[Y(0) \mid T=1] - \mathbb{E}[Y(0) \mid T=0]}_{\text{Selection bias}}

Selection bias is the baseline difference between treated and control units that would have existed even without treatment. A randomized experiment sets TT independently of (Y(0),Y(1))(Y(0), Y(1)), which makes selection bias zero on average. In observational data, selection bias is almost never zero.

Three core assumptions let you identify causal effects from data:

Assumption Meaning Violation example
Ignorability (unconfoundedness) (Y(0),Y(1))⊥T∣X(Y(0), Y(1)) \perp T \mid X Unmeasured customer loyalty drives both autopay and retention
Positivity (overlap) 0<P(T=1∣X)<10 \lt P(T = 1 \mid X) \lt 1 for all XX One payment method forbids autopay completely
SUTVA (no interference) One unit’s treatment does not alter another’s outcome Discounting one store cannibalizes a nearby store

Causal DAGs: confounders, mediators and colliders

Section titled “Causal DAGs: confounders, mediators and colliders”

A Directed Acyclic Graph (DAG) is a causal diagram made of nodes (variables) and one-way arrows (direct causal effects) with no feedback cycles. DAGs turn informal domain stories into exact rules for which variables you must adjust for and which variables you must leave alone.

Every three-variable path in a DAG falls into one of three basic structures:

flowchart LR
    subgraph Confounder["1. Confounder (Fork)"]
        Z1["Z (Payment method)"] --> T1["T (Autopay)"]
        Z1 --> Y1["Y (Churn)"]
        T1 --> Y1
    end
    subgraph Mediator["2. Mediator (Chain)"]
        T2["T (New checkout)"] --> M2["M (Page speed)"]
        M2 --> Y2["Y (Conversion)"]
    end
    subgraph Collider["3. Collider (Inverted fork)"]
        T3["T (Marketing spend)"] --> C3["C (High-intent lead)"]
        Y3["Y (Product fit)"] --> C3
    end
  1. A confounder (T←Z→YT \leftarrow Z \rightarrow Y) is a common cause of treatment and outcome. It creates a non-causal backdoor path between TT and YY. Adjusting for ZZ blocks the backdoor path and removes the bias.
  2. A mediator (T→M→YT \rightarrow M \rightarrow Y) sits on the causal pathway from treatment to outcome. If you want the total causal effect of TT on YY, do not adjust for MM — holding the mediator constant strips away the very mechanism by which TT works.
  3. A collider (T→C←YT \rightarrow C \leftarrow Y) is a common effect of two variables. The path T→C←YT \rightarrow C \leftarrow Y is naturally blocked. Adjusting for a collider opens a spurious path between its causes (known as collider bias or Berkson’s paradox).

See the difference in a quick simulation where TT and YY are independent causes of a collider CC, while ZZ confounds TT and YY:

rng = np.random.default_rng(42)
n = 4_000
z = rng.normal(size=n) # confounder
t = 0.8 * z + rng.normal(size=n) # treatment caused by Z
y = 1.5 * t + 1.2 * z + rng.normal(size=n) # true effect of T on Y is 1.5
c = 0.9 * t + 0.9 * y + rng.normal(scale=0.5, size=n) # collider caused by T and Y
sim = pd.DataFrame({"t": t, "y": y, "z": z, "c": c})
for label, formula in [
("Naive (y ~ t)", "y ~ t"),
("Adjust confounder (y ~ t + z)", "y ~ t + z"),
("Bad: adjust collider (y ~ t + z + c)", "y ~ t + z + c"),
]:
coef = smf.ols(formula, data=sim).fit().params["t"]
print(f"{label:<38} estimated effect = {coef:+.3f}")
Output
Naive (y ~ t) estimated effect = +2.070
Adjust confounder (y ~ t + z) estimated effect = +1.496
Bad: adjust collider (y ~ t + z + c) estimated effect = -0.418

Throwing every available column into a regression (“kitchen-sink adjustment”) is dangerous for causal questions. Leaving out the confounder ZZ inflates the estimate from 1.501.50 to about 2.072.07, adjusting for ZZ nails the true 1.501.50, and adding the collider CC wrecks the estimate all the way down to about −0.42-0.42.

Simpson’s paradox happens when a trend or comparison that holds inside every subgroup reverses direction when the subgroups are combined. It is not a mathematical trick — it is confounding in action.

Suppose a product team rolls out a redesigned checkout page gradually: 80% of mobile visitors see the new page, while only 20% of desktop visitors see it. Because desktop converts higher than mobile regardless of page design, the pooled conversion rate makes the better checkout look worse:

rows = [
("desktop", "control", 800, 128),
("desktop", "treatment", 200, 36),
("mobile", "control", 200, 16),
("mobile", "treatment", 800, 80),
]
simp = pd.DataFrame(rows, columns=["device", "group", "visitors", "buyers"])
simp["rate"] = simp["buyers"] / simp["visitors"]
by_device = simp.pivot(index="device", columns="group", values="rate")
by_device["lift"] = by_device["treatment"] - by_device["control"]
pooled = simp.groupby("group")[["buyers", "visitors"]].sum()
pooled["rate"] = pooled["buyers"] / pooled["visitors"]
print(by_device.round(3))
print("\nPooled conversion:")
print(pooled.round(3))
Output
group control treatment lift
device
desktop 0.16 0.18 0.02
mobile 0.08 0.10 0.02
Pooled conversion:
buyers visitors rate
group
control 144 1000 0.144
treatment 116 1000 0.116

Inside desktop, treatment beats control (+2.0 percentage points). Inside mobile, treatment also beats control (+2.0 percentage points). Yet pooled together, treatment trails control (11.6% vs. 14.4%) because device confounded group assignment. To decide whether to trust the pooled number or the segmented number, you always consult the causal DAG: here device causes both group assignment and conversion, so device is a confounder and you must stratify by it.

Experimentation pitfalls: peeking, SRM and novelty effects

Section titled “Experimentation pitfalls: peeking, SRM and novelty effects”

Even a randomized A/B test breaks if you violate its statistical protocol. Three failure modes cause the majority of bad experiment decisions in practice:

  1. Sample Ratio Mismatch (SRM): You configure a 50/50 split, yet at the end of the week control has 5,180 users and treatment has 4,820. A chi-square goodness-of-fit test (stats.chisquare) checks whether the observed counts match the expected ratio. Even a small SRM (say p<0.001p \lt 0.001) means randomization or telemetry is broken — for instance, a buggy redirect dropping mobile users in treatment. Never analyze conversion lift on an experiment with an unresolved SRM.
  2. Optional stopping (peeking): In a fixed-horizon test at α=0.05\alpha = 0.05, the 5% false-positive guarantee holds only if you test once at the planned sample size. Checking the p-value every day and shipping the moment p<0.05p \lt 0.05 gives noise many chances to cross the threshold, inflating the false-positive rate to 20–30% or higher. Solutions include waiting for the pre-registered sample size, using sequential alpha-spending boundaries (such as O’Brien–Fleming), or using always-valid sequential tests.
  3. Novelty and primacy effects: Returning users click a shiny new button out of curiosity (novelty effect) or temporarily stumble over a changed layout (primacy effect). Both fade over 1–2 weeks. Segmenting metrics by new vs. returning users and tracking daily lift over time reveals whether an effect is durable.

Waiting for statistical power costs weeks of engineering time. CUPED (Controlled-experiment Using Pre-Experiment Data) cuts metric variance — and therefore cuts required sample size — by using a pre-experiment covariate XX that correlates with the post-experiment outcome YY.

Because randomization ensures the pre-experiment mean E[X]\mathbb{E}[X] is identical in treatment and control, subtracting θ(Xi−Xˉ)\theta (X_i - \bar{X}) from every user’s outcome leaves the treatment effect unbiased:

Yicuped=Yi−θ(Xi−Xˉ),θ=Cov(Y,X)Var(X)Y_i^{\text{cuped}} = Y_i - \theta (X_i - \bar{X}), \qquad \theta = \frac{\text{Cov}(Y, X)}{\text{Var}(X)}

Computing θ\theta on the pooled sample (ignoring treatment labels) minimizes variance without leaking treatment information. The variance shrinks by a factor of (1−ρ2)(1 - \rho^2), where ρ=Corr(Y,X)\rho = \text{Corr}(Y, X):

Pre/post correlation ρ\rho Variance remaining (1−ρ2)(1 - \rho^2) Sample size saved
0.30 91% 9%
0.50 75% 25%
0.70 51% 49%
0.80 36% 64%

Exploration vs. exploitation: multi-armed bandits

Section titled “Exploration vs. exploitation: multi-armed bandits”

A fixed 50/50 A/B test sends half of all visitors to the losing variant until the experiment ends. When traffic is limited or campaigns are short (flash sales, headline tests, email send-time choices), you may care more about maximizing conversions during the test than about equal-precision estimates of every arm.

A multi-armed bandit shifts traffic dynamically toward arms that perform well while still exploring uncertain arms. Performance is measured by cumulative regret: the total expected reward lost compared to an oracle that knew the best arm from visitor 1:

Regret(T)=∑t=1T(p∗−pat)\text{Regret}(T) = \sum_{t=1}^{T} \left(p^* - p_{a_t}\right)

Three classic bandit algorithms cover most practical needs:

Strategy Selection rule Pros and cons
ε\varepsilon-greedy Pick a random arm with probability ε\varepsilon, else the arm with the highest sample mean Simple, easy to debug; fixed ε\varepsilon keeps wasting traffic forever
UCB1 Pick the arm maximizing p^a+2ln⁡tna\hat{p}_a + \sqrt{\frac{2 \ln t}{n_a}} Deterministic; automatically shrinks exploration as counts nan_a grow
Thompson sampling Sample p~a∼Beta(αa,βa)\tilde{p}_a \sim \text{Beta}(\alpha_a, \beta_a) per arm and pick the largest draw Natural Bayesian uncertainty; strong empirical regret; handles delayed batches well

Thompson sampling connects directly to the Beta–Binomial updating from module 48: start each arm with Beta(1,1)\text{Beta}(1, 1), increment αa\alpha_a on a conversion and βa\beta_a on a non-conversion. Keep in mind the trade-off: bandits reduce regret, but because arm assignment adapts over time, naive p-values and confidence intervals from bandit logs are biased. Use fixed-horizon A/B tests when you need clean long-term inference, guardrail metrics, or regulatory evidence; use bandits when short-lived opportunity cost dominates.

Observational causal methods I: propensity scores, matching and IPW

Section titled “Observational causal methods I: propensity scores, matching and IPW”

Often you cannot randomize: you cannot force half your customers onto a two-year contract or randomly deny autopay. Instead, you observe who chose treatment (T=1T=1) and who did not (T=0T=0), along with pre-treatment covariates XX.

The propensity score is the probability of receiving treatment given covariates:

e(X)=P(T=1∣X)e(X) = P(T = 1 \mid X)

Rosenbaum and Rubin’s central theorem shows that if ignorability holds given the full vector XX, it also holds given the single scalar e(X)e(X). That turns a high-dimensional adjustment problem into a 1D score, used in three ways:

  1. Propensity score matching: pair each treated unit with the control unit(s) having the closest propensity score (usually within a maximum distance called a caliper). Matching estimates the ATT cleanly and discards units outside the region of common support.
  2. Inverse Probability Weighting (IPW): keep all units and reweight them to build a balanced “pseudo-population” where treatment is independent of XX. Treated units get weight wi=1/e^(Xi)w_i = 1 / \hat{e}(X_i) and control units get weight wi=1/(1−e^(Xi))w_i = 1 / (1 - \hat{e}(X_i)). In practice, always use the normalized Hájek IPW estimator, which stabilizes variance by dividing by the sum of weights in each group:
ATE^IPW=∑i:Ti=1Yie^(Xi)∑i:Ti=11e^(Xi)−∑i:Ti=0Yi1−e^(Xi)∑i:Ti=011−e^(Xi)\widehat{\text{ATE}}_{\text{IPW}} = \frac{\sum_{i: T_i=1} \frac{Y_i}{\hat{e}(X_i)}}{\sum_{i: T_i=1} \frac{1}{\hat{e}(X_i)}} - \frac{\sum_{i: T_i=0} \frac{Y_i}{1 - \hat{e}(X_i)}}{\sum_{i: T_i=0} \frac{1}{1 - \hat{e}(X_i)}}
  1. Doubly robust estimation (AIPW): combines an outcome regression model μ^t(X)\hat{\mu}_t(X) with IPW weights. It remains consistent if either the propensity model or the outcome model is correctly specified.

After weighting or matching, you always check covariate balance using the Standardized Mean Difference (SMD) for every confounder:

SMD=xˉ1−xˉ0(s12+s02)/2\text{SMD} = \frac{\bar{x}_1 - \bar{x}_0}{\sqrt{(s_1^2 + s_0^2) / 2}}

A common rule of thumb is ∣SMD∣<0.10|\text{SMD}| \lt 0.10 for every covariate after weighting. If a covariate still has large imbalance, refine the propensity model (add interactions or nonlinear terms) or check whether positivity is violated (e^(X)\hat{e}(X) near 0 or 1).

Observational causal methods II: Difference-in-Differences (DiD)

Section titled “Observational causal methods II: Difference-in-Differences (DiD)”

What if treated and control groups differ in unobserved, time-invariant ways — for example, one region is permanently wealthier than another? Propensity scores only adjust for observed confounders. Difference-in-Differences (DiD) handles time-invariant unobserved confounding by comparing changes over time instead of raw levels.

Suppose a treated group (D=1D=1) receives an intervention in the post-period (P=1P=1), while a control group (D=0D=0) never receives it:

DiD^=(YˉD=1,P=1−YˉD=1,P=0)−(YˉD=0,P=1−YˉD=0,P=0)\widehat{\text{DiD}} = \left(\bar{Y}_{D=1, P=1} - \bar{Y}_{D=1, P=0}\right) - \left(\bar{Y}_{D=0, P=1} - \bar{Y}_{D=0, P=0}\right)

Equivalently, fit an OLS regression with an interaction term:

Yit=β0+β1Di+β2Pt+δ(Di×Pt)+εitY_{it} = \beta_0 + \beta_1 D_i + \beta_2 P_t + \delta (D_i \times P_t) + \varepsilon_{it}

Here β1\beta_1 absorbs permanent baseline differences between groups, β2\beta_2 absorbs common time shocks (seasonality, market-wide growth), and the interaction coefficient δ\delta is the exact DiD causal effect.

DiD relies on the parallel trends assumption: in the absence of treatment, the treated and control groups would have moved along parallel trajectories from the pre-period to the post-period. You can never prove the unobserved post-period counterfactual, so you test its credibility by checking pre-treatment periods (plotting both series and testing whether the pre-period group-by-time slope interaction is near zero).

Generalized Linear Models (GLMs) in statsmodels

Section titled “Generalized Linear Models (GLMs) in statsmodels”

Ordinary Least Squares assumes the outcome is continuous, unbounded and has constant error variance. Real business targets often violate all three:

  • churned is binary (00 or 11): OLS can predict probabilities below 00 or above 11.
  • support_tickets and daily orders are non-negative integers (0,1,2,…0, 1, 2, \dots) whose variance grows with the mean.
  • Buyer revenue is strictly positive and heavily right-skewed.

A Generalized Linear Model (GLM) generalizes linear regression with two ingredients:

  1. A random component (family) from the exponential family specifying the conditional distribution of Y∣XY \mid X and its mean–variance relationship.
  2. A link function g(⋅)g(\cdot) mapping the expected value μ=E[Y∣X]\mu = \mathbb{E}[Y \mid X] onto the unbounded linear predictor η=Xβ\eta = X\beta:
g(μ)=β0+β1x1+⋯+βpxpg(\mu) = \beta_0 + \beta_1 x_1 + \dots + \beta_p x_p
Outcome type GLM family Canonical / standard link Interpreting exp⁡(βj)\exp(\beta_j)
Continuous, symmetric Gaussian Identity: μ=η\mu = \eta Additive change βj\beta_j (identical to OLS)
Binary (0/1) Binomial Logit: ln⁡μ1−μ=η\ln\frac{\mu}{1-\mu} = \eta Odds ratio per 1-unit increase in xjx_j
Counts (variance ≈\approx mean) Poisson Log: ln⁡(μ)=η\ln(\mu) = \eta Incidence rate ratio (IRR) per 1-unit increase
Overdispersed counts Negative Binomial Log: ln⁡(μ)=η\ln(\mu) = \eta Incidence rate ratio (IRR) with extra variance μ+αμ2\mu + \alpha \mu^2
Positive skewed amounts Gamma Log: ln⁡(μ)=η\ln(\mu) = \eta Multiplicative factor on mean amount

For count data, always check overdispersion: in a Poisson model, Var(Y∣X)=μ\text{Var}(Y \mid X) = \mu, so the ratio Pearson χ2/dfresid\text{Pearson }\chi^2 / \text{df}_{\text{resid}} (or deviance/dfresid\text{deviance} / \text{df}_{\text{resid}}) should sit near 1.01.0. When it is much larger than 11, Poisson standard errors are too narrow and p-values are artificially small. Switching to a Negative Binomial model adds a dispersion parameter α>0\alpha \gt 0 so Var(Y∣X)=μ+αμ2\text{Var}(Y \mid X) = \mu + \alpha \mu^2, and you compare candidate models using AIC and BIC (lower is better).

Survival analysis and censoring: Kaplan–Meier and hazard rates

Section titled “Survival analysis and censoring: Kaplan–Meier and hazard rates”

Suppose you want to estimate how long subscription customers stay before churning. In data/customers.csv, 4,037 of 5,000 customers are still active on the snapshot date 2024-12-31. Their true churn times have not happened yet — you only know that each active customer survived at least as long as their current tenure_months. This is right censoring.

If you drop active customers and average only the churners’ tenures, you throw away your longest-lived customers and badly underestimate retention. If you treat censored tenure as if those customers churned today, you also underestimate retention. Survival analysis uses every customer’s observed time without bias.

Define two core functions of time tt:

  • Survival function S(t)=P(T>t)S(t) = P(T \gt t): the probability a customer is still active past month tt.
  • Hazard rate h(t)h(t): the instantaneous risk of churning at time tt given survival up to tt.

The Kaplan–Meier estimator computes S^(t)\hat{S}(t) non-parametrically from observed event times t1<t2<⋯<tkt_1 \lt t_2 \lt \dots \lt t_k. At each event time tjt_j, let njn_j be the number of customers still at risk (tenure ≥tj\ge t_j, neither churned nor censored before tjt_j) and djd_j be the number who churned at tjt_j:

S^(t)=∏tj≤t(1−djnj)\hat{S}(t) = \prod_{t_j \le t} \left(1 - \frac{d_j}{n_j}\right)

Censored customers contribute to the denominator njn_j at every time step up to their observed tenure, then leave the risk set cleanly without counting as an event. Uncertainty is quantified by Greenwood’s formula for the variance of S^(t)\hat{S}(t):

Var^(S^(t))=S^(t)2∑tj≤tdjnj(nj−dj)\widehat{\text{Var}}(\hat{S}(t)) = \hat{S}(t)^2 \sum_{t_j \le t} \frac{d_j}{n_j (n_j - d_j)}

Example 1 — Detect Sample Ratio Mismatch and simulate the peeking trap

Section titled “Example 1 — Detect Sample Ratio Mismatch and simulate the peeking trap”

Goal: Audit data/ab_test.csv for Sample Ratio Mismatch, then simulate sequential peeking under a true null to measure how quickly false positives balloon.

Run a chi-square goodness-of-fit test against the planned 50/50 split on the real checkout experiment, and compare it with a broken experiment that drops 5% of treatment users.

ab = pd.read_csv("data/ab_test.csv")
counts = ab["group"].value_counts().sort_index()
n_total = int(counts.sum())
srm_ok = stats.chisquare(counts.to_numpy(), f_exp=[n_total / 2, n_total / 2])
# Contrast with a broken 50/50 split that silently drops 5% of treatment logs
broken = np.array([5000, 4750])
srm_bad = stats.chisquare(broken, f_exp=[broken.sum() / 2, broken.sum() / 2])
print(
f"ab_test.csv counts: control={counts['control']}, "
f"treatment={counts['treatment']}"
)
print(f"SRM check (ab_test): chi2={srm_ok.statistic:.4f}, p={srm_ok.pvalue:.4f}")
print(f"SRM check (broken): chi2={srm_bad.statistic:.2f}, p={srm_bad.pvalue:.2e}")
Output
ab_test.csv counts: control=5002, treatment=4998
SRM check (ab_test): chi2=0.0016, p=0.9681
SRM check (broken): chi2=6.41, p=1.13e-02

data/ab_test.csv passes the SRM check cleanly (p=0.9681p = 0.9681). By contrast, losing just 5% of treatment telemetry yields p≈0.011p \approx 0.011 (and with larger traffic, p<10−6p \lt 10^{-6}), flagging a logging or randomization bug immediately before anyone trusts the conversion numbers.

Step 2 — Simulate the peeking false-positive trap

Section titled “Step 2 — Simulate the peeking false-positive trap”

Generate 1,000 A/A experiments where control and treatment have the exact same true conversion rate (p0=0.10p_0 = 0.10) and total sample size N=2,000N = 2{,}000 per arm. Measure the false-positive rate when you peek 1, 2, 5, 10, 20 or 40 evenly spaced times and stop early whenever two-sided p<0.05p \lt 0.05.

rng = np.random.default_rng(42)
n_sims, n_per_arm, p0 = 1_000, 2_000, 0.10
ctrl = rng.binomial(1, p0, size=(n_sims, n_per_arm)).cumsum(axis=1)
trt = rng.binomial(1, p0, size=(n_sims, n_per_arm)).cumsum(axis=1)
look_counts = [1, 2, 5, 10, 20, 40]
fprs = []
for k in look_counts:
checkpoints = np.linspace(n_per_arm // k, n_per_arm, k, dtype=int)
rejected = np.zeros(n_sims, dtype=bool)
for n_now in checkpoints:
c_now = ctrl[:, n_now - 1]
t_now = trt[:, n_now - 1]
p_pool = (c_now + t_now) / (2 * n_now)
se = np.sqrt(np.maximum(2 * p_pool * (1 - p_pool) / n_now, 1e-12))
z = np.abs((t_now - c_now) / n_now) / se
rejected |= z > stats.norm.ppf(0.975)
fprs.append(float(rejected.mean()))
print(f"peeks = {k:>2d} | false-positive rate = {rejected.mean():.3f}")
Output
peeks = 1 | false-positive rate = 0.039
peeks = 2 | false-positive rate = 0.069
peeks = 5 | false-positive rate = 0.136
peeks = 10 | false-positive rate = 0.183
peeks = 20 | false-positive rate = 0.236
peeks = 40 | false-positive rate = 0.295

With 1 look at the end, the false-positive rate sits near the nominal 5%. Peeking 20 times pushes the false-positive rate above 23%, and peeking 40 times nears 30% — almost six times the advertised α=0.05\alpha = 0.05.

Step 3 — Plot false-positive inflation against number of peeks

Section titled “Step 3 — Plot false-positive inflation against number of peeks”
fig, ax = plt.subplots(figsize=(6.5, 3.8))
ax.plot(look_counts, [100 * f for f in fprs], marker="o", linewidth=2, color="#d95f02")
ax.axhline(5.0, linestyle="--", color="#555555", label="Nominal 5% alpha")
ax.set_xlabel("Number of interim peeks")
ax.set_ylabel("False-positive rate (%)")
ax.set_title("Peeking inflates false positives under a true null (1,000 A/A sims)")
ax.set_ylim(0, 35)
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
Line chart showing false-positive rate rising from about 5 percent at 1 peek to over 25 percent at 40 peeks under a true null.
Optional stopping rapidly inflates the false-positive rate above the 5% target.

Common mistakes:

  • Running an SRM check with alpha = 0.05 on dozens of experiments without investigating borderline cases; most experimentation platforms alert at p<0.001p \lt 0.001 or p<0.01p \lt 0.01 and block shipping until root-caused.
  • Calling a test “statistically significant” after watching a live dashboard cross p<0.05p \lt 0.05 mid-week.

Example 2 — Cut experiment variance in half with CUPED

Section titled “Example 2 — Cut experiment variance in half with CUPED”

Goal: Use customers’ real 2023 order counts from data/sales.csv as a pre-experiment covariate XX to shrink the standard error of a simulated 2024 loyalty-program experiment.

Step 1 — Build the pre/post customer panel

Section titled “Step 1 — Build the pre/post customer panel”

Select customers who signed up before July 2023 so every customer has a full pre-period (2023) and post-period (2024) history, then measure the pre/post correlation ρ\rho.

customers = pd.read_csv("data/customers.csv")
sales = pd.read_csv("data/sales.csv")
sales["year"] = pd.to_datetime(sales["order_date"]).dt.year
eligible = customers.loc[customers["signup_date"] < "2023-07-01", "customer_id"]
orders_by_yr = (
sales.groupby(["customer_id", "year"])["order_id"]
.nunique()
.unstack(fill_value=0)
.reindex(eligible, fill_value=0)
)
x_pre = orders_by_yr[2023].to_numpy(dtype=float)
y_base = orders_by_yr[2024].to_numpy(dtype=float)
rho = float(np.corrcoef(x_pre, y_base)[0, 1])
print(f"eligible customers: {len(eligible):,}")
print(
f"pre/post correlation rho = {rho:.3f} "
f"(theoretical var reduction = {rho**2:.1%})"
)
Output
eligible customers: 2,458
pre/post correlation rho = 0.738 (theoretical var reduction = 54.4%)

A customer’s 2023 order count correlates strongly (ρ≈0.74\rho \approx 0.74) with their 2024 order count. Theory predicts CUPED will eliminate roughly ρ2≈54%\rho^2 \approx 54\% of the outcome variance.

Step 2 — Run a randomized experiment and compare raw vs. CUPED estimates

Section titled “Step 2 — Run a randomized experiment and compare raw vs. CUPED estimates”

Randomly assign half the eligible customers to treatment and inject a modest true lift of +0.25 orders per customer in 2024. Compare Welch’s two-sample t-test on raw YY against CUPED-adjusted YcupedY_{\text{cuped}}.

rng = np.random.default_rng(42)
treat = rng.binomial(1, 0.5, size=len(eligible))
y_obs = y_base + 0.25 * treat
# Pooled theta (computed without looking at treatment labels)
theta = np.cov(y_obs, x_pre, ddof=1)[0, 1] / np.var(x_pre, ddof=1)
y_cuped = y_obs - theta * (x_pre - x_pre.mean())
def summarize_diff(y: np.ndarray, t: np.ndarray, name: str) -> tuple[float, float]:
y1, y0 = y[t == 1], y[t == 0]
diff = float(y1.mean() - y0.mean())
se = float(np.sqrt(y1.var(ddof=1) / len(y1) + y0.var(ddof=1) / len(y0)))
pval = float(stats.ttest_ind(y1, y0, equal_var=False).pvalue)
print(f"{name:<6} diff={diff:+.3f} SE={se:.4f} p={pval:.4f}")
return diff, se
_, se_raw = summarize_diff(y_obs, treat, "Raw")
_, se_cuped = summarize_diff(y_cuped, treat, "CUPED")
var_reduction = 1.0 - (se_cuped / se_raw) ** 2
print(f"theta = {theta:.3f} | empirical variance reduction = {var_reduction:.1%}")
Output
Raw diff=+0.212 SE=0.1054 p=0.0442
CUPED diff=+0.335 SE=0.0712 p=0.0000
theta = 0.607 | empirical variance reduction = 54.3%

Look at what happened: the raw t-test has a wide standard error (SE = 0.1054) and barely crosses p = 0.05 (p = 0.0442) because customer-to-customer spending heterogeneity adds heavy noise. CUPED cuts the variance by 54.3%, drops the standard error to 0.0712, drives p<0.0001p \lt 0.0001, and delivers the equivalent of more than double the sample size at zero extra traffic cost.

Common mistakes:

  • Fitting a separate θ\theta inside treatment and control, which can introduce small-sample bias; always estimate one pooled θ\theta across all users (or use cross-fitting).
  • Using a variable measured after randomization as XX, which absorbs part of the treatment effect.

Example 3 — Compare Thompson sampling against a fixed A/B test

Section titled “Example 3 — Compare Thompson sampling against a fixed A/B test”

Goal: Simulate 5,000 checkout visitors choosing among 3 variants with true conversion rates [0.06, 0.10, 0.14], averaging over 15 independent trials to compare a fixed uniform 3-way A/B test, ε\varepsilon-greedy, UCB1 and Thompson sampling on cumulative regret and total conversions.

Step 1 — Implement the four allocation strategies

Section titled “Step 1 — Implement the four allocation strategies”
true_rates = np.array([0.06, 0.10, 0.14])
best_rate = float(true_rates.max())
n_visitors, n_arms, n_trials = 5_000, len(true_rates), 15
def run_bandit(strategy: str, seed: int) -> tuple[np.ndarray, np.ndarray, int]:
rng = np.random.default_rng(seed)
pulls = np.zeros(n_arms, dtype=int)
wins = np.zeros(n_arms, dtype=int)
regret = np.zeros(n_visitors, dtype=float)
cum_regret = 0.0
for t in range(1, n_visitors + 1):
if strategy == "fixed_ab":
arm = (t - 1) % n_arms
elif strategy == "eps_greedy":
if t <= n_arms:
arm = t - 1
elif rng.random() < 0.10:
arm = int(rng.integers(n_arms))
else:
arm = int(np.argmax(wins / pulls))
elif strategy == "ucb1":
if t <= n_arms:
arm = t - 1
else:
ucb = (wins / pulls) + np.sqrt(2.0 * np.log(t) / pulls)
arm = int(np.argmax(ucb))
elif strategy == "thompson":
samples = rng.beta(1 + wins, 1 + pulls - wins)
arm = int(np.argmax(samples))
else:
raise ValueError(f"Unknown strategy: {strategy}")
reward = int(rng.random() < true_rates[arm])
pulls[arm] += 1
wins[arm] += reward
cum_regret += best_rate - true_rates[arm]
regret[t - 1] = cum_regret
return regret, pulls, int(wins.sum())
results = {}
for name in ["fixed_ab", "eps_greedy", "ucb1", "thompson"]:
runs = [run_bandit(name, seed=42 + s) for s in range(n_trials)]
mean_reg = np.mean([r[0] for r in runs], axis=0)
mean_pulls = np.round(np.mean([r[1] for r in runs], axis=0)).astype(int)
mean_conv = float(np.mean([r[2] for r in runs]))
results[name] = (mean_reg, mean_pulls, mean_conv)
print(
f"{name:<11} conv={mean_conv:>5.1f} regret={mean_reg[-1]:>5.1f} "
f"pulls={mean_pulls.tolist()}"
)
Output
fixed_ab conv=498.9 regret=200.0 pulls=[1667, 1667, 1666]
eps_greedy conv=657.3 regret= 43.6 pulls=[274, 541, 4184]
ucb1 conv=591.4 regret=108.7 pulls=[690, 1339, 2972]
thompson conv=671.7 regret= 25.2 pulls=[124, 382, 4494]

A fixed 3-way A/B test keeps sending two-thirds of all traffic to inferior variants, accumulating 200 lost conversions of expected regret. Thompson sampling concentrates nearly 90% of visitors onto the 14% winner, cutting regret by 87% relative to fixed A/B and gaining over 170 additional conversions.

fig, ax = plt.subplots(figsize=(6.8, 3.8))
styles = {
"fixed_ab": ("Fixed 3-way A/B", "#7570b3", "--"),
"eps_greedy": ("Epsilon-greedy (0.10)", "#d95f02", "-."),
"ucb1": ("UCB1", "#e7298a", ":"),
"thompson": ("Thompson sampling", "#1b9e77", "-"),
}
for name, (label, color, ls) in styles.items():
ax.plot(results[name][0], label=label, color=color, linestyle=ls, linewidth=2)
ax.set_xlabel("Visitors")
ax.set_ylabel("Mean cumulative regret (conversions)")
ax.set_title("Cumulative regret across 5,000 visitors (rates 6%, 10%, 14%)")
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
Four lines showing mean cumulative regret over 5,000 visitors: fixed A/B rises linearly to 200, UCB1 reaches 109, epsilon-greedy reaches 44, and Thompson sampling flattens near 25.
Thompson sampling bends the regret curve quickly by shifting traffic to the winning variant.

Common mistakes:

  • Reading a standard two-proportion p-value straight off Thompson sampling logs; adaptive sampling breaks fixed-sample p-value calibration.
  • Forgetting warm-up pulls in UCB1 or ε\varepsilon-greedy, causing division by zero when pulls == 0.

Example 4 — Estimate the causal effect of autopay on churn with IPW

Section titled “Example 4 — Estimate the causal effect of autopay on churn with IPW”

Goal: Estimate whether has_autopay causally reduces churn in data/customers.csv after adjusting for observed confounders (payment_method, contract, plan, region, age, tenure_months, monthly_charges) using propensity score IPW.

Step 1 — Inspect the naive gap and confounding by payment method

Section titled “Step 1 — Inspect the naive gap and confounding by payment method”
naive_rates = customers.groupby("has_autopay")["churned"].mean()
naive_diff = float(naive_rates.loc[1] - naive_rates.loc[0])
autopay_by_pay = (
customers.groupby("payment_method")["has_autopay"]
.agg(["count", "mean"])
.rename(columns={"mean": "autopay_rate"})
)
autopay_by_pay["churn_rate"] = customers.groupby("payment_method")["churned"].mean()
print(f"Naive churn diff (autopay=1 minus autopay=0): {naive_diff:+.4f}")
print()
print(autopay_by_pay.round(3))
Output
Naive churn diff (autopay=1 minus autopay=0): -0.0493
count autopay_rate churn_rate
payment_method
bank_transfer 1209 0.805 0.174
credit_card 1360 0.756 0.158
electronic_check 1563 0.160 0.248
paypal 868 0.454 0.174

Customers using electronic_check have both the lowest autopay enrollment (16.0%) and the highest churn rate (24.8%). That makes payment_method a classic confounder: it pulls down the apparent churn rate of the autopay group even if autopay itself had a smaller effect.

Step 2 — Fit the propensity model, check overlap and compute Hájek IPW

Section titled “Step 2 — Fit the propensity model, check overlap and compute Hájek IPW”

Exclude post-treatment behavioral signals (support_tickets, logins_last_30d, avg_session_minutes) that could act as mediators or colliders, and estimate propensity scores from baseline account attributes only.

cat_cols = ["payment_method", "contract", "plan", "region"]
num_cols = ["age", "tenure_months", "monthly_charges"]
X_conf = customers[cat_cols + num_cols]
t_auto = customers["has_autopay"].to_numpy()
y_churn = customers["churned"].to_numpy()
pre = ColumnTransformer(
[
("cat", OneHotEncoder(drop="first", sparse_output=False), cat_cols),
("num", StandardScaler(), num_cols),
]
)
ps_pipe = make_pipeline(pre, LogisticRegression(max_iter=1000))
ps_pipe.fit(X_conf, t_auto)
ps = ps_pipe.predict_proba(X_conf)[:, 1]
def hajek_ipw(y: np.ndarray, t: np.ndarray, e: np.ndarray) -> float:
w1 = t / e
w0 = (1 - t) / (1 - e)
return float(np.sum(w1 * y) / np.sum(w1) - np.sum(w0 * y) / np.sum(w0))
ate_ipw = hajek_ipw(y_churn, t_auto, ps)
ols_adj = smf.ols(
"churned ~ has_autopay + C(payment_method) + C(contract) + C(plan)"
" + C(region) + age + tenure_months + monthly_charges",
data=customers,
).fit(cov_type="HC3")
print(f"Propensity score range: [{ps.min():.3f}, {ps.max():.3f}]")
print(f"Naive difference: {naive_diff:+.4f}")
print(f"Hajek IPW ATE: {ate_ipw:+.4f}")
print(
f"OLS adjusted coef: {ols_adj.params['has_autopay']:+.4f} "
f"(HC3 SE={ols_adj.bse['has_autopay']:.4f}, p={ols_adj.pvalues['has_autopay']:.4f})"
)
Output
Propensity score range: [0.087, 0.879]
Naive difference: -0.0493
Hajek IPW ATE: -0.0272
OLS adjusted coef: -0.0213 (HC3 SE=0.0124, p=0.0860)

Overlap is healthy (e^(X)∈[0.087,0.879]\hat{e}(X) \in [0.087, 0.879], nowhere near 0 or 1). Once we adjust for confounders, the estimated autopay effect shrinks almost in half — from -4.93 percentage points naive to -2.72 percentage points under Hájek IPW (and -2.13 pp under OLS adjustment).

Step 3 — Check covariate balance (SMD) and bootstrap a 95% CI

Section titled “Step 3 — Check covariate balance (SMD) and bootstrap a 95% CI”

Compute the Standardized Mean Difference before and after IPW across all encoded confounders, then run a 200-replicate paired bootstrap (refitting the propensity score inside each replicate) for a 95% confidence interval.

X_design = pre.transform(X_conf)
feat_names = [
name.split("__", 1)[1] for name in pre.get_feature_names_out()
]
weights = np.where(t_auto == 1, 1.0 / ps, 1.0 / (1.0 - ps))
def smd_vector(
X_mat: np.ndarray, t: np.ndarray, w: np.ndarray | None = None
) -> np.ndarray:
m1 = t == 1
m0 = t == 0
if w is None:
mu1, mu0 = X_mat[m1].mean(axis=0), X_mat[m0].mean(axis=0)
v1, v0 = X_mat[m1].var(axis=0, ddof=1), X_mat[m0].var(axis=0, ddof=1)
else:
w1, w0 = w[m1], w[m0]
mu1 = np.average(X_mat[m1], axis=0, weights=w1)
mu0 = np.average(X_mat[m0], axis=0, weights=w0)
v1 = np.average((X_mat[m1] - mu1) ** 2, axis=0, weights=w1)
v0 = np.average((X_mat[m0] - mu0) ** 2, axis=0, weights=w0)
return (mu1 - mu0) / np.sqrt(0.5 * (v1 + v0))
smd_raw = np.abs(smd_vector(X_design, t_auto))
smd_ipw = np.abs(smd_vector(X_design, t_auto, weights))
balance = pd.DataFrame(
{"raw_abs_smd": smd_raw, "ipw_abs_smd": smd_ipw}, index=feat_names
).sort_values("raw_abs_smd", ascending=False)
print(balance.head(5).round(4))
print(f"Max |SMD| raw: {smd_raw.max():.4f} -> after IPW: {smd_ipw.max():.4f}")
rng = np.random.default_rng(42)
boot_ates = []
n_rows = len(customers)
for _ in range(200):
idx = rng.integers(0, n_rows, size=n_rows)
lr = LogisticRegression(max_iter=1000).fit(X_design[idx], t_auto[idx])
e_b = np.clip(lr.predict_proba(X_design[idx])[:, 1], 0.02, 0.98)
boot_ates.append(hajek_ipw(y_churn[idx], t_auto[idx], e_b))
ci_lo, ci_hi = np.percentile(boot_ates, [2.5, 97.5])
print(f"IPW 95% bootstrap CI: [{ci_lo:+.4f}, {ci_hi:+.4f}]")
Output
raw_abs_smd ipw_abs_smd
payment_method_electronic_check 1.136 0.009
payment_method_credit_card 0.585 0.003
payment_method_paypal 0.138 0.002
age 0.075 0.014
plan_standard 0.068 0.004
Max |SMD| raw: 1.1357 -> after IPW: 0.0137
IPW 95% bootstrap CI: [-0.0539, -0.0024]

IPW collapses the massive electronic_check imbalance from |SMD| = 1.14 down below 0.01, bringing every single confounder well under the 0.10 balance threshold.

Step 4 — Plot propensity overlap and covariate balance

Section titled “Step 4 — Plot propensity overlap and covariate balance”
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.0, 3.8))
ax1.hist(
ps[t_auto == 0],
bins=25,
alpha=0.6,
density=True,
label="No autopay",
color="#d95f02",
)
ax1.hist(
ps[t_auto == 1],
bins=25,
alpha=0.6,
density=True,
label="Autopay",
color="#1b9e77",
)
ax1.set_xlabel("Estimated propensity score P(autopay=1 | X)")
ax1.set_ylabel("Density")
ax1.set_title("Propensity score overlap")
ax1.legend()
ax1.grid(alpha=0.25)
top_bal = balance.head(7).iloc[::-1]
y_pos = np.arange(len(top_bal))
ax2.scatter(top_bal["raw_abs_smd"], y_pos, label="Unweighted", color="#d95f02", s=50)
ax2.scatter(
top_bal["ipw_abs_smd"], y_pos, label="IPW", color="#1b9e77", s=50, marker="s"
)
ax2.axvline(0.10, linestyle="--", color="#555555", label="0.10 threshold")
ax2.set_yticks(y_pos)
ax2.set_yticklabels(top_bal.index, fontsize=8)
ax2.set_xlabel("Absolute Standardized Mean Difference")
ax2.set_title("Covariate balance (Love plot)")
ax2.legend(fontsize=8)
ax2.grid(alpha=0.25)
fig.tight_layout()
plt.show()
Two-panel chart: left shows overlapping histograms of propensity scores for autopay vs non-autopay; right shows a Love plot where IPW reduces all standardized mean differences from up to 1.14 to near zero.
Propensity overlap is well-supported and IPW eliminates observed covariate imbalance.

Common mistakes:

  • Including post-treatment outcomes or mediators in the propensity model.
  • Using unnormalized Horvitz–Thompson weights when propensity scores approach 0 or 1, which explodes variance; always inspect overlap and use Hájek weights (plus trimming if needed).

Example 5 — Measure campaign and store-opening impact with Difference-in-Differences

Section titled “Example 5 — Measure campaign and store-opening impact with Difference-in-Differences”

Goal: Use Difference-in-Differences with parallel-trends checks on two real business questions: (a) how many daily signups the April 2024 marketing campaign added in data/web_traffic.csv, and (b) whether opening store S12 in Denver on 2023-06-15 lifted total West-region orders in data/sales.csv.

Step 1 — Estimate the April 2024 marketing campaign lift on data/web_traffic.csv

Section titled “Step 1 — Estimate the April 2024 marketing campaign lift on data/web_traffic.csv”

A major marketing campaign starts on Monday 2024-04-08 (ISO week 15 of 2024). Use ISO week 14 as the pre-period, ISO week 15 as the post-period, and the same calendar weeks in 2023 (when no April campaign ran) as the seasonal control group. First test parallel trends on weeks 13 → 14.

wt = pd.read_csv("data/web_traffic.csv")
wt["date"] = pd.to_datetime(wt["date"])
wt["year"] = wt["date"].dt.year
wt["iso_week"] = wt["date"].dt.isocalendar().week.astype(int)
sub = wt[wt["year"].isin([2023, 2024]) & wt["iso_week"].isin([13, 14, 15])].copy()
sub["treated"] = (sub["year"] == 2024).astype(int)
# Parallel trends check: week 13 -> week 14 (both pre-campaign)
pre_wt = sub[sub["iso_week"].isin([13, 14])].copy()
pre_wt["w14"] = (pre_wt["iso_week"] == 14).astype(int)
pt_wt = smf.ols("signups ~ treated * w14", data=pre_wt).fit(cov_type="HC3")
# DiD: week 14 (pre) -> week 15 (campaign)
did_wt_df = sub[sub["iso_week"].isin([14, 15])].copy()
did_wt_df["post"] = (did_wt_df["iso_week"] == 15).astype(int)
did_wt = smf.ols("signups ~ treated * post", data=did_wt_df).fit(cov_type="HC3")
print("Mean daily signups (row=treated 2024, col=post week 15):")
print(did_wt_df.pivot_table(index="treated", columns="post", values="signups").round(2))
print(
f"Pre-trend check (w13->w14): diff={pt_wt.params['treated:w14']:+.2f}, "
f"p={pt_wt.pvalues['treated:w14']:.4f}"
)
print(
f"Campaign DiD lift: {did_wt.params['treated:post']:+.2f} signups/day "
f"(SE={did_wt.bse['treated:post']:.2f}, p={did_wt.pvalues['treated:post']:.4f})"
)
Output
Mean daily signups (row=treated 2024, col=post week 15):
post 0 1
treated
0 58.43 56.86
1 77.14 206.00
Pre-trend check (w13->w14): diff=+3.00, p=0.7383
Campaign DiD lift: +130.43 signups/day (SE=44.14, p=0.0031)

In the pre-period, 2024 and 2023 moved in lockstep (slope difference +3.0 signups/day, p=0.74p = 0.74), supporting parallel trends. Once the campaign launched in week 15, daily signups jumped by +130.4 above what the 2023 seasonal control predicts (p=0.0031p = 0.0031).

Step 2 — Check net regional lift vs. cannibalization when store S12 opened

Section titled “Step 2 — Check net regional lift vs. cannibalization when store S12 opened”

Store S12 (Denver, West region) opened on 2023-06-15. Compare daily orders in the West region (west = 1) against the other three regions (west = 0) over the 90 days before and 90 days after the opening.

sales["order_date"] = pd.to_datetime(sales["order_date"])
daily_reg = (
sales.groupby(["order_date", "region"])["order_id"]
.nunique()
.reset_index(name="orders")
)
win = daily_reg[
(daily_reg["order_date"] >= "2023-03-17")
& (daily_reg["order_date"] <= "2023-09-12")
].copy()
win["west"] = (win["region"] == "West").astype(int)
win["post"] = (win["order_date"] >= "2023-06-15").astype(int)
pre_s = win[win["post"] == 0].copy()
pre_s["day"] = (pre_s["order_date"] - pre_s["order_date"].min()).dt.days
pt_s = smf.ols("orders ~ west * day", data=pre_s).fit(cov_type="HC3")
did_s = smf.ols("orders ~ west * post", data=win).fit(cov_type="HC3")
s12_orders = sales.loc[
(sales["store_id"] == "S12") & (sales["order_date"] <= "2023-09-12"), "order_id"
].nunique()
print(f"Orders processed by new store S12 in first 90 days: {s12_orders}")
print(f"Pre-trend check (West vs others): p={pt_s.pvalues['west:day']:.4f}")
print(
f"West net DiD lift: {did_s.params['west:post']:+.3f} orders/day "
f"(SE={did_s.bse['west:post']:.3f}, p={did_s.pvalues['west:post']:.4f})"
)
Output
Orders processed by new store S12 in first 90 days: 86
Pre-trend check (West vs others): p=0.7142
West net DiD lift: -0.171 orders/day (SE=0.368, p=0.6421)

Look how valuable DiD is for avoiding false wins: S12 logged 86 orders in its first 90 days, so a naive store-only report might claim 86 net new orders. Yet the region-level DiD against East, North and South shows no statistically significant net regional lift (p=0.64p = 0.64) — much of S12’s volume shifted over from existing West stores or matched normal summer growth.

Common mistakes:

  • Skipping the pre-trend check; if treated and control were already diverging before the intervention, the DiD estimate merely extrapolates that pre-existing divergence.
  • Measuring DiD at the store level when neighboring stores share customers (a SUTVA spillover violation); aggregate to the market or region level to capture net lift.

Example 6 — Model count data with Poisson and Negative Binomial GLMs

Section titled “Example 6 — Model count data with Poisson and Negative Binomial GLMs”

Goal: Fit Poisson and Negative Binomial models on two count targets — daily order counts in data/sales.csv (strongly overdispersed) and support_tickets in data/customers.csv — then compare dispersion, AIC/BIC and incidence rate ratios.

Step 1 — Fit Poisson vs. Negative Binomial on daily orders (data/sales.csv)

Section titled “Step 1 — Fit Poisson vs. Negative Binomial on daily orders (data/sales.csv)”
daily = (
sales.groupby("order_date")
.agg(orders=("order_id", "nunique"), avg_discount=("discount", "mean"))
.reset_index()
)
daily["dow"] = daily["order_date"].dt.day_name()
daily["month"] = daily["order_date"].dt.month
daily["year_t"] = (daily["order_date"] - daily["order_date"].min()).dt.days / 365.0
formula_orders = "orders ~ year_t + C(dow) + C(month) + avg_discount"
pois_orders = smf.glm(
formula_orders, data=daily, family=sm.families.Poisson()
).fit()
nb_orders = smf.negativebinomial(formula_orders, data=daily).fit(
method="bfgs", maxiter=300, disp=False
)
disp_ratio = pois_orders.pearson_chi2 / pois_orders.df_resid
print(
f"Daily orders mean={daily['orders'].mean():.2f}, "
f"var={daily['orders'].var():.2f}"
)
print(
f"Poisson AIC={pois_orders.aic:.1f} BIC={pois_orders.bic_llf:.1f} "
f"Pearson/df={disp_ratio:.2f}"
)
print(
f"NegBin AIC={nb_orders.aic:.1f} BIC={nb_orders.bic:.1f} "
f"alpha={nb_orders.params['alpha']:.4f}"
)
Output
Daily orders mean=20.35, var=104.04
Poisson AIC=4598.3 BIC=4690.2 Pearson/df=1.53
NegBin AIC=4502.0 BIC=4598.4 alpha=0.0237

Even after controlling for day of week, month, linear growth and average discount, daily orders remain overdispersed (Pearson χ2/df>1.5\text{Pearson }\chi^2 / \text{df} \gt 1.5). The Negative Binomial model improves AIC by nearly 100 points and produces honest standard errors.

Step 2 — Interpret Incidence Rate Ratios and model support_tickets

Section titled “Step 2 — Interpret Incidence Rate Ratios and model support_tickets”

Exponentiating log-link coefficients gives Incidence Rate Ratios (IRRs): multiplicative changes in the expected count per 1-unit increase in the predictor.

disc_irr = np.exp(0.10 * nb_orders.params["avg_discount"])
print(f"Orders IRR for +1 year trend: {np.exp(nb_orders.params['year_t']):.3f}x")
print(f"Orders IRR for +0.10 avg_discount: {disc_irr:.3f}x")
formula_tix = (
"support_tickets ~ C(contract) + C(plan) + tenure_months"
" + monthly_charges + logins_last_30d"
)
pois_tix = smf.glm(formula_tix, data=customers, family=sm.families.Poisson()).fit()
nb_tix = smf.negativebinomial(formula_tix, data=customers).fit(
method="bfgs", maxiter=300, disp=False
)
tix_disp = pois_tix.pearson_chi2 / pois_tix.df_resid
print(
f"\nTickets Poisson AIC={pois_tix.aic:.1f} (Pearson/df={tix_disp:.3f}) | "
f"NegBin AIC={nb_tix.aic:.1f} (alpha={nb_tix.params['alpha']:.4f})"
)
Output
Orders IRR for +1 year trend: 1.207x
Orders IRR for +0.10 avg_discount: 1.765x
Tickets Poisson AIC=14263.0 (Pearson/df=1.039) | NegBin AIC=14261.0 (alpha=0.0323)

For support_tickets, Pearson/df is 1.04 and alpha is tiny (0.032), so Poisson and Negative Binomial agree closely (AIC differs by only 2 points). Checking the dispersion ratio tells you immediately whether Poisson is adequate or Negative Binomial is essential.

Common mistakes:

  • Reading a log-link coefficient β=0.20\beta = 0.20 as “+0.20 orders”; on a log link, exp⁡(0.20)=1.221\exp(0.20) = 1.221 means +22.1% more expected orders.
  • Relying on default Poisson p-values when pearson_chi2 / df_resid is well above 1.

Example 7 — Build Kaplan–Meier retention curves by contract type

Section titled “Example 7 — Build Kaplan–Meier retention curves by contract type”

Goal: Implement the Kaplan–Meier estimator with Greenwood 95% confidence intervals in pure NumPy/pandas on data/customers.csv and compare customer retention across month-to-month, one-year and two-year contracts.

Step 1 — Write a clean Kaplan–Meier function with right censoring

Section titled “Step 1 — Write a clean Kaplan–Meier function with right censoring”

Each row in data/customers.csv records tenure_months (time) and churned (1 = event observed, 0 = right-censored active customer).

def kaplan_meier(time: np.ndarray, event: np.ndarray) -> pd.DataFrame:
"""Compute Kaplan-Meier survival curve and Greenwood 95% CI."""
order = np.argsort(time)
t_sorted, e_sorted = time[order], event[order]
event_times = np.unique(t_sorted[e_sorted == 1])
rows = [(0.0, len(t_sorted), 0, 1.0, 0.0, 1.0, 1.0)]
surv = 1.0
greenwood_sum = 0.0
for tj in event_times:
n_risk = int(np.sum(t_sorted >= tj))
d_j = int(np.sum((t_sorted == tj) & (e_sorted == 1)))
surv *= 1.0 - d_j / n_risk
if n_risk > d_j:
greenwood_sum += d_j / (n_risk * (n_risk - d_j))
se = surv * np.sqrt(greenwood_sum)
ci_lo = max(0.0, surv - 1.96 * se)
ci_hi = min(1.0, surv + 1.96 * se)
rows.append((float(tj), n_risk, d_j, surv, se, ci_lo, ci_hi))
return pd.DataFrame(
rows, columns=["time", "n_risk", "events", "survival", "se", "ci_lo", "ci_hi"]
)
def survival_at(km_df: pd.DataFrame, month: float) -> float:
return float(km_df.loc[km_df["time"] <= month, "survival"].iloc[-1])
km_curves: dict[str, pd.DataFrame] = {}
for contract, grp in customers.groupby("contract"):
km = kaplan_meier(grp["tenure_months"].to_numpy(), grp["churned"].to_numpy())
km_curves[str(contract)] = km
print(
f"{contract:<15} n={len(grp):>4d} events={int(grp['churned'].sum()):>3d} "
f"S(12)={survival_at(km, 12):.3f} S(36)={survival_at(km, 36):.3f} "
f"S(60)={survival_at(km, 60):.3f}"
)
Output
month-to-month n=2784 events=823 S(12)=0.742 S(36)=0.557 S(60)=0.480
one-year n=1225 events=108 S(12)=0.974 S(36)=0.888 S(60)=0.846
two-year n= 991 events= 32 S(12)=0.995 S(36)=0.972 S(60)=0.952

By month 12, only 74.2% of month-to-month customers remain active, compared to 97.4% of one-year and 99.5% of two-year customers. By month 60, month-to-month survival drops to 48.0%, whereas two-year contracts retain over 95%.

Step 2 — Plot the step curves with 95% confidence bands

Section titled “Step 2 — Plot the step curves with 95% confidence bands”
fig, ax = plt.subplots(figsize=(7.0, 4.0))
palette = {"month-to-month": "#d95f02", "one-year": "#7570b3", "two-year": "#1b9e77"}
for contract, km in km_curves.items():
color = palette[contract]
ax.step(km["time"], km["survival"], where="post", label=contract, color=color, lw=2)
ax.fill_between(
km["time"], km["ci_lo"], km["ci_hi"], step="post", alpha=0.18, color=color
)
ax.set_xlabel("Tenure (months)")
ax.set_ylabel("Estimated survival probability S(t)")
ax.set_title("Kaplan-Meier customer retention by contract type (95% Greenwood CI)")
ax.set_ylim(0.35, 1.03)
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
Three Kaplan-Meier step curves with shaded 95 percent confidence bands showing two-year contracts staying above 0.92, one-year near 0.76, and month-to-month dropping to 0.44 over 72 months.
Kaplan–Meier survival curves show sharp early retention gaps between contract types.

Common mistakes:

  • Averaging tenure_months over churned == 1 rows only; ignoring right-censored active customers creates severe survivorship/selection bias.
  • Plotting Kaplan–Meier curves with straight diagonal lines instead of where="post" step functions; survival only drops at observed event times.
Mistake Symptom Fix
Adjusting for a collider or mediator Estimated treatment effect flips sign or shrinks to zero even when a true effect exists Draw the causal DAG first; adjust only for pre-treatment confounders
Peeking at an A/B test daily and stopping when p<0.05p \lt 0.05 False-positive rate balloons from 5% to 20–30% Wait for the fixed sample size or use sequential alpha-spending boundaries
Ignoring a Sample Ratio Mismatch (SRM) Apparent huge lift disappears after shipping Run stats.chisquare on group counts first; halt analysis if p<0.001p \lt 0.001
Using a post-treatment variable in CUPED Biased ATE that understates or reverses the true effect Restrict CUPED covariates strictly to pre-experiment history
Running IPW without checking overlap or SMD Huge standard errors and unstable ATE from weights of 100+ Inspect propensity histograms, use Hájek IPW, trim extreme scores and verify max ∣SMD∣<0.10\lvert\text{SMD}\rvert \lt 0.10
Running DiD without checking pre-trends Pre-existing growth differences masquerade as a treatment effect Plot pre-period trends and test the pre-treatment group × time slope
Using Poisson GLM on overdispersed counts Tiny p-values and overly narrow confidence intervals Check pearson_chi2 / df_resid; switch to Negative Binomial when dispersion > 1.2
Dropping censored rows in retention analysis Grossly underestimated customer lifetime Use Kaplan–Meier so right-censored units stay in the risk set until censoring
  • Product engineering and feature flags: Experimentation platforms run automated SRM alerts, CUPED variance reduction and multi-armed bandit rollouts on every UI change and ranking tweak.
  • Clinical trials and epidemiology: Kaplan–Meier curves, log-rank tests, propensity matching and O’Brien–Fleming interim stopping boundaries are standard regulatory tools for evaluating treatments.
  • Public policy and economics: Difference-in-Differences and propensity weighting evaluate minimum-wage laws, transit expansions and education programs when randomized trials are impossible.
  • Site reliability and hardware engineering: Survival analysis models time-to-failure of servers, SSDs and sensors where most machines are still running (right-censored) at analysis time.
  • Causal questions target potential outcomes (ATE=E[Y(1)−Y(0)]\text{ATE} = \mathbb{E}[Y(1) - Y(0)]); naive group differences mix the true effect with selection bias.
  • Causal DAGs tell you what to adjust for: adjust for confounders, leave mediators alone for total effects, and never condition on colliders.
  • Guard every experiment with an SRM check, avoid naive peeking, shrink variance with CUPED using pre-experiment covariates, and consider Thompson sampling when short-term regret matters more than fixed-horizon inference.
  • For observational data, propensity score IPW balances observed confounders (verify overlap and ∣SMD∣<0.10|\text{SMD}| \lt 0.10), while Difference-in-Differences removes time-invariant unobserved differences provided parallel trends hold.
  • GLMs extend linear regression to binary, count and skewed positive targets via link functions; prefer Negative Binomial over Poisson whenever counts are overdispersed.
  • Kaplan–Meier estimates retention accurately in the presence of right censoring by keeping active customers in the risk set up to their censoring time.

Q1. What is the fundamental problem of causal inference, and how does randomization address it?

Answer

For any individual unit, you can observe only Yi(1)Y_i(1) or Yi(0)Y_i(0), never both. Randomization makes treatment assignment independent of potential outcomes, so the control group’s average outcome is an unbiased stand-in for the treated group’s unobserved counterfactual, making selection bias zero on average.

Q2. Why can adding more control variables to a regression sometimes make a causal estimate worse?

Answer

If an added variable is a collider (caused by both treatment and outcome), conditioning on it opens a spurious non-causal path and introduces collider bias. If it is a mediator (on the path from treatment to outcome), conditioning on it blocks part of the causal effect you want to measure.

Q3. Your 50/50 checkout A/B test ends with 5,210 users in control and 4,790 in treatment, and treatment shows a +1.8% conversion lift (p=0.008p = 0.008). Should you ship?

Answer

No. A 5,210 vs. 4,790 split has a severe Sample Ratio Mismatch (χ2=17.64\chi^2 = 17.64, p<0.0001p \lt 0.0001). Randomization or event logging is broken, so the +1.8% lift is untrustworthy until the engineering bug is found and the test is re-run.

Q4. If a pre-experiment covariate XX has correlation ρ=0.6\rho = 0.6 with the experiment outcome YY, roughly what fraction of the required sample size does CUPED save?

Answer

CUPED reduces outcome variance by a factor of 1−ρ2=1−0.36=0.641 - \rho^2 = 1 - 0.36 = 0.64, which saves ρ2=36%\rho^2 = 36\% of the required sample size for the same statistical power.

Q5. Why is time_on_page_s from data/ab_test.csv not a valid CUPED covariate for that checkout experiment?

Answer

time_on_page_s was measured during the experiment and was itself affected by treatment (mean 82.7 s in control vs. 91.8 s in treatment). Adjusting for a post-treatment variable violates the CUPED requirement that E[X∣T=1]=E[X∣T=0]\mathbb{E}[X \mid T=1] = \mathbb{E}[X \mid T=0] and biases the treatment effect.

Q6. When should you prefer a fixed-horizon A/B test over a Thompson-sampling bandit?

Answer

Prefer a fixed-horizon A/B test when you need clean confidence intervals and p-values, want to monitor multiple guardrail metrics equally, or are making a long-term product decision where the cost of a short experiment is small compared to shipping a wrong change.

Q7. What two diagnostics must you inspect before trusting an Inverse Probability Weighting (IPW) causal estimate?

Answer

First, propensity score overlap (positivity): treated and control propensity distributions should overlap without extreme values near 0 or 1. Second, post-weighting covariate balance: the absolute Standardized Mean Difference (∣SMD∣\lvert\text{SMD}\rvert) should drop below 0.10 for every confounder after weighting.

Q8. What assumption makes Difference-in-Differences valid, and how do you check whether it is plausible?

Answer

The parallel trends assumption: without treatment, treated and control groups would have changed by the same amount over time. You check its plausibility by plotting multiple pre-treatment periods and testing whether the pre-period group-by-time trend interaction is close to zero.

Q9. You fit a Poisson GLM to daily ticket counts and see pearson_chi2 / df_resid = 3.8. What does this mean and what should you change?

Answer

The data is strongly overdispersed: conditional variance is nearly four times the mean, violating the Poisson assumption Var(Y∣X)=μ\text{Var}(Y \mid X) = \mu and making Poisson standard errors too small. Switch to a Negative Binomial model (or quasi-Poisson) and compare AIC/BIC.

Q10. In data/customers.csv, why are active (churned == 0) customers kept in the Kaplan–Meier calculation instead of dropped?

Answer

Active customers are right-censored: they provide real information that they survived at least through their current tenure_months. Keeping them in the at-risk denominator njn_j up to their censoring time avoids downward survival bias.

Your progress

0 / 4 done