12/36
Part 3 of 6 · Parallel trendsLearn and do

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.