Library/Experiments and causal inference/When randomization is messy

Difference-in-differences

90 min6 partsCoreFundamentalsChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Say why comparing the groups only after launch, or the treated group only before and after, gives the wrong answer, and by how much
  • Compute the difference-in-differences estimate from four means, say the counterfactual it assumes, and subtract in the right order
  • Check parallel trends on the weeks before launch with a slope gap, a placebo launch date and an event study, and say what those checks can't prove
  • Write the regression with an interaction term and with two-way fixed effects, and cluster the standard errors by city
  • Say why one two-way fixed effects regression can break on a staggered rollout when the effect changes over time, and what to run instead
  • Say when to switch to synthetic control or an interrupted time series
Part 1 of 6about 14 min
No coin flip

Difference-in-differences, when you can't run an A/B test

One OpenAI senior data scientist report lists an experimentation question about what you'd do if you cannot run an A/B test (1 report). Netflix tests nearly all proposed product changes with controlled A/B experiments (1 source), and for the questions those can't answer, it says "we rely on quasi-experiments and causal inference methods to inform decisions" (1 source). An Airbnb staff analytics posting asks for causal methods when randomized trials aren't available (1 source), Anthropic's growth data scientist posting lists quasi-experiments next to A/B tests (1 source), and a prep site lists an Airbnb screen question about a feature "launched globally on 2025-05-10 with no control or holdout" (1 source). Our version of the practice reads like this:

A new policy reached 15 of 30 cities in week 8, and the other 15 never got it. You have every city's metric for 16 weeks. Estimate what the policy did, and tell me whether to trust the estimate.

The practice comes in four levels. Level 1 writes did_estimate, from four means. Level 2 writes pre_trend_gap, which checks parallel trends on the weeks before launch. Level 3 writes placebo_estimate, a fake launch date that should find nothing. Level 4 writes event_study, the gap week by week.

You don't write them yet. The lesson starts with why the easy comparisons are wrong, builds the estimate on a worked example, then tests its one assumption, and ends with the regression, clustered standard errors and staggered rollouts. At the end you solve the whole problem, level by level, in an interview simulation with a 40-minute timer.

This lesson builds on the A/B test lesson, which had a coin flip to lean on, and on the cluster-randomized lesson's clustered standard errors. It's the last lesson on experiments.

Some changes reach whole cities at once, so no coin flip splits the users

Start with why the A/B test's move isn't available here.

Predict

A launch goes to cities that someone picked. Are the treated and control cities alike before the change?

Pick an answer above to see the rest

The practice data: 30 cities over 16 weeks, half of them treated from week 8

The practice data is a panel: one row per city per week.

import numpy as np

def panel(seed=0, effect=2.0, extra_trend=0.0):
    rng = np.random.default_rng(seed)
    city = np.repeat(np.arange(30), 16)
    week = np.tile(np.arange(16), 30)
    treated = (city < 15).astype(float)
    post = (week >= 8).astype(float)
    base = rng.normal(0, 1, 30)[city] + 5 * treated
    y = (20 + base + 0.4 * week + extra_trend * treated * week
         + effect * treated * post + rng.normal(0, 1, city.size))
    return y, treated, post, week

y, treated, post, week = panel()
city = np.repeat(np.arange(30), 16)
print("city  week  treated  post      y")
for row in (7, 8, 16 * 29 + 7, 16 * 29 + 8):
    print(f"{city[row]:>4}  {week[row]:>4}  {treated[row]:>7}"
          f"  {post[row]:>4}  {y[row]:5.2f}")
city  week  treated  post      y
   0     7      1.0   0.0  27.80
   0     8      1.0   1.0  31.11
  29     7      0.0   0.0  23.47
  29     8      0.0   1.0  21.73

This is the practice problem's data. There's one row per city per week, 480 rows in all. np.repeat(np.arange(30), 16) lists each city 16 times, and np.tile(np.arange(16), 30) lists the weeks 0 to 15 once for each city. So row 8 is city 0 in week 8.

The y line builds each row's metric from five parts:

  • 20, plus the city's own level: random, and 5 higher for a treated city.
  • 0.4 a week, for every city.
  • An extra trend for the treated cities, extra_trend a week. It's 0 unless a step says otherwise.
  • The effect, 2, for a treated city after launch.
  • Noise.

So the true effect is 2. Your job is to get it back from y, treated and post alone.

Look at the printed rows. treated belongs to the city, and post belongs to the week. City 29 is a control city, and its post turns to 1 at week 8 too. Split the rows by those two flags and you get four cells:

Weeks 0 to 7, post = 0Weeks 8 to 15, post = 1
15 treated cities, treated = 1T0: 120 rowsT1, policy on: 120 rows
15 control cities, treated = 0C0: 120 rowsC1, still no policy: 120 rows

