Module contents
Stage 7 of 9Advanced 90 min

Regression discontinuity

Use public election data to estimate an effect at a threshold with local linear regression, bandwidth selection, and robust bias-corrected intervals. Examine density, predetermined covariates, and placebo cutoffs as validity diagnostics.

After this lesson you can

  • Implement local linear regression with a triangular kernel on both sides of the threshold.
  • Choose bandwidths and calculate robust bias-corrected intervals.
  • Apply density, covariate balance, and placebo cutoff diagnostics.
  • Explain why high-degree global polynomials are discouraged.

Before you start

Deciding at a threshold

A very close election can change who holds a seat by a small vote difference. In sharp regression discontinuity, treatment changes when a running variable XX crosses a known threshold. If potential outcomes are continuous there, the difference between right and left limits identifies a local effect; it does not automatically describe elections won by large margins.

We use the public Senate election extract from the rdrobust authors: Democratic victory margin in one election and Democratic vote share in the next election for that seat. Documentation describes the outcome as t+2t+2 in its cycle coding; the tool’s article relates it to the next election for that seat, six years later. The data illustrate party advantage in the Senate and relate to Lee’s House design; they are not the same sample. There are 1,297 rows with observed outcome and margin.

Treatment is the Democratic party winning the seat at zero margin. Causal interpretation requires other relevant characteristics and potential outcomes to evolve continuously across zero and the observed outcome to be comparable. The later outcome may be selectively missing; this demonstration uses complete cases, which also needs examination. The data cover historical elections, not a current election forecast.

Fitting near the cutoff

Local polynomial regression fits a function on each side, weighting observations near the threshold more heavily. For degree one, ui=Xi−cu_i=X_i-c, and triangular kernel K(v)=max⁡(1−∣v∣,0)K(v)=\max(1-|v|,0), minimize ∑iK(ui/h)[Yi−as−bsui]2\sum_iK(u_i/h)[Y_i-a_s-b_su_i]^2 separately on each side ss. The estimated jump is a^+−a^−\hat a_+-\hat a_-. HC0 errors use residuals and effective regression weights; the interactive interval is conventional and does not correct smoothing bias.

InteractiveWhat changes when moving the window
0255075100-50-2502550Democratic margin (points)

Lines show predictions; the dashed line marks the threshold. The vertical axis is later vote percentage. Increasing degree or bandwidth does not turn the fit into a reliable effect.

20
Estimated jump7.27
Conventional 95% CI4.57 to 9.97
Senate election points. Browser calculations use conventional HC0 intervals; the lab calculates robust bias correction.

The scatter shows observations with margins between -50 and 50 points. Models use all observations within the chosen bandwidth, including outside that axis when h>50h>50; curves are clipped to the plotting area. With h=100h=100 and degree four it illustrates an almost global fit. High-degree polynomials can oscillate, concentrate influence at extremes, and give degree-sensitive jumps; a good global fit does not ensure a good local fit. Changing kernel, degree, and window is a diagnostic, not a search for the preferred result.

A small hh reduces local approximation bias but uses fewer data and usually increases variance; a large one can introduce unmodeled curvature. The lab implements two educational rules over candidates 10, 15, 20, 25, and 30 points: leave-one-out predictive validation evaluated on the same fixed region ∣X∣≤10|X|\le10, and an approximate jump MSE combining HC0 variance and bias calculated with a 30-point quadratic pilot. Both selected 30 in this run; they are discrete rules with pilot choices, not the CCT selector or a guarantee of a global optimum. Predictive validation of YY is not identical to optimizing jump error.

Bias and interval

An MSE-optimal bandwidth can leave bias of the same order as the standard error. Robust bias correction estimates curvature with a local quadratic regression of bandwidth bb, subtracts estimated bias from the linear jump, and calculates variance including correction uncertainty. Moving the point estimate while retaining the conventional standard error is insufficient. Calonico, Cattaneo, and Titiunik explain robust inference and its conditions.

