Regression discontinuity (RD) estimates a treatment effect when treatment is assigned by a cutoff on a score: students below a test score get tutoring, customers above a spend threshold get a perk. People just either side of the cutoff are nearly identical, so the jump in the outcome at the cutoff is the effect. In Python you fit a local linear regression on a window around the cutoff, using smf.wls from statsmodels with an indicator for which side you're on. The code below targets statsmodels 0.14.
Quick Example
This simulates a placement exam where students scoring below 60 get a tutoring program. The true effect on the final grade is +4 points. Scores near the cutoff are otherwise comparable:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(41)
n = 3000
score = rng.normal(62, 12, n).clip(25, 100)
tutored = (score < 60).astype(int)
true_effect = 4.0
final = (20 + 0.55 * score + 0.002 * (score - 60) ** 2
+ true_effect * tutored + rng.normal(0, 5, n))
df = pd.DataFrame({"score": score, "tutored": tutored, "final": final})
df["x"] = df.score - 60 # running variable, centered at the cutoff
def rd_fit(d, h):
w = d[abs(d.x) <= h].copy()
w["wt"] = 1 - abs(w.x) / h # triangular kernel: weight falls to 0 at the edge
m = smf.wls("final ~ tutored + x + tutored:x", w, weights=w.wt).fit(cov_type="HC1")
return m.params["tutored"], m.bse["tutored"], len(w)
est, se, nn = rd_fit(df, h=10)
print(f"effect {est:.2f}, 95% CI [{est - 1.96 * se:.2f}, {est + 1.96 * se:.2f}], n={nn}")
The estimate is 3.53 points with a 95% interval of 2.48 to 4.59, using the 1,740 students within 10 points of the cutoff. It covers the true effect of 4.0. Centering the score at the cutoff (x = score - 60) means the tutored coefficient is the jump exactly at the cutoff. The tutored:x interaction lets the slope differ on each side.
What Is Regression Discontinuity?
Treatment depends on a running variable (the exam score) crossing a cutoff (60). Students at 59 and 61 differ by a few exam points but not much else, so the cutoff acts like a local coin flip for them. A jump in outcomes right at the cutoff can't come from the smooth trend in scores, so it is attributed to the treatment.
RD gives a causal estimate without randomization, but only at the cutoff, and only for people close to it. It says nothing about students who scored 30. Two assumptions carry the design:
- Continuity: without the treatment, outcomes would change smoothly through the cutoff.
- No precise manipulation: people can't sort themselves just above or below the line.
Draw the RD Plot
Plot binned averages of the outcome against the running variable, with the fitted lines on each side of the cutoff. This is the main evidence in an RD analysis, and the jump should be visible without the regression:
bins = np.arange(25, 100, 2.0)
df["bin"] = pd.cut(df.score, bins)
binned = df.groupby("bin", observed=True).agg(x=("score", "mean"), y=("final", "mean"),
n=("final", "size"))
h = 10
w = df[abs(df.x) <= h].copy()
w["wt"] = 1 - abs(w.x) / h
m = smf.wls("final ~ tutored + x + tutored:x", w, weights=w.wt).fit()
p = m.params
fig, ax = plt.subplots(figsize=(7.5, 4.8))
ax.scatter(binned.x, binned.y, s=binned.n.clip(upper=120) * 0.7 + 8, color="#94a3b8",
alpha=0.9, label="Binned mean (2-point bins)")
xs = np.linspace(-h, 0, 20)
ax.plot(xs + 60, p["Intercept"] + p["tutored"] + (p["x"] + p["tutored:x"]) * xs,
color="#e11d48", lw=3, label="Local linear fit, tutored")
xs = np.linspace(0, h, 20)
ax.plot(xs + 60, p["Intercept"] + p["x"] * xs, color="#2563eb", lw=3,
label="Local linear fit, not tutored")
ax.axvline(60, color="#0f172a", ls="--", lw=1)
ax.set(xlabel="Placement exam score (tutoring if below 60)", ylabel="Final grade",
title="Regression discontinuity at the tutoring cutoff")
ax.legend(loc="upper left")