T is the treated group and C the control group. 0 is before launch and 1 is after. Each cell's mean is one number, and the whole method works on those four.

You write two functions. did_estimate returns the effect. pre_trend_gap checks the assumption that makes the effect believable.

A worked example: two groups of cities over eight weeks

The treated cities sat 12 above the control cities before launch, and 16 above after

Four cities got a new policy in week 5, and four similar cities didn't. Each number is one group's average for one week, laid out like the practice data: one row per group per week.

def worked_example():
    week = np.tile(np.arange(1, 9), 2)
    treated = np.repeat([1.0, 0.0], 8)
    post = (week >= 5).astype(float)
    y = np.array([52.0, 54, 53, 56, 61, 64, 63, 66,
                  40, 42, 41, 44, 45, 48, 47, 50])
    return y, treated, post, week

y, treated, post, week = worked_example()
print("treated:", y[treated == 1])
print("control:", y[treated == 0])
print("gap:    ", y[treated == 1] - y[treated == 0])
Predict

Both groups wobble from week to week. What does the gap between them do before the policy?

Pick one to see what it prints.
Pick an answer above to see the rest

Four means hold everything the estimate needs

The weekly series boil down to four numbers.

def mean(t, p):
    return y[(treated == t) & (post == p)].mean()

T0, T1, C0, C1 = mean(1, 0), mean(1, 1), mean(0, 0), mean(0, 1)
rows = [("treated", T0, T1), ("control", C0, C1),
        ("gap", T0 - C0, T1 - C1)]
print("           before   after   change")
for name, b, a in rows:
    print(f"{name:<9} {b:7.2f} {a:7.2f}  {a - b:7.2f}")
           before   after   change
treated     53.75   63.50     9.75
control     41.75   47.50     5.75
gap         12.00   16.00     4.00

mean(t, p) averages the rows of one cell. (treated == t) & (post == p) is True on that cell's rows, since & is NumPy's elementwise and.

These are the practice data's four cells, T0, T1, C0 and C1, filled in for the worked example: T0=53.75T_0 = 53.75 and T1=63.5T_1 = 63.5 for the treated cities before and after, and C0=41.75C_0 = 41.75 and C1=47.5C_1 = 47.5 for the control cities.

The last number in the gap row, 4, is the answer the rest of this lesson builds. The gap grew from 12 to 16.

Each mean runs over every row in its cell. In a balanced panel, where every city has every week, that's the same as averaging the city averages.

In the editor, write cell_means(y, treated, post): the 2 by 2 table of means.

CheckpointThe four means

Write cell_means(y, treated, post). Return a 2×2 array m where m[i, j] is the mean of y over the rows with treated == i and post == j. So m[1, 0] is T0T_0, the treated cities before launch, and m[0, 1] is C1C_1, the control cities after.

Part 1 done
Part 2 of 6about 14 min
The estimate

After-only and before-and-after each look causal, and each keeps a bias

Two comparisons look causal and aren't. Interviewers want to hear you reject them and say why.

def easy_answers(y, treated, post):
    def mean(t, p):
        return y[(treated == t) & (post == p)].mean()
    after_only = mean(1, 1) - mean(0, 1)
    own_change = mean(1, 1) - mean(1, 0)
    return after_only, own_change

for name, data in [("worked example", worked_example()),
                   ("practice panel", panel())]:
    a, b = easy_answers(*data[:3])
    print(f"{name}:  after only {a:5.2f}   treated's change {b:5.2f}")
Predict

Which easy comparison still carries the gap that existed before launch?

Pick one to see what it prints.
Pick an answer above to see the rest

Difference-in-differences subtracts what the two easy comparisons keep

Each easy comparison is the right answer plus one bias:

T1−C1=(T0−C0)⏟gap already there+DiDT_1 - C_1 = \underbrace{(T_0 - C_0)}_{\text{gap already there}} + \text{DiD} T1−T0=(C1−C0)⏟change anyway+DiDT_1 - T_0 = \underbrace{(C_1 - C_0)}_{\text{change anyway}} + \text{DiD}

In words: DiD is the difference in differences, (T1−T0)−(C1−C0)(T_1 - T_0) - (C_1 - C_0). Both lines are true for any four numbers, so they need no assumption. On the worked example:

The two easy comparisons, and the difference in differences
0481216
after only: T1 - C1 = 16
the treated group's own change: T1 - T0 = 9.75
difference in differences = 4
the gap that was already therethe effectthe common change

The same 4 sits inside both wrong answers. The pre-launch gap is what's wrong with after-only, and the control group's change is what's wrong with before-and-after. Difference-in-differences subtracts both.