On one side, let PP be the matrix with columns 1,u1,u, WhW_h the diagonal triangular weights, and γ^2\hat\gamma_2 the u2u^2 coefficient of the quadratic fit with bandwidth bb. The corrected intercept subtracts e1⊤(P⊤WhP)−1P⊤Whu2γ^2e_1^\top(P^\top W_hP)^{-1}P^\top W_hu^2\hat\gamma_2 from a^\hat a, where e1e_1 selects the intercept. An observation may contribute to both fits: robust variance uses the combined influence weight of linear estimation and correction, with quadratic-fit residuals. Jump variance sums both sides’ contributions under independent observations. This explains why bandwidth bb also matters for the interval.

The custom matrix implementation uses rdrobust’s MSE selector to set h=17,683h=17,683 and b=28,090b=28,090, triangular kernel, and HC0. The conventional jump is 7.417 percentage points; the corrected jump is 7.506, with robust standard error 1.739 and 95% normal interval [4.097, 10.915]. All five values agree with rdrobust beyond the third decimal in this run. The conventional interval, centered at 7.417, is [4.560, 10.274]. The two earlier custom bandwidth estimators are educational alternatives; the complete CCT selector is not claimed to be reimplemented.

Observations can be dependent within a state. As sensitivity we use rdrobust with state clustering and CR1, retaining both bandwidths: robust standard error 1.791 and interval [3.995, 11.017]. Validity requires enough clusters and additional conditions. The custom HC0 test assumes independent observations and does not replace the clustered analysis.

Is the discontinuity credible?

Validity checks look for observable incompatibilities. A discontinuity in margin density can suggest manipulation or selection around the cutoff, though other process characteristics may also explain it. rddensity returns jackknife statistic -0.760 and p=0,447p=0,447 for these complete rows. This run does not cluster by state; dependence across elections can affect calibration. Failure to reject does not prove continuous density or absence of manipulation: the test can have low power and depends on its method.

As predetermined covariates we test seat class, coded as a class 3 indicator, and election year. Using the outcome bandwidths, corrected jumps were 0.010 and 0.972, with p=0,912p=0,912 and p=0,839p=0,839 respectively. These are exploratory diagnostics, not balance tests for every variable. Terms or characteristics after the election outcome should not automatically be treated as predetermined.

At false cutoffs -15 and +15 points, only the corresponding side of the true cutoff and bandwidth 8 are used to avoid mixing in the real threshold. Corrected jumps were -7.144 and -2.138, with p=0,185p=0,185 and p=0,631p=0,631. Neither is rejected at 5% in this run; this does not prove zero effects at those cutoffs. Multiplicity has not been adjusted and cutoffs are not random choices. Also inspect histograms, assignment rules, and context-supported covariates.

In fuzzy RD, crossing the threshold changes treatment probability without determining treatment for everyone. The ratio of the outcome jump to the treatment-probability jump is a local instrumental effect under relevance, exclusion, and other necessary assumptions; it should not be confused with the reduced-form jump when the first stage is less than one.

Laboratory

In Python 3.12 install python -m pip install "numpy==2.2.6" "scipy==1.15.3" "pandas==2.3.3" "scikit-learn==1.6.1" "rdrobust==2.1.1" "rddensity==3.0". Download rd.py, test_rd.py, and experiment.py. The results and points include bandwidths, estimates, and versions. Run python test_rd.py and python experiment.py --data data/rdrobust_senate.csv --out results.json. The script downloads the authors’ CSV at revision a9e62bf776d42c8284aabf16916860cd1fe867df, verifies its SHA-256, and does not overwrite results. The cell repeats tests, diagnostics, and comparisons.

[ ]Regression discontinuity in the SenateLocal GPU
"""RD local lineal y corrección de sesgo mediante matrices NumPy."""
import numpy as np