Marker size shows how many students fall in each bin. Grades rise smoothly with exam score away from the cutoff, and at 60 the red (tutored) line sits about 3.5 points above where the blue (not tutored) line starts. The tutored students scored lower on the exam but end up with higher final grades than the trend predicts, which is the program's effect.
Why a Local Linear Fit and Not One Line for All the Data?
Fitting a single straight line across all scores ignores curvature. If the true relationship bends, the line's error near the cutoff turns into a fake jump. The standard fix is to fit separate lines on each side using only observations near the cutoff, which is the h=10 window above. The triangular weights give the points closest to the cutoff the most influence.
A narrower window removes more curvature bias but leaves fewer observations. A wider window is more precise but depends more on the line being right. That trade-off is the bandwidth choice.
How Sensitive Is the Estimate to the Bandwidth?
Refit across a range of bandwidths and look for a stable answer:
hs = np.arange(4, 26, 1.0)
res = [rd_fit(df, hh) for hh in hs]
effs = np.array([r[0] for r in res])
ses = np.array([r[1] for r in res])
fig, ax = plt.subplots(figsize=(7.5, 4.2))
ax.fill_between(hs, effs - 1.96 * ses, effs + 1.96 * ses, color="#c4b5fd", alpha=0.6, label="95% CI")
ax.plot(hs, effs, color="#6d28d9", lw=2.5, label="Estimated jump")
ax.axhline(true_effect, color="#0f172a", ls="--", lw=1, label="True effect (4.0)")
ax.axhline(0, color="#94a3b8", lw=1)
ax.set(xlabel="Bandwidth (exam points on each side of the cutoff)",
ylabel="Estimated effect on final grade", title="The estimate across bandwidths")
ax.legend(loc="lower right")

| Bandwidth | Estimate | 95% half-width | Students used |
|---|---|---|---|
| 5 | 3.94 | 1.52 | 931 |
| 10 | 3.53 | 1.05 | 1,740 |
| 15 | 3.56 | 0.86 | 2,342 |
| 20 | 3.70 | 0.76 | 2,710 |
The estimate stays between about 3.5 and 4.1 and the interval shrinks as the window grows, all with zero well outside the band. That stability is what you want to see. If the estimate swung across zero as the bandwidth changed, the finding would be fragile. For a data-driven bandwidth, the rdrobust package implements the standard MSE-optimal selector and robust confidence intervals. This post sticks with statsmodels so you can see every step.
Check for Manipulation at the Cutoff
If students (or graders) could nudge scores to land just under 60 to get tutoring, the people on each side wouldn't be comparable. A histogram of the running variable should show no pile-up or gap at the cutoff:
fig, ax = plt.subplots(figsize=(7.5, 3.8))
ax.hist(df.score, bins=np.arange(25, 101, 2), color="#38bdf8", edgecolor="white")
ax.axvline(60, color="#0f172a", ls="--", lw=1)
ax.set(xlabel="Placement exam score", ylabel="Students",
title="No pile-up of students just above or below the cutoff")
print("students within 4 points below:", ((df.score >= 56) & (df.score < 60)).sum())
print("students within 4 points above:", ((df.score >= 60) & (df.score < 64)).sum())

There are 364 students in the four points below the cutoff and 375 in the four points above, and the histogram is smooth across the line. Formal versions of this test (McCrary, or the rddensity package) compare the density estimates on each side. In real data, also check that other pre-treatment variables (age, prior grades) don't jump at the cutoff.
Run Placebo Cutoffs
Applying the same method at cutoffs where nothing happens should find nothing. Use only data from one side of the real cutoff so the real treatment can't contaminate the test:
for c in (50, 70):
d2 = df[df.score < 60].copy() if c == 50 else df[df.score >= 60].copy()
d2["x"] = d2.score - c
d2["tutored"] = (d2.score < c).astype(int)
e, s, k = rd_fit(d2, h=8)
print(f"placebo cutoff {c}: {e:.2f} +/- {1.96 * s:.2f}")
Both fake cutoffs come back with intervals that include zero: -0.91 ± 1.36 at 50 and -0.61 ± 1.20 at 70. A placebo that shows a jump means the real estimate may be picking up something other than the program.
Sharp vs Fuzzy Regression Discontinuity
Everything above is a sharp design: crossing the cutoff determines treatment for everyone. In a fuzzy design, crossing the cutoff only raises the probability of treatment (some eligible people decline, some ineligible get it anyway). Then you scale the jump in the outcome by the jump in treatment rates, which is an instrumental-variables estimate. The rdrobust package supports it with a fuzzy= argument.
Practical Tips
- Show the RD plot first. A convincing effect is visible in the binned means, and a regression that finds one the plot doesn't show deserves suspicion.
- Use local linear, not high-order polynomials. Fitting a cubic or quartic to all the data is known to give erratic estimates near the boundary.
- Report several bandwidths, not just one, as in the table above.
- Cluster standard errors if observations share a group (classroom, store) the way the rule might.
- Interpret locally. The effect applies to people at the cutoff. Extrapolating to everyone assumes more than the design provides.
- Beware coarse running variables. If scores only take a few distinct values near the cutoff, there is no continuous neighborhood to work with.