The practice data works the same way. The treated cities start 5 higher, every city rises 0.4 a week, and the true effect is 2. The pre weeks are 0 to 7 and the post weeks 8 to 15, so the two periods' midpoints are 8 weeks apart. After-only should land near 5+2=75 + 2 = 7, and before-and-after near 0.4×8+2=5.20.4 \times 8 + 2 = 5.2. Over 2,000 simulated panels they average 7.00 and 5.20, and difference-in-differences averages 2.00.

In the editor, write easy_answers(m): both easy comparisons and the difference in differences, from the four means.

The estimate is the treated group's change minus the control group's change

Subtract one easy answer's bias, and the estimate is left.

def did_estimate(y, treated, post):
    y, treated, post = (np.asarray(a, float)
                        for a in (y, treated, post))

    def mean(t, p):
        return y[(treated == t) & (post == p)].mean()

    treated_change = mean(1, 1) - mean(1, 0)
    control_change = mean(0, 1) - mean(0, 0)
    return float(treated_change - control_change)

print(did_estimate(*worked_example()[:3]))
print(round(did_estimate(*panel()[:3]), 2))
Predict

The practice panel was built with a true effect of 2. About what does did_estimate return?

Pick one to see what it prints.
Pick an answer above to see the rest

Card and Krueger's minimum wage study is the classic difference in differences

The method's best-known use is a minimum wage study.

Predict

New Jersey raised its minimum wage in 1992, and neighboring Pennsylvania didn't. What did the difference in differences find for fast-food jobs?

Pick an answer above to see the rest
Part 2 done
Part 3 of 6about 36 min
Parallel trends

Everything rests on one assumption, which you can test only indirectly, on the weeks before launch

The estimate is only as good as one assumption.

Predict

Difference-in-differences rests on one assumption. Which?

Pick an answer above to see the rest

Check the weeks before launch: the two groups' slopes should match

You can't see the treated cities' path without the launch, but you can see their path before it.

def pre_trend_gap(y, treated, week, start_week):
    y, treated, week = (np.asarray(a, float)
                        for a in (y, treated, week))
    pre = week < start_week

    def weekly_slope(group):
        rows = pre & (treated == group)
        weeks = np.unique(week[rows])
        means = [y[rows & (week == w)].mean() for w in weeks]
        return np.polyfit(weeks, means, 1)[0]

    return float(weekly_slope(1) - weekly_slope(0))

y, treated, post, week = worked_example()
gap = pre_trend_gap(y, treated, week, 5)
print(f"worked example, weeks 1 to 4:  {gap:+.3f}")
for extra in (0.0, 0.3):
    y, treated, post, week = panel(3, extra_trend=extra)
    gap = pre_trend_gap(y, treated, week, 8)
    print(f"panel, extra trend {extra}:       {gap:+.3f}")
worked example, weeks 1 to 4:  +0.000
panel, extra trend 0.0:       -0.002
panel, extra trend 0.3:       +0.298

What you can check is the pre-launch period. If the groups moved in parallel for weeks before the launch, it's more believable they would have kept going that way.

That's pre_trend_gap. It fits a least-squares line through each group's weekly means, on pre-launch weeks only, and returns the treated slope minus the control slope. A least-squares line is the straight line that makes the squared misses as small as possible.

  • On the worked example, weeks 1 to 4, both lines rise 1.1 a week. The gap is 0: parallel.
  • On a practice panel with parallel trends, the gap is -0.002.
  • On the same panel with the treated cities trending 0.3 a week faster, it's 0.298.

np.unique lists each pre-launch week once, in order. np.polyfit(weeks, means, 1) fits a polynomial of degree 1, a straight line, and returns its coefficients from the highest power down. So [0] is the slope. The name isn't the point: the checkpoint below computes the same slope by hand.

Why pre-launch only? After launch, the treated line carries the effect. To a least-squares fit across all weeks, a jump at launch looks like a steeper line:

A step of 1 at week 8, and the least-squares line through it
010815week
a step of 1 at week 8 the least-squares line, 0.094 a week

Nothing in the step trends, yet the line through it climbs 0.094 a week.

In the editor, write ls_slope(x, y): a least-squares slope without np.polyfit.

CheckpointA least-squares slope by hand

Write ls_slope(x, y) for two arrays. Return the slope of the least-squares line through the points, without np.polyfit. The worked example's treated means before launch, 52, 54, 53 and 56 over weeks 1 to 4, give 1.1 a week.

Two slopes make the pre-trend gap

With a slope function, the check is one subtraction.

In the editor, finish pre_trend_gap(y, treated, week, start_week) with ls_slope.