def _weights(u,h,kernel):
    t=np.abs(u/h)
    if kernel=='triangular':return np.maximum(1-t,0)/h
    if kernel=='uniform':return (t<1).astype(float)/(2*h)
    if kernel=='epanechnikov':return .75*np.maximum(1-t*t,0)/h
    raise ValueError('Kernel desconocido')

def _side(x,y,h,b,kernel,degree=1):
    u=np.asarray(x,float);y=np.asarray(y,float)
    valid=np.abs(u)<max(h,b);u=u[valid];y=y[valid]
    wh=_weights(u,h,kernel);wb=_weights(u,b,kernel)
    P=np.column_stack([u**j for j in range(degree+1)])
    Q=np.column_stack([u**j for j in range(degree+2)])
    if (wh>0).sum()<=degree+1 or (wb>0).sum()<=degree+2:raise ValueError('Muy pocos puntos')
    G=P.T@(wh[:,None]*P);H=Q.T@(wb[:,None]*Q)
    left=np.linalg.solve(G,P.T*wh);right=np.linalg.solve(H,Q.T*wb)
    linear=left@y;quadratic=right@y
    projection=np.linalg.solve(G,P.T@(wh*u**(degree+1)))
    corrected=linear[0]-projection[0]*quadratic[-1]
    influence=left[0]-projection[0]*right[-1]
    res_p=y-P@linear;res_q=y-Q@quadratic
    var_conventional=float(np.sum((left[0]*res_p)**2))
    var_robust=float(np.sum((influence*res_q)**2))
    return float(linear[0]),float(corrected),var_conventional,var_robust

def local_linear_rd(x,y,cutoff=0.,h=20.,b=None,kernel='triangular'):
    x,y=np.asarray(x,float),np.asarray(y,float)
    if x.ndim!=1 or y.shape!=x.shape or not np.isfinite(x).all() or not np.isfinite(y).all() or h<=0:raise ValueError('Datos o ancho inválidos')
    b=h if b is None else float(b)
    if b<=0:raise ValueError('Ancho de sesgo inválido')
    u=x-cutoff;left=_side(u[u<0],y[u<0],h,b,kernel);right=_side(u[u>=0],y[u>=0],h,b,kernel)
    estimate=right[0]-left[0];corrected=right[1]-left[1]
    se=np.sqrt(left[2]+right[2]);se_rb=np.sqrt(left[3]+right[3])
    return {'estimate':float(estimate),'se':float(se),'bias_corrected':float(corrected),'se_robust':float(se_rb),
            'ci_robust':[float(corrected-1.959963984540054*se_rb),float(corrected+1.959963984540054*se_rb)]}

def bandwidth_cv(x,y,candidates,validation_radius=10.):
    """LOO en una región fija; elección predictiva, no selector CCT de MSE del salto."""
    x,y=np.asarray(x,float),np.asarray(y,float);scores=[]
    for h in candidates:
        errors=[]
        for side in (x<0,x>=0):
            u=x[side];v=y[side];w=_weights(u,h,'triangular');P=np.column_stack([np.ones(len(u)),u])
            G=P.T@(w[:,None]*P);inverse=np.linalg.inv(G);beta=inverse@(P.T@(w*v))
            leverage=w*np.einsum('ij,jk,ik->i',P,inverse,P)
            mask=np.abs(u)<=validation_radius
            errors.extend(((v[mask]-P[mask]@beta)/(1-leverage[mask]))**2)
        scores.append(float(np.mean(errors)))
    i=int(np.argmin(scores));return float(candidates[i]),scores

