Published on

A/B Testing vs Difference-in-Differences in Python

Authors

How to Measure Whether a Strategy Change Worked ended on a grocery chain whose curbside pickup launch looked like +17,500perstoreperweekandwasreallyworthabout17,500 per store per week and was really worth about 6,400. That post was about picking a design that fits how a change rolls out. This one is about running the two designs you will use most, and the checks that decide whether to believe the answer.

An A/B test, for when you control who gets the change. Difference-in-differences, for when the change went to whole stores and you can't. Every number below comes from the code next to it, and all of it runs as written.

pip install pandas statsmodels scipy

Running an A/B test

The same chain wants to test a redesigned checkout in its ordering app. Individual users can be randomized, so a coin flip decides who sees which version. That makes the two groups alike on everything, including what nobody measured, so any gap that opens up afterwards belongs to the checkout.

Size it before you start. Checkout conversion runs at 3.1%, and the team decides a lift to 3.5% is the smallest one worth shipping.

from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize

effect = proportion_effectsize(0.035, 0.031)
NormalIndPower().solve_power(effect, alpha=0.05, power=0.8)   # 31,280 users per group

About 31,000 users per arm, which at their traffic is two weeks. This number is the stopping rule, and it gets written down before anyone sees a result.

Run it, then read it once.

ArmUsersOrdersConversion
Old checkout31,8709633.02%
New checkout32,1301,1663.63%
from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep

orders = [1166, 963]     # new checkout, old checkout
users = [32130, 31870]

z, p = proportions_ztest(orders, users)                                       # p = 0.00002
low, high = confint_proportions_2indep(orders[0], users[0], orders[1], users[1])  # 0.0033 to 0.0089

The new checkout lifted conversion by 0.61 percentage points, with a 95% interval of 0.33 to 0.89. Ship it, and plan on the low end. I simulated this test with a true lift of 0.4 points, so the estimate landed high, which is normal. The interval contains the truth, and a forecast built on 0.33 is safer than one built on 0.61.

Check the split. A 50/50 test should produce two groups of nearly equal size. If it doesn't, something in the assignment or the logging is broken, and the result can't be trusted however good it looks.

from scipy.stats import chisquare

chisquare(users).pvalue   # 0.30, the split is fine

This is called a sample ratio mismatch check. It is one line, and it catches more broken experiments than any other test.

Don't stop the day the dashboard turns green. Here is what checking every day does to 2,000 tests where the two checkouts are identical:

import numpy as np

rng = np.random.default_rng(7406)
days, per_day, sims = 14, 2300, 2000
n = per_day * np.arange(1, days + 1)

control = rng.binomial(per_day, 0.031, (sims, days)).cumsum(axis=1)
treated = rng.binomial(per_day, 0.031, (sims, days)).cumsum(axis=1)
pooled = (control + treated) / (2 * n)
z = (treated - control) / n / np.sqrt(pooled * (1 - pooled) * 2 / n)
significant = np.abs(z) > 1.96

significant.any(axis=1).mean()   # 0.237: "significant" on at least one day
significant[:, -1].mean()        # 0.0585: read once, at day 14

Read once at the planned end, 5.9% of them come up significant, close to the 5% you signed up for. Checked daily, 23.7% do at some point. Peeking turns a 1-in-20 false alarm rate into nearly 1-in-4.

Running difference-in-differences

Pickup needed parking bays and staff, so it went to 20 whole stores, not to random customers. The other 40 stores are the comparison. Load the data and start with the 2×2 of average weekly sales, in $000s:

import pandas as pd
import statsmodels.formula.api as smf

stores = pd.read_csv("https://data-awesome.com/static/data/experimentation/store_sales.csv")
stores.pivot_table(index="pickup", columns="post", values="sales").round(1)
# post        0      1
# pickup
# 0       122.3  133.4
# 1       155.8  173.3