CheckpointThe pre-trend gap

Finish pre_trend_gap(y, treated, week, start_week), using ls_slope from the step before. Use only the weeks before start_week. Return the slope of the treated group's weekly means minus the slope of the control group's.

A trend gap of g a week, kept after launch, adds g times the weeks between the period midpoints

A gap in the slopes doesn't stop at the launch.

The gap the practice formula expects, before noise
46810120815weekthe gap
parallel trends treated cities trend 0.3 a week faster

The launch is week 8. With parallel trends the gap steps up by the effect, 2. With the extra trend it climbs all the way.

Average gapWeeks 0 to 7Weeks 8 to 15Difference
parallel trends5.007.002.00
treated 0.3 a week faster6.0510.454.40

Each line in the figure is the gap the practice formula expects, treated minus control, week by week, and the table averages it over each period. With parallel trends, the gap sits at 5, then steps up by the effect, 2. With the treated cities trending 0.3 a week faster, the gap climbs the whole time.

Difference-in-differences compares the average gap after launch with the average gap before. So it picks up the climb along with the step. If the treated group's trend is steeper by gg a week, before and after launch, the estimate absorbs all of it:

bias=g×(wˉpost−wˉpre)\text{bias} = g \times (\bar w_{\text{post}} - \bar w_{\text{pre}})

In words: wˉ\bar w is the average week number in each period. The bias is the slope gap times the distance between the two periods' middles.

In the practice data the pre weeks average 3.5 and the post weeks 11.5, 8 weeks apart. So every 0.1 a week of extra trend adds 0.8. Take a practice panel with g=0.3g = 0.3: over 2,000 simulated panels the estimate averages 4.4 where the true effect is 2, and pre_trend_gap averages 0.30.

That's the job of the check. A gap of 0.3 a week tells you not to report 4.4.

In the editor, write trend_bias(g, pre_weeks, post_weeks): what a trend gap adds to the estimate.

Passing the check is weaker than it sounds.

Predict

A pre-period check finds no trend gap. Does that prove the trends are parallel?

Pick an answer above to see the rest

The scale matters too.

weeks = np.arange(8)
big, small = 100 * 1.05 ** weeks, 50 * 1.05 ** weeks
print("gap each week:", np.round(big - small, 1))
levels, logs = did_two_ways(big, small, 4)
print(f"estimate in levels: {levels:.1f}")
print(f"estimate in logs:   {logs:.1f}")
Predict

Both groups grow 5% a week, from 100 and from 50, with no effect at all. Which scale shows parallel trends?

Pick one to see what it prints.
Pick an answer above to see the rest

A fake launch date before the real one should find nothing

A second check moves the launch date.

A placebo launch inside the weeks before the real one
04816 weeks
the fake launch is week 4, and the real launch week 8
fake before: weeks 0 to 3fake after: weeks 4 to 7left out: weeks 8 to 15

A placebo test runs the same analysis where the true effect is known to be zero. Here it drops the real post weeks, pretends the launch came at week 4, and runs did_estimate on weeks 0 to 7:

for name, extra in [("parallel trends", 0.0), ("treated +0.3 a week", 0.3)]:
    y, treated, post, week = panel(3, extra_trend=extra)
    est = placebo_estimate(y, treated, week, 4, 8)
    print(f"{name + ':':<21} {est:+.2f}")
Predict

A fake launch at week 4, on weeks 0 to 7 only. The treated cities trend 0.3 a week faster. What does it find?

Pick one to see what it prints.
Pick an answer above to see the rest

An event study shows the gap week by week

The placebo checks one fake date. An event study checks every week.

for extra in (0.0, 0.3):
    y, treated, post, week = panel(0, extra_trend=extra)
    e = event_study(y, treated, week, 8)
    print(f"extra trend {extra}")
    print("  weeks -8 to -1:", " ".join(f"{v:5.2f}" for v in e[:8]))
    print("  weeks  0 to  7:", " ".join(f"{v:5.2f}" for v in e[8:]))
extra trend 0.0
  weeks -8 to -1:  0.21  0.46  0.43  0.33  0.34  0.51  0.52  0.00
  weeks  0 to  7:  2.54  2.71  2.18  2.40  1.94  2.12  2.04  2.43
extra trend 0.3
  weeks -8 to -1: -1.89 -1.34 -1.07 -0.87 -0.56 -0.09  0.22  0.00
  weeks  0 to  7:  2.84  3.31  3.08  3.60  3.44  3.92  4.14  4.83

The two-period estimate averages the effect over all post weeks and the trend over all pre weeks. An event study shows every week. It takes the treated-minus-control gap in each week and subtracts the gap in the last week before launch, the reference week. Here is the printed output as a plot:

Each week's gap against week -1, before noise
-2024-8-107weeks since launchthe gap
parallel trends treated cities trend 0.3 a week faster

Week -1 is the reference, at 0. With parallel trends the gap is flat before launch and steps up after.

Before launch the points should hover around zero with no slope. After launch they show the effect week by week: whether it lands at once, builds or fades.

A regression gives the same numbers plus a standard error for each. It uses dummies, columns of 0s and 1s. There's one for each city and one for each week, called city and week fixed effects, and one treated-times-week dummy for every week except the reference. In a balanced panel with one launch date, its coefficients match the numbers above to 1e-12 on the practice data. Their standard errors, clustered by city, run from 0.44 to 0.63 on this panel.

  • The parallel series is flat before launch and steps up by about 2 at launch. Its pre-launch points all sit a little above zero. That's because every point is measured against the same week, and that week's gap happened to come in low. Each is within one standard error of zero, two of them only just, so none comes near significance.
  • The other series climbs about 0.3 a week before launch and keeps climbing after. No amount of staring separates the effect from the trend. That's a failed check.

In the editor, write event_study(y, treated, week, start_week): the gap for every week, against week 7.

A dip just before launch suggests anticipation, and a climb after suggests a growing effect

Two more patterns to look for:

  • A dip or a jump in the last week or two before launch suggests anticipation: people reacted to the announcement. Move the reference week to before the announcement.
  • Post-launch points that keep growing mean the two-period estimate is averaging an effect that's still building. Say which weeks your number covers.
Part 3 done
Part 4 of 6about 15 min
Regression

The regression gives the same number, plus a standard error

A standard error needs the estimate written as a regression.

y, treated, post, week = worked_example()
X = np.column_stack([np.ones_like(y), treated, post, treated * post])
alpha, beta, gamma, delta = np.linalg.lstsq(X, y, rcond=None)[0]
print(f"alpha {alpha:.2f}  beta {beta:.2f}  "
      f"gamma {gamma:.2f}  delta {delta:.2f}")

y, treated, post, week = panel(1)
X = np.column_stack([np.ones_like(y), treated, post, treated * post])
delta = np.linalg.lstsq(X, y, rcond=None)[0][3]
did = did_estimate(y, treated, post)
print(f"delta {delta:.6f}   did_estimate {did:.6f}   "
      f"apart by {abs(delta - did):.0e}")
Predict

Regress y on an intercept, treated, post and treated × post. The interaction's coefficient equals what?

Pick one to see what it prints.
Pick an answer above to see the rest

Two-way fixed effects give every city and every week its own level

A richer regression gives each city and each week its own level.

def twfe(y, unit, week, D):
    X = np.column_stack([unit == u for u in np.unique(unit)]
                        + [week == w for w in np.unique(week)[1:]]
                        + [D]).astype(float)
    return float(np.linalg.lstsq(X, y, rcond=None)[0][-1])

y, treated, post, week = panel()
city = np.repeat(np.arange(30), 16)
print(f"{twfe(y, city, week, treated * post):.6f}")
print(f"{did_estimate(y, treated, post):.6f}")
Predict

One launch date and a balanced panel. Does two-way fixed effects match the simple difference in differences?

Pick one to see what it prints.
Pick an answer above to see the rest

Cluster the standard errors by city

The regression's standard error has the cluster lesson's problem.

30 cities, no real effect, weekly shocks that carry over
true spread
0.53
OLS SE
0.24
clustered SE
0.55

Over 2,000 simulated runs, the placebo came out significant in 38% of runs with the OLS standard error, and in about 4% clustered by city.

The practice data has 480 rows, but not 480 independent observations. A city having a good month has it in four rows. And the treatment doesn't vary at all within a city's post weeks. The usual OLS standard error treats every row as new information, and with panel data that's usually far too confident.

Bertrand, Duflo and Mullainathan showed how far by adding fake laws to real state-level data: "we find an 'effect' significant at the 5 percent level for up to 45 percent of the placebo interventions."

You can reproduce it, and the bars above come from that run:

  • Simulate 30 cities over 16 weeks with no effect.
  • Give each city weekly shocks that carry over, with a correlation of 0.8 from one week to the next.
  • Assign a placebo launch to half the cities at week 8, and fit two-way fixed effects.

Across 2,000 runs, the estimate's true standard deviation is 0.53. The usual OLS standard error averages 0.24, and the placebo comes out significant at 5% in 38% of runs. Clustered by city, the standard error averages 0.55, and the false-positive rate is about 4%.

A clustered standard error sums within each city before squaring

The fix is the same sandwich.

