Switchback and Cluster-Randomized Experiments in Python

Analyze experiments where users can't be randomized one by one: cluster-randomized tests with cluster-robust standard errors, ICC and design effect, and switchback tests with block length and washout.

When users can affect each other (drivers and riders, buyers and sellers, friends in a feed), randomizing individual users breaks the test. Randomize whole groups instead (a cluster-randomized test), or flip the treatment on and off over time in one market (a switchback test), and analyze the data at the level you randomized. In statsmodels that means smf.ols(...).fit(cov_type="cluster", cov_kwds={"groups": ...}). This post covers both designs, shows how much a naive test lies when you skip that step, and looks at how block length trades bias against noise in switchbacks.

Quick Example

A retailer randomizes 40 stores (the clusters), 20 to a new checkout flow and 20 to the old one, and measures order value for every customer. The data is simulated with a true lift of $0.80, and customers in the same store are correlated. This runs on its own:

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats

rng = np.random.default_rng(21)
n_clusters, effect, sd_total, icc = 40, 0.8, 5.0, 0.05

clusters = pd.DataFrame({
    "cluster": np.arange(n_clusters),
    "size": rng.integers(100, 301, n_clusters),
    "treated": rng.permutation([0, 1] * (n_clusters // 2)),
})
clusters["u"] = rng.normal(0, sd_total * np.sqrt(icc), n_clusters)   # store-level shift
df = clusters.loc[clusters.index.repeat(clusters["size"])].reset_index(drop=True)
df["order_value"] = (
    30 + df["u"] + effect * df["treated"]
    + rng.normal(0, sd_total * np.sqrt(1 - icc), len(df))
)

naive = smf.ols("order_value ~ treated", data=df).fit()
robust = smf.ols("order_value ~ treated", data=df).fit(
    cov_type="cluster", cov_kwds={"groups": df["cluster"]}
)
for name, res in [("naive", naive), ("cluster-robust", robust)]:
    lo, hi = res.conf_int().loc["treated"]
    print(f"{name:15s} est={res.params['treated']:.3f} se={res.bse['treated']:.3f} "
          f"CI=({lo:.2f}, {hi:.2f}) p={res.pvalues['treated']:.4f}")

Both fits give the same estimate, a $0.74 lift across 8,557 customers. The standard errors are not close:

Analysis Estimate Std. error 95% CI p-value
Naive (customers independent) 0.737 0.107 0.53 to 0.95 below 0.0001
Cluster-robust (by store) 0.737 0.320 0.11 to 1.37 0.021

The cluster-robust interval is three times wider. Only 40 stores were randomized, so there are really about 40 independent observations, not 8,557.

Left: mean order value for each of 40 stores, treatment stores averaging about 30.9 and control stores about 30.0. Right: confidence intervals for the lift, a narrow naive interval from 0.53 to 0.95 and a wide cluster-robust interval from 0.11 to 1.37, both centered on 0.74

Why Can't I Randomize Users Individually?

Individual randomization assumes one user's outcome doesn't depend on who else is treated. Three situations break that:

  • Interference in a marketplace. A discount shown to half of riders pulls drivers toward those riders, so the control group sees longer waits. The control is no longer a clean baseline.
  • Network effects. A feature that only works when your contacts also have it can't be tested on a random half of a friend graph.
  • Shared infrastructure or staff. A new store process, a regional price, or a support script applies to everyone in that location at once.

The fix is to pick the unit that contains the spillover (a store, a city, a classroom, a market-hour) and randomize that unit. Everything downstream, including the standard error and the sample size, is then measured in units of the randomized group.

What Is the Intraclass Correlation and Design Effect?

Users in the same cluster resemble each other. The intraclass correlation (ICC) is the share of the outcome's variance that sits between clusters. The design effect says how much that correlation inflates the variance of your estimate compared with randomizing users one by one:

DEFF = 1 + (m - 1) * ICC

where m is the average cluster size. An ICC of 0.05 sounds negligible, but with 214 customers per store it gives a design effect above 10, so you need roughly ten times the users for the same precision. A one-way ANOVA estimate of the ICC on the quick example data:

m_bar = df.groupby("cluster").size().mean()
g = df.groupby("cluster")["order_value"]
msb = (g.size() * (g.mean() - df["order_value"].mean()) ** 2).sum() / (n_clusters - 1)
msw = ((df["order_value"] - g.transform("mean")) ** 2).sum() / (len(df) - n_clusters)
n0 = (len(df) - (g.size() ** 2).sum() / len(df)) / (n_clusters - 1)
icc_hat = (msb - msw) / (msb + (n0 - 1) * msw)
deff = 1 + (m_bar - 1) * icc_hat
print(f"ICC={icc_hat:.3f}  mean cluster size={m_bar:.1f}  DEFF={deff:.2f}")
print(f"SE ratio: {robust.bse['treated'] / naive.bse['treated']:.2f}  vs sqrt(DEFF)={np.sqrt(deff):.2f}")

The estimated ICC is 0.043 (the true value was 0.05), the design effect is 10.2, and the standard errors differ by a factor of 3.00, close to sqrt(DEFF) of 3.19. The standard error scales with the square root of the design effect, which is the quick way to see how much a naive analysis understates uncertainty.

Plan the test with the design effect too: take the sample size from the power calculation for individual randomization and multiply it by DEFF. Adding more users per cluster helps less than adding clusters, because the term (m - 1) * ICC grows with m.

How Bad Is the Naive Test? An A/A Simulation

An A/A simulation shows the damage directly: assign 40 clusters of 200 users to two arms with no true effect, test at 5%, and count how often the test fires. A correct test fires about 5% of the time.

from scipy import stats

rng = np.random.default_rng(7)
k, m, n_sims = 40, 200, 2000
rows = []
for r in [0.0, 0.01, 0.02, 0.05, 0.1, 0.2]:
    u = rng.normal(0, np.sqrt(r), (n_sims, k, 1))
    y = u + rng.normal(0, np.sqrt(1 - r), (n_sims, k, m))       # no treatment effect
    arm = np.tile(np.array([0, 1] * (k // 2)), (n_sims, 1))
    y1 = y[arm == 1].reshape(n_sims, -1, m)
    y0 = y[arm == 0].reshape(n_sims, -1, m)
    a, b = y1.reshape(n_sims, -1), y0.reshape(n_sims, -1)
    se = np.sqrt(a.var(axis=1, ddof=1) / a.shape[1] + b.var(axis=1, ddof=1) / b.shape[1])
    p_naive = 2 * stats.norm.sf(np.abs((a.mean(1) - b.mean(1)) / se))
    p_cluster = stats.ttest_ind(y1.mean(2), y0.mean(2), axis=1).pvalue
    rows.append((r, (p_naive < 0.05).mean(), (p_cluster < 0.05).mean()))
print(pd.DataFrame(rows, columns=["icc", "naive", "cluster_means"]).round(3))
ICC Naive user-level test Test on cluster means
0.00 5.8% 5.3%
0.01 26.4% 5.0%
0.02 38.4% 4.6%
0.05 54.3% 4.6%
0.10 67.0% 5.6%
0.20 75.8% 5.2%

At an ICC of just 0.01, the naive test declares a winner more than a quarter of the time when nothing changed. At 0.05 it is more than half. Testing the cluster means keeps the false positive rate near 5% at every ICC.

Line chart of A/A false positive rate against intraclass correlation. The naive user-level test climbs from 5.8% at ICC 0 to 75.8% at ICC 0.2, while the test on cluster means stays flat near the nominal 5% line

How Do I Analyze a Cluster-Randomized Test?

There are two sound options, and they usually agree:

  1. Cluster-robust standard errors on the user-level regression, as in the Quick Example. You keep the user-level data, can add covariates, and the estimate weights each store by its size.
  2. Collapse to cluster means and run an ordinary t-test on those 40 numbers. It is simple and hard to get wrong.
cl = df.groupby(["cluster", "treated"], as_index=False)["order_value"].mean()
t = stats.ttest_ind(
    cl.loc[cl.treated == 1, "order_value"], cl.loc[cl.treated == 0, "order_value"]
)
print(f"diff of cluster means = {cl.groupby('treated')['order_value'].mean().diff().iloc[-1]:.3f}, p = {t.pvalue:.4f}")

The difference of cluster means is $0.94 (p = 0.0076), a bit different from the size-weighted $0.74 because the unweighted version treats a 100-customer store the same as a 300-customer one. Both are valid for different questions: the unweighted version estimates the effect on the average store, the weighted version the effect on the average customer. Pick one before looking at the data.

Cluster-robust standard errors lean on large-sample theory in the number of clusters, not users. With fewer than about 30 clusters they tend to be too small, so prefer the cluster-means t-test there, or a permutation test that reshuffles which clusters are treated. Pairing similar clusters before randomizing (by size, region or past sales) reduces the noise from between-cluster differences, and the same pre-period covariate trick from CUPED works at the cluster level.

What Is a Switchback Experiment?

A switchback test has one market, such as a city, and alternates the treatment over time. Each block of hours or days is randomly assigned to treatment or control, and you compare the blocks. It is the standard design when the whole marketplace has to see one version at a time (surge pricing, dispatch algorithms, delivery fees) and there are too few markets to randomize across them.

The data below is hourly rides over 28 days: a daily demand cycle, autocorrelated noise, and a pricing change worth 8 extra rides per hour once it has fully taken hold. The effect builds up gradually after a switch (carryover), which is what makes switchbacks tricky. It is simulated with 4-hour blocks.

H, tau, decay = 24 * 28, 8.0, 0.6

def simulate(rng, block):
    t = np.arange(H)
    n_blocks = int(np.ceil(H / block))
    z = np.repeat(rng.permutation(np.r_[np.ones(n_blocks // 2), np.zeros(n_blocks - n_blocks // 2)]), block)[:H]
    s, prev = np.zeros(H), 0.0
    for i in range(H):                       # effect lingers after a switch
        prev = decay * prev + (1 - decay) * z[i]
        s[i] = prev
    noise = np.zeros(H)
    for i in range(1, H):
        noise[i] = 0.6 * noise[i - 1] + rng.normal(0, 5)
    base = 100 + 30 * np.sin(2 * np.pi * (t % 24 - 9) / 24)
    y = base + tau * s + noise
    return pd.DataFrame({"hour": t % 24, "block": t // block, "pos": t % block, "z": z, "y": y})

rng = np.random.default_rng(11)
sb = simulate(rng, block=4)

Line chart of hourly rides over three days with a daily demand peak around 14:00 and several 4-hour blocks shaded to show when the new pricing was on

Demand swings between about 60 and 150 rides an hour over the day, which is far larger than the effect. Compare treated and control hours without accounting for that and the result depends on which hours happened to land in which arm. Put hour-of-day fixed effects in the regression, and cluster the standard errors by block, because hours inside a block share noise and treatment:

fit = smf.ols("y ~ z + C(hour)", data=sb).fit(
    cov_type="cluster", cov_kwds={"groups": sb["block"]}
)
lo, hi = fit.conf_int().loc["z"]
print(f"effect = {fit.params['z']:.2f}, 95% CI ({lo:.2f}, {hi:.2f})")

The estimate is 7.21 rides per hour with a 95% CI of 5.83 to 8.59, against a true 8. The interval covers the truth, but the point estimate sits below it, and the reason is carryover.

How Do I Handle Carryover With a Washout Period?

After the pricing switches back to control, some of the effect lingers: drivers who repositioned are still there, riders who already booked still show up. Those hours are labeled control but behave partly like treatment, which pulls the measured difference toward zero. The usual fix is a washout: drop the first hours after each switch from the analysis.

kept = sb[sb["pos"] >= 2]                    # drop the first 2 hours of every block
fit_w = smf.ols("y ~ z + C(hour)", data=kept).fit(
    cov_type="cluster", cov_kwds={"groups": kept["block"]}
)
lo, hi = fit_w.conf_int().loc["z"]
print(f"effect = {fit_w.params['z']:.2f}, 95% CI ({lo:.2f}, {hi:.2f})")

This gives 8.39 with a 95% CI of 6.66 to 10.13. The estimate moves closer to the truth, and the interval gets wider because half the hours are gone. That is the cost of washout, and one seed can't tell you whether the shift is a real improvement or luck, so the next section repeats the exercise 400 times.

How Long Should Switchback Blocks Be?

Block length is the main design choice. Short blocks give many blocks to average over but most of each block sits in the carryover window. Long blocks are clean but leave few independent units. This simulation repeats the experiment 400 times for each block length, with and without a 2-hour washout:

rng = np.random.default_rng(5)
res = []
for B in [1, 2, 4, 8, 12, 24, 48]:
    for _ in range(400):
        s_ = simulate(rng, B)
        s_["y_dm"] = s_["y"] - s_.groupby("hour")["y"].transform("mean")   # remove the daily cycle
        est_all = s_.loc[s_.z == 1, "y_dm"].mean() - s_.loc[s_.z == 0, "y_dm"].mean()
        k_ = s_[s_["pos"] >= 2]
        est_w = (k_.loc[k_.z == 1, "y_dm"].mean() - k_.loc[k_.z == 0, "y_dm"].mean()) if B > 2 else np.nan
        res.append((B, est_all, est_w))
r = pd.DataFrame(res, columns=["block", "all", "washout"])
print(r.groupby("block").agg(["mean", "std"]).round(2))
Block length All hours: mean (SD) Drop first 2 hours: mean (SD)
1h 3.06 (0.46) n/a
2h 4.02 (0.66) n/a
4h 5.24 (0.79) 6.41 (0.91)
8h 6.39 (0.88) 7.20 (0.95)
12h 6.92 (0.95) 7.49 (1.00)
24h 7.50 (0.93) 7.81 (0.97)
48h 7.67 (0.91) 7.85 (0.94)

Chart of the estimated switchback effect by block length from 1 hour to 48 hours with error bars. Estimates rise from about 3 rides per hour at 1-hour blocks toward the true 8 as blocks lengthen, and dropping the first 2 hours of each block moves estimates closer to 8

With 1-hour blocks the estimate is 3.06, well under half the true 8, because almost every hour is contaminated by the one before it. Estimates approach the truth as blocks lengthen, and the washout closes most of the remaining gap at short and moderate lengths (6.41 vs 5.24 at 4 hours, 7.20 vs 6.39 at 8 hours). The spread of the estimates does not keep shrinking: from 8-hour blocks on it stays around 0.9 to 1.0, because longer blocks also mean fewer of them (14 blocks at 48 hours), so each run leans on a few coin flips.

In this simulation the carryover has a half-life of about 1.4 hours, so blocks of 8 to 24 hours with a washout work well. In a real test, the carryover length is the thing to learn first: run a pilot, plot the outcome in the hours after a switch, and set the block length to a few multiples of how long it takes to settle.

Cluster-Randomized vs Switchback vs User-Level A/B

Design Randomization unit Use when Analysis
User-level A/B test User No interference between users Standard two-sample test
Cluster-randomized Store, city, class, network community Interference stays inside groups, and you have 30+ groups Cluster-robust SEs or test on cluster means
Switchback Time block within one market Interference is market-wide and you have one or a few markets Regression with time-of-day effects and block-clustered SEs
Geo experiment Region, with a few treated Very few units Synthetic control or CausalImpact

Practical Tips

  • Count clusters, not users. The precision of a cluster-randomized test is set mostly by how many clusters you have. A million users in 6 stores is a 6-observation experiment.
  • Estimate the ICC from history before the test, using past data grouped by the cluster you plan to randomize, and use it in the power calculation.
  • Analyze at the unit of randomization. If you randomized stores or blocks, cluster the standard errors there, even when the analysis table has one row per user or per hour.
  • Check balance and sample ratio at the cluster level. An SRM check on the number of clusters per arm, and on cluster sizes, catches assignment bugs.
  • Fix the block length and washout before the test. Choosing them after seeing results is another form of peeking.
  • Alternate at fixed boundaries. Switch at the same clock times each day, and randomize which block gets which arm so a weekday pattern can't line up with the treatment.

Similar Topics