def bandwidth_mse_grid(x,y,candidates,pilot=30.):
    """MSE plug-in aproximado en rejilla: curvatura y varianza HC0 piloto."""
    if pilot<=0 or not candidates or any(h<=0 or h>pilot for h in candidates):
        raise ValueError('Candidatos positivos no mayores que el piloto')
    x,y=np.asarray(x,float),np.asarray(y,float);states=[]
    for side in (x<0,x>=0):
        u=x[side];v=y[side];mask=np.abs(u)<pilot;u=u[mask];v=v[mask]
        q=np.column_stack([np.ones(len(u)),u,u*u]);w=_weights(u,pilot,'triangular')
        beta=np.linalg.solve(q.T@(w[:,None]*q),q.T@(w*v));residual=v-q@beta
        states.append((u,residual,beta[2]))
    scores=[]
    for h in candidates:
        biases=[];variances=[]
        for u,residual,curvature in states:
            p=np.column_stack([np.ones(len(u)),u]);w=_weights(u,h,'triangular')
            influence=np.linalg.solve(p.T@(w[:,None]*p),p.T*w)[0]
            biases.append(float(curvature*(influence@(u*u))))
            variances.append(float(np.sum((influence*residual)**2)))
        scores.append((biases[1]-biases[0])**2+sum(variances))
    return float(candidates[int(np.argmin(scores))]),[float(x) for x in scores]

"""Contrastar salto, HC0 y corrección de sesgo con rdrobust."""
import numpy as np
from rdrobust import rdrobust

rng=np.random.default_rng(701);x=rng.uniform(-1,1,3000)
y=1.5+2*(x>=0)+x+2*x*x+rng.normal(0,.4,len(x))
for h,b,kernel in [(.5,.7,'triangular'),(.7,.7,'triangular'),(.8,.5,'triangular'),(.6,.8,'uniform')]:
    a=local_linear_rd(x,y,h=h,b=b,kernel=kernel)
    r=rdrobust(y,x,h=h,b=b,kernel=kernel,vce='hc0')
    assert np.allclose([a['estimate'],a['se'],a['bias_corrected'],a['se_robust'],*a['ci_robust']],
        [r.coef.loc['Conventional','Coeff'],r.se.loc['Conventional','Std. Err.'],r.coef.loc['Robust','Coeff'],
         r.se.loc['Robust','Std. Err.'],r.ci.loc['Robust','CI Lower'],r.ci.loc['Robust','CI Upper']],atol=1e-8)
    assert abs(a['bias_corrected']-2)<.15
candidates=[.3,.5,.8]
choice,scores=bandwidth_cv(x,y,candidates,validation_radius=.3)
assert choice==candidates[int(np.argmin(scores))] and np.isfinite(scores).all()
choice,scores=bandwidth_mse_grid(x,y,candidates,pilot=.9)
assert choice==candidates[int(np.argmin(scores))] and np.isfinite(scores).all()
print('RD, HC0, corrección de sesgo y selectores contrastados')
"""Senado: RD, selectores, falsos umbrales y diagnósticos."""
import argparse,hashlib,json,platform,urllib.request
from importlib.metadata import version
from pathlib import Path
import numpy as np
import pandas as pd
import scipy
from scipy.stats import norm
import rdrobust as rdpackage
import rddensity as densitypackage
from rdrobust import rdrobust
from rddensity import rddensity

REVISION='a9e62bf776d42c8284aabf16916860cd1fe867df'
URL=f'https://raw.githubusercontent.com/rdpackages/rdrobust/{REVISION}/Python/rdrobust_senate.csv'
SHA256='def1fc6b8ae5af273f2140aa449c81b3ecfe1d0f325aa80ceccb0d9638a2ad44'

def load_data(path):
    path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
    if not path.exists():
        with urllib.request.urlopen(URL,timeout=90) as r:data=r.read()
        if hashlib.sha256(data).hexdigest()!=SHA256:raise ValueError('Hash inesperado')
        path.write_bytes(data)
    if hashlib.sha256(path.read_bytes()).hexdigest()!=SHA256:raise ValueError('Archivo modificado')
    data=pd.read_csv(path).dropna(subset=['vote','margin']).copy()
    if len(data)!=1297:raise ValueError('Tamaño inesperado')
    return data