def cluster_se(X, y, cluster, j=-1):
    XtX_inv = np.linalg.inv(X.T @ X)
    resid = y - X @ (XtX_inv @ X.T @ y)
    groups = np.unique(cluster)
    meat = sum(np.outer(s, s) for s in
               (X[cluster == g].T @ resid[cluster == g] for g in groups))
    n, k, G = X.shape[0], X.shape[1], len(groups)
    V = XtX_inv @ meat @ XtX_inv * G / (G - 1) * (n - 1) / (n - k)
    return float(np.sqrt(V[j, j]))

Cluster on the unit that carries the correlation: here the city, which is usually also the unit that was treated.

The usual standard error treats each row's residual as its own piece of information. The clustered one first adds up, within each city, the rows weighted by their residuals: that sum is the city's score. Then it uses the spread of those 30 scores. Rows of one city that move together count as one lump, not 16 separate draws.

In the code, the inner generator makes each city's score, and sum adds up their outer products into meat. The inverse of X⊤XX^\top X goes on both sides, so it's called the sandwich formula. The last factors are a small-sample correction. j=-1 picks the last coefficient, δ\delta in both the four-mean regression and two-way fixed effects. The lesson Randomized by city, analyzed by user builds the same formula step by step.

On the practice data, where weeks are independent, clustering still moves one standard error

Clustering doesn't always move the standard error the way you'd guess.

Predict

The practice data's noise is independent from week to week. The four-mean regression's usual standard error is 0.30. Clustered by city, what happens?

Pick an answer above to see the rest

With few cities, the clustered standard error isn't enough

With few cities, even the clustered standard error is shaky.

Predict

With only a handful of cities, what's a safe analysis?

Pick an answer above to see the rest
Part 4 done
Part 5 of 6about 7 min
Rollouts

Staggered rollouts can break one regression when the effect changes over time

So far every treated city launched in the same week. Real rollouts come in waves.

Two waves launch in week 4 and week 10
041016 weeks
early wave
late wave
not launched yetlaunched
ComparisonWeeksWho is the control
1: early against late0 to 9the late wave, before it launches
2: late against early4 to 15the early wave, already launched

Launches rarely reach every treated city on the same day. They go out in waves, like the two in the figure. The natural move is the two-way fixed effects regression with DitD_{it} switching on at each city's own launch week. It looks like a straight generalization, and it's where the method breaks.

Goodman-Bacon showed what that regression computes: "the two-way fixed effects estimator equals a weighted average of all possible two-group/two-period DD estimators in the data."

  • Some of those comparisons are clean, like comparison 1: a wave that just launched, against cities that haven't launched yet.
  • Others, like comparison 2, use cities that launched earlier as the control group for a later wave.

If the effect is constant, that's harmless. If it grows over time, the early cities are still changing because of their own launch, and that change gets subtracted from the later wave's effect. In his words: "A causal interpretation of two-way fixed effects DD estimates requires both a parallel trends assumption and treatment effects that are constant over time."

In one rollout where every effect is positive, the regression returns -0.05

Here's how badly it can go.

city = np.repeat(np.arange(20), 16)
week = np.tile(np.arange(16), 20)
launch = np.where(city < 10, 4, 10)
D = (week >= launch).astype(float)
effect = np.where(D == 1, 0.5 * (week - launch + 1), 0.0)

print(f"true average effect:        {effect[D == 1].mean():.2f}")
print(f"regression, growing effect: {twfe(effect, city, week, D):.2f}")
print(f"regression, constant 3:     {twfe(3 * D, city, week, D):.2f}")
true average effect:        2.75
regression, growing effect: -0.05
regression, constant 3:     3.00

This is the rollout from the step before: two waves of 10 cities, launching in week 4 and week 10, over 16 weeks, with no city left untreated. The effect is 0.5 in a city's launch week and grows by 0.5 every week after. The outcome is the effect alone, with no noise. City levels and weekly shocks would change nothing, since the fixed effects absorb them.

Every treated city-week has a positive effect, and they average 2.75. The regression returns -0.05. It's a weighted average of the two comparisons:

ComparisonEstimateWeight
Early wave against the late wave, weeks 0 to 9, before the late wave launches1.750.4
Late wave against the early wave, weeks 4 to 15, after the early wave launched-1.250.6
The regression, weeks 0 to 15-0.05

The first row is right: 1.75 is the early wave's average effect over weeks 4 to 9.

The second row is the late wave's true effect over weeks 10 to 15, also 1.75, minus 3.0. That 3.0 is how much the early wave's own effect grew between the two windows: from 1.75 on average over weeks 4 to 9 to 4.75 over weeks 10 to 15.