Pickup stores rose 17.5. Comparison stores rose 11.1, which is what the holidays did on their own. The difference, 6.4, is the pickup effect, against a true value of 6.0 that I set when I simulated the data.

As a regression it is one interaction term:

smf.ols("sales ~ pickup * post", data=stores).fit().params["pickup:post"]   # 6.38

pickup absorbs the permanent gap between the groups. post absorbs what changed for everyone. The interaction is what changed only for pickup stores, only after launch.

Clustered standard errors

That estimate is right. Its default standard error is not. There are 1,200 rows and only 60 stores, and a store that has a good week tends to have a good next week, so the rows are not 1,200 independent observations.

The version worth reporting adds store and week fixed effects and clusters the errors by store:

def did(data, term):
    return smf.ols(f"sales ~ {term} + C(store) + C(week)", data=data).fit(
        cov_type="cluster", cov_kwds={"groups": data["store"]}, use_t=True
    )

result = did(stores, "pickup:post")
result.params["pickup:post"]              # 6.38
result.conf_int().loc["pickup:post"]      # 4.34 to 8.43
Standard errorsSE95% interval
Default$5605,280to5,280 to 7,480
Clustered by store$1,0204,340to4,340 to 8,430

Same estimate, and the honest interval is almost twice as wide. Here the conclusion survives. With a smaller effect it would not, and you would have reported a confident result that was mostly correlated noise.

Cluster at the level the change was assigned. Pickup went to stores, so cluster by store. use_t=True matters when there are few clusters, because it builds the interval from 59 degrees of freedom (60 stores minus one) instead of the normal distribution.

Difference-in-differences rests on one assumption: without pickup, the two groups would have kept moving in parallel. They don't need the same level, only the same trend. The chart in the previous post shows the lines moving together before launch, but a chart is a judgment call. A placebo test puts a number on it.

Take only the 12 weeks before launch, pretend pickup started in week 7, and estimate the effect of a launch that never happened:

before = stores[stores.post == 0].assign(fake=lambda d: (d.week >= 7).astype(int))
placebo = did(before, "pickup:fake")
placebo.params["pickup:fake"]             # -0.06
placebo.conf_int().loc["pickup:fake"]     # -2.66 to 2.54

The fake launch comes out at −60perstore,withanintervalsittingsquarelyonzero.Themethodfindsnothingwherethereisnothing,whichiswhatyouwanttoseebeforetrustingitwherethereissomething.Hadtheplacebocomebackat60 per store, with an interval sitting squarely on zero. The method finds nothing where there is nothing, which is what you want to see before trusting it where there is something. Had the placebo come back at 5,000, the groups were already drifting apart, and the real estimate would be measuring the drift.

One case needs a different tool. When stores launch in different months, the two-way model above can give misleading answers, because early stores end up serving as the comparison for late ones. Use an estimator built for staggered rollouts, such as Callaway and Sant'Anna's, which the differences package implements in Python.

Which one to use

A/B testDifference-in-differences
Use it whenYou control who gets the changeThe change went to whole stores or regions
What it rests onRandom assignment, which you can verifyParallel trends, which you can only support
The check that mattersSample ratio mismatchPlacebo on the pre-period
How it usually breaksPeeking, broken splitsDiverging trends, something else launching too

If you can randomize, randomize. Difference-in-differences is not a cheaper A/B test. It carries an assumption the A/B test does not need.

Before you report either one

  1. The sample size was fixed before the test started, and the result was read once.
  2. The split check passes.
  3. The placebo on the pre-period comes back near zero.
  4. Standard errors are clustered at the level the change was assigned.
  5. The headline is the interval, not the point estimate.

For why a regression coefficient on its own can't tell you what a change will do, see Regression Coefficients Are Not Causal. The case against trusting one lucky result applies to models too, and the post on single test splits makes it for model comparison.

Get the next one

Posts on data, analytics and the judgment calls that decide whether a model gets trusted.

ShareLinkedInXReddit