20When you can't run an A/B test: difference-in-differences (NumPy)

mediumnumpy
40:00

20 When you can't run an A/B test: difference-in-differences (NumPy)

An OpenAI senior data scientist report asks "what if you cannot run an A/B test?" (1 report). Netflix says it uses quasi-experiments and causal inference when a randomized test isn't possible (1 source), an Airbnb posting uses causal methods when randomized trials aren't available (1 source), and a prep site lists an Airbnb screen on the lift of a feature launched with no holdout (abnb-059, guide only). Difference-in-differences is the first tool to reach for.

Half the cities got a policy starting in some week; the rest never did. Arrays are one row per city per week. Write in solution.py:

Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/20_diff_in_diff -k level1. Earlier levels must keep passing.

Level 1. did_estimate(y, treated, post): (treated after minus treated before) minus (control after minus control before), using group means.

Level 2. pre_trend_gap(y, treated, week, start_week): using only weeks before start_week, the slope of the treated cities' weekly mean minus the slope of the control cities' weekly mean (least squares on week). Near zero is what parallel trends look like.

Level 3. placebo_estimate(y, treated, week, fake_start, real_start): the estimate with a fake launch at fake_start, on the weeks before real_start only. Weeks from fake_start on count as after, the same way post marks the launch week as after. With parallel trends it finds nothing.

Level 4. event_study(y, treated, week, start_week): for every week, the treated cities' mean minus the control cities' mean, minus that gap in the last week before launch. One number per week, in week order.

Things to get right: why the after-only comparison is biased when the groups start at different levels, why the before/after comparison inside the treated group picks up the common trend, the regression form y ~ treated + post + treated:post (its interaction coefficient is the same number), and what a pre-trend gap means for trusting the estimate. Follow-ups: staggered rollouts, synthetic control, and clustering the standard errors by city (problem 19).

solution.py
Run the tests to see which pass.