Give every city-week the same effect of 3 instead, and the regression returns exactly 3.

Compare each wave only with cities that haven't launched yet

The fix is to choose the comparisons yourself.

Predict

With waves, which cities make a clean control group for a wave?

Pick an answer above to see the rest

When there's no good control group, build one or forecast

Everything so far needed a control group that moved like the treated one.

Is there a group the change didn't reach?Did it move like the treated group before launch?Use
yesyesdifference-in-differences
yesnosynthetic control: weight the untreated units so their blend tracks the treated one before launch
nointerrupted time series: forecast the treated series from its own past

When there isn't one, there are two standard answers.

Synthetic control weights untreated units so their blend tracks the treated one before launch

If no single group matches, build one.

Predict

No single untreated city moved like the treated one. What can you build instead?

Pick an answer above to see the rest

An interrupted time series forecasts the treated series from its own past

The hardest case is a global launch with no holdout (1 source). There's no untreated group at all, only the treated series before and after.

An interrupted time series fits the pre-launch series, trend and seasonality included. It forecasts what would have happened, and reads the effect as actual minus forecast. Its assumption is stronger than parallel trends: nothing else changed at launch, and the pre-launch pattern would have held.

Brodersen and coauthors' CausalImpact does this with a Bayesian structural time-series model that "predicts the counterfactual market response in a synthetic control that would have occurred had no intervention taken place," helped by control series the launch didn't affect.

Airbnb's Artificial Counterfactual Estimation, from a 2022 post, trains a machine learning model to predict the treated group's counterfactual (1 source). It uses A/A tests to debias its estimates and build confidence intervals (1 source).

Part 5 done
Part 6 of 6about 4 min
Follow-ups

What interviewers ask next

The practice problem names three follow-ups: staggered rollouts, synthetic control, and clustering the standard errors by city. Each has its own step earlier in the lesson. These come up too.

With a global launch, look for a hidden control group before you forecast

Predict

The launch reached every user at once. What do you look for first?

Pick an answer above to see the rest

The pre-trends aren't parallel. Now what? First look for a better control group: cities matched on their pre-launch path, or a synthetic control.

If you have to model the gap, fit the extra trend on pre-launch weeks only, extrapolate it, and report how much the estimate moved.

Don't add a treated-group trend fitted over all weeks, because it soaks up any effect that builds after launch. With parallel trends and an effect that starts at 2 and grows 0.25 a week, averaging 2.88 over the post weeks, that model returns 1.88.

Extrapolating the pre-launch trend is honest but noisy. With a real gap of 0.1 a week it recovers 2.02 against a true 2. But its standard deviation is 0.49, against 0.18 for the plain estimate, because any error in a slope grows as you project it 8 weeks forward.

Spillovers, composition and anticipation can break it too

What else could break it?

  • Spillovers. If the launch moves the control cities too, the control group's change is no longer the counterfactual. Riders might cross a city line, or supply might shift between markets. Pick controls the launch can't reach, or measure the spillover.
  • Composition. If the launch changes who shows up in the data, the post-launch average describes different people. Follow a fixed set of units from before launch.
  • Anticipation. If behavior moved at the announcement, the last pre-launch weeks are already treated. Put the reference period before the announcement.

The practice problem, start to finish

That's every piece of the practice problem, and the follow-ups after it. The simulation asks for all four functions under a timer, so rehearse the order once.

Check yourself
5 questions
  1. 1.Treated cities averaged 53.75 before launch and 63.5 after. Control cities averaged 41.75 and 47.5. What is the difference-in-differences estimate?

  2. 2.Your pre_trend_gap fits each group's slope on all 16 weeks of a practice panel. The trends are parallel and the effect is 2, starting at week 8. About what does it return?

  3. 3.Treated cities trend 0.3 a week faster than control cities, before and after launch. The pre weeks are 0 to 7, the post weeks 8 to 15, and the true effect is 2. What does difference-in-differences return on average?

  4. 4.Thirty cities, 16 weeks, a placebo launch with no real effect, and weekly shocks that carry over from one week to the next. You fit two-way fixed effects and use the plain OLS standard error. About how often is the placebo significant at 5%?

  5. 5.Two waves of cities launch in week 4 and week 10, every city ends up treated, and the effect grows each week after launch. Why can one two-way fixed effects regression return a negative number?

Where this shows up

The reports behind this lesson, each with its source.

Same L5 DS report, experimentation question: what if you cannot run an A/B test.

Candidate report·Aced, formerly Exponent (verified candidate report)Source

When a randomized test is not possible, Netflix uses quasi-experiments and causal inference.

“In these cases, we rely on quasi-experiments and causal inference methods to inform decisions.”
Company source·Netflix Research (research.netflix.com)Source

