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_trenda 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 = 0 | Weeks 8 to 15, post = 1 | |
|---|---|---|
| 15 treated cities, treated = 1 | T0: 120 rows | T1, policy on: 120 rows |
| 15 control cities, treated = 0 | C0: 120 rows | C1, 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.