def run(path):
    d=load_data(path);x=d.margin.to_numpy(float);y=d.vote.to_numpy(float)
    ref=rdrobust(y,x,vce='hc0');h=float(ref.bws.loc['h','left']);b=float(ref.bws.loc['b','left'])
    own=local_linear_rd(x,y,h=h,b=b)
    assert np.allclose([own['estimate'],own['bias_corrected'],own['se_robust'],*own['ci_robust']],
        [ref.coef.loc['Conventional','Coeff'],ref.coef.loc['Robust','Coeff'],ref.se.loc['Robust','Std. Err.'],
         ref.ci.loc['Robust','CI Lower'],ref.ci.loc['Robust','CI Upper']],atol=1e-8)
    cv,scores=bandwidth_cv(x,y,[10,15,20,25,30],validation_radius=10.)
    mse,mse_scores=bandwidth_mse_grid(x,y,[10,15,20,25,30],pilot=30.)
    density=rddensity(x)
    cluster=rdrobust(y,x,h=h,b=b,cluster=d.state.to_numpy(),vce='cr1')
    controls={}
    for name,arr in [('class3',(d['class']==3).to_numpy(float)),('year',d.year.to_numpy(float))]:
        r=rdrobust(arr,x,h=h,b=b,vce='hc0')
        controls[name]={'estimate':float(r.coef.loc['Robust','Coeff']),
                        'p':float(r.pv.loc['Robust','P>|z|'])}
    placebos=[]
    for cutoff in (-15.,15.):
        mask=x<0 if cutoff<0 else x>0
        r=rdrobust(y[mask],x[mask],c=cutoff,h=8,b=8,vce='hc0')
        placebos.append({'cutoff':cutoff,'estimate':float(r.coef.loc['Robust','Coeff']),
                         'p':float(r.pv.loc['Robust','P>|z|']),
                         'ci':[float(r.ci.loc['Robust','CI Lower']),float(r.ci.loc['Robust','CI Upper'])]})
    return {'source':{'revision':REVISION,'sha256':SHA256},'n':len(d),'h_cct':h,'b_cct':b,
            'cv':{'candidates':[10,15,20,25,30],'validation_radius':10.,'choice':cv,'scores':scores},
            'mse_grid':{'candidates':[10,15,20,25,30],'pilot':30.,'choice':mse,'scores':mse_scores},
            'own':own,'reference_p':float(ref.pv.loc['Robust','P>|z|']),
            'cluster_cr1':{'se':float(cluster.se.loc['Robust','Std. Err.']),
                           'ci':[float(cluster.ci.loc['Robust','CI Lower']),float(cluster.ci.loc['Robust','CI Upper'])]},
            'density':{'stat':float(density.test['t_jk']),'p':float(density.test['p_jk'])},
            'controls':controls,'placebos':placebos,'x':x.tolist(),'y':y.tolist(),
            'versions':{'python':platform.python_version(),'numpy':np.__version__,'pandas':pd.__version__,
                        'scipy':scipy.__version__,'rdrobust':version('rdrobust'),'rddensity':version('rddensity')}}


result=run('data/rdrobust_senate.csv')
print({k:v for k,v in result.items() if k not in ('x','y')})
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Quiz
The histogram has a spike just to the right of the cutoff. What would you do?
Quiz
Only 70% of eligible people receive treatment and some ineligible people receive it too. Which design applies?
Numeric
The outcome jump is 6 and the treatment-probability jump is 0.6. What is the local Wald ratio?
Code
Implement local_linear_rd(x, y, cutoff, h): return the right-minus-left jump and conventional HC0 standard error. Fit each side with intercept and slope, triangular weights max(1−|x−cutoff|/h,0), using only points with positive weight. x and y are finite arrays and each side has at least three points.
def local_linear_rd(x, y, cutoff, h):
  pass
Shift+Enter to run

Summary

Key idea
RD compares local limits under continuity and a defensible assignment mechanism. Bandwidth, bias, dependence, and validity checks must accompany the estimated jump.