Staff, Advanced Analytics (Host Incentives) uses causal methods when randomized trials are not available.

“Leverage causal methods when traditional randomized trials aren’t available.”
Company source·Airbnb job posting (Greenhouse API; same text as careers.airbnb.com/positions/<id>)·2026-11-04Source

DS technical screen question (posted 2025-10-13, linked to the Oct 2025 report): estimate the causal lift of a feature launched globally with no holdout.

Prep site·PracHub (prep site question bank)·2025-10-13Source

Data Scientist, Growth involves designing and analyzing A/B tests and quasi-experiments across the growth funnel.

“Design and analyze A/B tests and quasi-experiments across activation, retention and monetization”
Company source·Anthropic job posting (Greenhouse)Source

Netflix runs controlled A/B tests on nearly every product change.

“We use controlled A/B experiments to test nearly all proposed changes to our product”
Company source·Netflix Research (research.netflix.com)Source

Causal inference survey (Jun 2024): Netflix uses a synthetic control framework with several variants.

“Our framework utilizes a variety of synthetic control (SC) models.”
Company source·Netflix Tech Blog, post 'Round 2: A Survey of Causal Inference Applications at Netflix' (full text read from the blog's Medium RSS feed; the post page itself returns 403)·2024-06-06Source

Artificial Counterfactual Estimation (Mar 2022, older): an ML model predicts the counterfactual outcome for the treated group.

“to train an ML model that predicts the counterfactual outcome”
Company source·Airbnb Tech Blog, post 'Artificial Counterfactual Estimation (ACE): Machine Learning-Based Causal Inference at Airbnb' (full text read from the blog's Medium RSS feed; the post page returns 403)·2022-03-16Source

ACE uses A/A tests to debias estimates and build confidence intervals.

“In ACE, we use A/A tests both for debiasing and for constructing confidence Intervals.”
Company source·Airbnb Tech Blog, post 'Artificial Counterfactual Estimation (ACE): Machine Learning-Based Causal Inference at Airbnb' (full text read from the blog's Medium RSS feed; the post page returns 403)·2022-03-16Source

Practice

Sources (9)
  1. Minimum Wages and Employment: A Case Study of the Fast-Food Industry in New Jersey and Pennsylvania · American Economic Review 84(4) · Sep 1, 1994
    “We find no indication that the rise in the minimum wage reduced employment.”
  2. How Much Should We Trust Differences-in-Differences Estimates? · Quarterly Journal of Economics 119(1) · Feb 1, 2004
    “These conventional DD standard errors severely understate the standard deviation of the estimators: we find an "effect" significant at the 5 percent level for up to 45 percent of the placebo interventions.”
  3. Difference-in-differences with variation in treatment timing · Journal of Econometrics 225(2) · Dec 1, 2021
    “A causal interpretation of two-way fixed effects DD estimates requires both a parallel trends assumption and treatment effects that are constant over time.”
  4. Difference-in-Differences with multiple time periods · Journal of Econometrics 225(2) · Dec 1, 2021
    “We show that a family of causal effect parameters are identified in staggered DiD setups, even if differences in observed characteristics create non-parallel outcome dynamics between groups.”
  5. Estimating dynamic treatment effects in event studies with heterogeneous treatment effects · Journal of Econometrics 225(2) · Dec 1, 2021
    “We show that in settings with variation in treatment timing across units, the coefficient on a given lead or lag can be contaminated by effects from other periods, and apparent pretrends can arise solely from treatment effects heterogeneity.”
  6. Pretest with Caution: Event-Study Estimates after Testing for Parallel Trends · American Economic Review: Insights 4(3) · Sep 1, 2022
    “First, conventional pre-trends tests may have low power.”
  7. Synthetic Control Methods for Comparative Case Studies: Estimating the Effect of California's Tobacco Control Program · NBER Working Paper 12831, published in JASA in 2010 · Jan 1, 2007
    “We estimate that by the year 2000 annual per-capita cigarette sales in California were about 26 packs lower than what they would have been in the absence of Proposition 99.”
  8. Using Synthetic Controls: Feasibility, Data Requirements, and Methodological Aspects · Journal of Economic Literature 59(2) · Jun 1, 2021
    “The main sections discuss the advantages of the synthetic control framework as a research design, and describe the settings where synthetic controls provide reliable estimates and those where they may fail.”
  9. Inferring causal impact using Bayesian structural time-series models · arXiv 1506.00356, Annals of Applied Statistics · Jun 1, 2015
    “This paper proposes to infer causal impact on the basis of a diffusion-regression state-space model that predicts the counterfactual market response in a synthetic control that would have occurred had no intervention taken place.”