Module contents
Lesson 21 of 28Core 110 min

Regression discontinuity designs

Regression discontinuity identifies local effects at a cutoff under continuity. Study sharp and fuzzy designs, local polynomial fits, bandwidth and robust bias correction, validity diagnostics, and election applications.

After this lesson you can

  • Formalize sharp and fuzzy RD with potential outcomes and continuity.
  • Implement local polynomial estimation with a triangular kernel and bandwidth selection.
  • Construct robust bias-corrected intervals and explain conventional undercoverage.
  • Use density, balance, and placebo diagnostics to assess design credibility.
  • Study Lee’s election incumbency analysis and distinguish the Senate example.

Before you start

A decision changes at the threshold

A team manually reviews alerts whose risk score exceeds a threshold. Two alerts with very close scores on opposite sides receive different decisions. Can comparing their outcomes estimate the review effect? It can near the cutoff if average trajectories would have been continuous there without the decision change. The rule alone does not guarantee continuity.

InteractiveThe jump at the threshold

The points are a fixed sample; the more visible points enter the local fit. Curves are polynomials estimated separately on each side. The jump is the difference between their intercepts at zero.

9.1−3.2−1.0−0.50.00.51.0Running variable X
  • Observations
  • Fit by side
  • Local window

Reproducible DGP: 240 fixed evenly spaced values in [−1,1], Y=0.5+0.4X+1{X≥0}(τ+6X²)+ε, independent normal ε with σ=1; seed 2721. The slider changes τ without regenerating noise. Local fits use a triangular kernel. The global degree-5 fit uses uniform weights and the entire sample, so it does not depend on h.

The interval uses the linear jump corrected by a quadratic pilot fit with bandwidth b=1. Its standard error incorporates the entire combination of weights, including covariance between estimate and correction, and uses known σ. With this quadratic conditional expectation and Gaussian errors it is an exact conditional normal interval for τ in this model. Orange lines show the uncorrected fit: its jump can differ from the interval center.

This known-variance demonstration does not implement rdrobust’s heteroskedastic variance. For robust bias-corrected inference and data-driven bandwidths, see Calonico, Cattaneo y Titiunik (2014).

0.60
1.0
Fit
Fitted jump1.003
Corrected jump1.262
Pointwise 95% CI[0.428; 2.096]
Adjust bandwidth and observe both fits, the jump, and its interval under the shown model.

Sharp RD: an effect at the cutoff

In sharp regression discontinuity, assignment variable XX and threshold cc determine D=1{X≥c}D=1\{X\ge c\}. Let Y(0),Y(1)Y(0),Y(1) be potential outcomes. Assume consistency, support for XX on both sides of the cutoff, and versions md(x)=E[Y(d)∣X=x]m_d(x)=E[Y(d)\mid X=x] continuous at cc for d=0,1d=0,1. Then

lim⁡x↓cE[Y∣X=x]−lim⁡x↑cE[Y∣X=x]=m1(c)−m0(c)=E[Y(1)−Y(0)∣X=c].\begin{aligned} \lim_{x\downarrow c}E[Y\mid X=x] -\lim_{x\uparrow c}E[Y\mid X=x] &=m_1(c)-m_0(c)\\ &=E[Y(1)-Y(0)\mid X=c]. \end{aligned}

The value conditioned on a point of a continuous variable is understood using those continuous versions. The first equality uses the rule and consistency; the second uses linearity of expectation. The result is local: it does not automatically identify the average effect far from the threshold. Nor does it require two particular units to be identical or turn every comparison within a window into a randomized experiment.

Two local fits

Instead of fitting one global polynomial, approximate the mean on each side using nearby observations. With ui=(Xi−c)/hu_i=(X_i-c)/h, triangular kernel K(u)=(1−∣u∣)1{∣u∣≤1}K(u)=(1-|u|)1\{|u|\le1\}, and bandwidth h>0h>0, estimate coefficients of YiY_i on (1,ui)(1,u_i) by weighted least squares separately on the left and right. The intercept difference is the estimated jump. Bandwidth changes both which observations enter and their weights.

A high-degree global polynomial can oscillate and let distant observations disproportionately influence the cutoff. Gelman and Imbens study these problems; a local line or quadratic reduces reliance on one global functional form but still requires bandwidth choice and smoothness justification.

Local polynomial means approximating each side near the boundary. In the lab you will compare the line with the model’s known curvature and see what happens when the interval uses or ignores bias.

Bandwidth changes bias and uncertainty

For a triangular local line, define one-sided moments μj=∫01uj(1−u) du\mu_j=\int_0^1u^j(1-u)\,du. The first four are 1/2,1/6,1/12,1/201/2,1/6,1/12,1/20. With two one-sided derivatives, positive regular density at the cutoff, and a common bandwidth, the leading jump-bias expansion is

Bias⁡(τ^h)=−h220{m1′′(c+)−m0′′(c−)}+o(h2).\operatorname{Bias}(\widehat\tau_h) =-\frac{h^2}{20}\{m_1''(c+)-m_0''(c-)\}+o(h^2).

Here m1m_1 and m0m_0 are the relevant potential means on observed sides. The sign comes from the one-sided equivalent kernel (1−u)(6−12u)(1-u)(6-12u): its second moment is −1/10-1/10, multiplied by h2m′′/2h^2m''/2. With different bandwidths retain each side’s term separately.

Leading variance decreases as 1/(nh)1/(nh), while squared bias grows as h4h^4. The bandwidth minimizing mean squared error balances both terms. In the explicit lab example, XX is uniform on [−1,1][-1,1], noise variance is one, and the mean is τ1{x≥0}+qx21{x≥0}\tau1\{x\ge0\}+q x^2 1\{x\ge0\}. For q≠0q\ne0 the expansion gives

Bias⁡≃−qh210,Var⁡≃965nh,hMSE=(480nq2)1/5.\operatorname{Bias}\simeq-\frac{qh^2}{10},\qquad \operatorname{Var}\simeq\frac{96}{5nh},\qquad h_{\rm MSE}=\left(\frac{480}{nq^2}\right)^{1/5}.

This is an oracle selector for that known model and an asymptotic approximation, not a universal selector knowing real-data curvature. If q=0q=0, this bias term vanishes and the bandwidth formula no longer applies.

InteractiveBias, variance, and coverage

Top: variance, squared bias and mean squared error of the linear jump. Bottom: fraction of intervals containing the true jump. The vertical line marks the selected bandwidth.

0.480Pointwise interval coverage100%0%95%0.20.40.60.81.0Bandwidth h
  • Variance
  • Bias²
  • MSE
  • Conventional coverage
  • Corrected coverage
  • 95 % nominal

These are 2,000 independent simulated Gaussian-error samples, using the same fixed design of 240 points and quadratic conditional expectation as the previous chart: jump 1, right curvature 6 and σ=1. The seed is 2721; the same samples are reused to compare bandwidths. Values are frequencies and moments from that simulation, not published results.

Correction uses a quadratic pilot with b=1 and the variance of all joint weights. Both intervals use known σ and the normal quantile; here the corrected interval has 95% conditional theoretical coverage due to the exact quadratic form. At h=0.60, theoretical conventional coverage is 90.9 %; Monte Carlo frequencies can differ. This does not guarantee exact coverage for other conditional means, sample sizes or unknown variances.

MSE averages squared errors; sample variance uses denominator 1,999, so adding it to bias² can differ slightly from MSE. The bandwidth minimizing estimation MSE is not necessarily optimal for coverage. See Calonico, Cattaneo y Farrell (2020).

4
Bandwidth h0.60
Empirical bias−0.209
Empirical MSE0.179
Conventional coverage90.50 %
Corrected coverage95.00 %
Compare mean squared error and conventional and corrected coverage in a reproducible model.

With hh of order n−1/5n^{-1/5}, bias may remain comparable with standard error. The conventional interval centered on the line may fail nominal coverage. Robust bias correction estimates the leading term with a higher-degree fit and subtracts it; it also calculates uncertainty of the entire combination, including bias-estimation uncertainty and covariance with the initial fit. Subtracting bias while keeping the old standard error does not itself produce a robust interval. The bandwidth optimal for estimating the jump is not generally optimal for coverage. See Calonico, Cattaneo and Titiunik and Calonico, Cattaneo and Farrell.

Fuzzy RD: a local first stage

In fuzzy RD, crossing the cutoff changes treatment probability but does not determine it perfectly. Let ΔY\Delta_Y be the outcome-mean jump and ΔD\Delta_D the treatment-probability jump. With appropriate continuity of potential outcomes and treatments, cutoff-side exclusion except through treatment, monotonicity, and a nonzero first stage,

τFRD=ΔYΔD\tau_{\rm FRD}=\frac{\Delta_Y}{\Delta_D}

identifies a LATE for compliers at the threshold, not necessarily the whole-population effect. If ΔD\Delta_D is small, the ratio and its normal approximation can be unstable. Covariance between outcome and treatment jumps matters for uncertainty. The lab computes a conventional joint delta standard error and notes it is not a bias-robust interval.

Is the cutoff credible?

Validity tests look for patterns incompatible with a plausible design; they do not prove continuity of potential outcomes:

  • Density: if units can precisely move their score across the cutoff, accumulation may appear on one side. A histogram depends on bins; test the density discontinuity using an appropriate method. Smooth density does not exclude all manipulation.
  • Prior covariates: examine jumps in characteristics measured before the decision, with intervals and power. Nonsignificant balance does not prove absence of confounding, and many tests increase the risk of chance findings.
  • Placebos and sensitivity: test cutoffs where the rule does not change and compare previously reasonable bandwidths and specifications. Strong variation may warn of curvature or poor support, but choosing the bandwidth most favorable to a conclusion invalidates a naive interval reading.
InteractiveManipulating the score

Treatment is received from score 0 onward. The sample is fixed; the control determines which candidates between −0.4 and 0 cross the threshold.

0.00.51.0−0.8 to −0.7: 82 units−0.7 to −0.6: 76 units−0.6 to −0.5: 84 units−0.5 to −0.4: 94 units−0.4 to −0.3: 59 units−0.3 to −0.2: 54 units−0.2 to −0.1: 47 units−0.1 to 0.0: 47 units0.0 to 0.1: 156 units0.1 to 0.2: 150 units0.2 to 0.3: 68 units0.3 to 0.4: 83 units0.4 to 0.5: 90 units0.5 to 0.6: 88 units0.6 to 0.7: 65 units0.7 to 0.8: 67 units−0.8−0.4−0.20.00.20.40.8Histogram densityObserved score
  • Untreated
  • Treated

Darker bars indicate the window [−0.2, 0.2): 94 scores on the left and 306 on the right. Across the sample, 125 of 1600 units crossed (7.8 %).

The two-sided binomial test compares equal masses in both halves of this fixed window. Under the no-manipulation model they are equal, so the test is exact conditional on the window total. A continuous but sloped density does not imply equal masses: this test does not replace the local density test of McCrary or rddensity. A nonsignificant result also does not establish absence of manipulation.

Model: initial score S uniform on [−1,1], binary ability B with probability 1/2, independent of S. Among those with B=1 and −0.4 ≤ S < 0, each crosses with the chosen probability and obtains X=−S/2; others retain X=S. Outcome is Y=2+0.7S+1.2B+ε+1.2·1(X≥0), with independent ε uniform on [−0.4,0.4]. The RD jump uses local lines with triangular kernel and bandwidth 0.2, without an interval. The population jump includes the composition change in B as well as the 1.2 effect.

70 %
Estimated local RD jump1.99
True causal effect1.20
Observed population jump1.77
Exact test: p-value< 0.001
Explore explicit manipulation of the running variable and its consequences.

A window as an experiment: an additional assumption

Local randomization proposes another design: within a window chosen without outcomes, specify an assignment mechanism and assume relevant potential outcomes are comparable under it. If the number treated is fixed and the null is sharp, enumerate compatible assignments and calculate an exact p-value. Continuity at the cutoff does not itself imply random assignment in a finite window. An exact sharp-null test is not automatically exact for the weak null of zero average effect.

With a discrete running variable and few values near cc, arbitrarily close observations are missing; without extra restrictions the same nonparametric limit cannot be recovered. In a regression kink, the rule’s slope changes and the estimand depends on a ratio of derivative changes and its own assumptions. Multiple cutoffs or geographic boundaries add threshold heterogeneity, spatial composition, and other choices that must be modeled, not merely relabeled.

Two different election studies

Lee (2008) studied US House elections. Margin separates narrow wins from narrow losses; comparison targets electoral advantage near the cutoff. The paper distinguishes the candidate’s later probability, the party’s seat-retention probability, and party vote share. Figure 4 reports a vote-share advantage on the order of 7–8 percentage points; these are not reelection probabilities.

The rdrobust Senate example comes from a different study and chamber. In it, margin is prior Democratic margin and vote the Democratic vote share for the same seat at the outcome the study calls t+2, in percent. Thus a jump of vote measures percentage points of vote share, not directly the probability of winning again. The Senate replication illustrates the same design but is not Lee’s original sample.

Lab: limits and diagnostics

Simulations specify data and seed. Intervals are interpreted under the model and assumptions in each cell; one run does not demonstrate coverage.

Download original Senate example data and prepare the local fit. The CSV contains observations without later outcome; these are excluded when estimating the jump.

[ ]Download Senate dataBrowser
from pyodide.http import pyfetch
url = ('https://raw.githubusercontent.com/rdpackages/rdrobust/'
       '7df239395c4afce2a58e22ef16a5817341683955/R/rdrobust_senate.csv')
respuesta = await pyfetch(url)
if not respuesta.ok:
    raise RuntimeError('No se pudo descargar la muestra de Senado')
raw = await respuesta.string()
print('Caracteres descargados:', len(raw), 'filas con cabecera:', len(raw.splitlines()))

The function calculates a local line and pilot quadratic separately on each side. The corrected interval uses variance of the full combination, not just the initial estimator.

[ ]rd linearBrowser
import numpy as np

def ajuste_local(x, y, h, grado):
    """Coeficientes, pesos de influencia y residuos de un lado del umbral."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    if h <= 0 or x.ndim != 1 or x.shape != y.shape:
        raise ValueError('Dimensiones o ancho no válidos')
    X = np.column_stack([x**j for j in range(grado + 1)])
    w = np.maximum(1 - np.abs(x) / h, 0)
    G = X.T @ (w[:, None] * X)
    if np.linalg.matrix_rank(G) < grado + 1:
        raise ValueError('No hay soporte suficiente para el ajuste local')
    A = np.linalg.solve(G, X.T * w)
    beta = A @ y
    return beta, A, y - X @ beta, X, w

def rd_lineal(x, y, h, b):
    """RD sharp sin covariables, kernel triangular, p=1, q=2, HC0."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    if x.ndim != 1 or x.shape != y.shape or not np.isfinite(x).all() or not np.isfinite(y).all():
        raise ValueError('x e y deben ser vectores finitos de igual longitud')
    if h <= 0 or b <= 0:
        raise ValueError('Los anchos deben ser positivos')
    filas = []
    for mask in (x < 0, x >= 0):
        xx, yy = x[mask], y[mask]
        bp, Ap, ep, Xp, wp = ajuste_local(xx, yy, h, 1)
        bq, Aq, eq, _, _ = ajuste_local(xx, yy, b, 2)
        # Proyección muestral de x² sobre la recta usada en el ajuste p.
        c = (Ap @ (xx**2))[0]
        infl_p = Ap[0]
        infl_bias = c * Aq[2]
        infl_bc = infl_p - infl_bias
        var_conv = np.sum((infl_p * ep)**2)
        var_rb = np.sum((infl_bc * eq)**2)
        filas.append((bp[0], c*bq[2], var_conv, var_rb,
                      np.sum(infl_p*infl_bias*eq**2), int(np.sum(wp > 0))))
    left, right = filas
    tau = right[0] - left[0]
    bias = right[1] - left[1]
    se = np.sqrt(left[2] + right[2])
    se_rb = np.sqrt(left[3] + right[3])
    return {'tau': tau, 'bias': bias, 'tau_bc': tau-bias,
            'se': se, 'se_rb': se_rb,
            'ic_conv': (tau-1.95996398454*se, tau+1.95996398454*se),
            'ic_robusto': (tau-bias-1.95996398454*se_rb,
                           tau-bias+1.95996398454*se_rb),
            'cov_p_sesgo': left[4]+right[4], 'n_h': (left[5],right[5])}

def ancho_mse_piloto(x, y, piloto=20, limites=(5, 30)):
    """Plug-in pedagógico para un ancho común; no es el selector de rdrobust.

    Estima curvaturas y varianzas con cuadráticas unilaterales de ancho piloto,
    y densidades con recuentos unilaterales dentro de ese ancho. Los límites
    estabilizan el resultado y se deben declarar; no son una garantía óptima.
    """
    x, y = np.asarray(x, float), np.asarray(y, float)
    n = len(x)
    if x.ndim != 1 or x.shape != y.shape or not np.isfinite(x).all() or not np.isfinite(y).all():
        raise ValueError('Datos no válidos')
    if piloto <= 0 or not 0 < limites[0] <= limites[1]:
        raise ValueError('Anchos no válidos')
    curvaturas, aporte_var = [], 0.0
    for mask in (x < 0, x >= 0):
        xx, yy = x[mask], y[mask]
        beta, _, residual, _, w = ajuste_local(xx, yy, piloto, 2)
        dentro = w > 0
        cuenta = int(dentro.sum())
        if cuenta <= 3:
            raise ValueError('Faltan observaciones en el piloto')
        densidad = cuenta / (n*piloto)
        # HC0 local simple; varianza condicional aproximada en el umbral.
        sigma2 = np.mean(residual[dentro]**2)
        curvaturas.append(2*beta[2])
        aporte_var += sigma2/densidad
    B = -(curvaturas[1]-curvaturas[0])/20
    V = (24/5)*aporte_var
    if abs(B) < 1e-12 or V <= 0:
        raise ValueError('El ancho plug-in degenera: revisar piloto o curvaturas')
    h_sin_limitar = (V/(4*B**2*n))**0.2
    return {'h': float(np.clip(h_sin_limitar,*limites)),
            'h_sin_limitar': float(h_sin_limitar), 'B': B, 'V': V,
            'curvaturas': tuple(curvaturas), 'piloto': piloto, 'limites': limites}

For the Senate, the selector is a pedagogical plug-in with pilot and explicit limits, not rdrobust’s formal selector. This demonstration’s HC0 errors assume independence; dependence within states may require different inference.

[ ]rd linear exampleBrowser
import csv, io

# raw contiene el CSV descargado en la primera celda.
filas = list(csv.DictReader(io.StringIO(raw)))
pares = [(float(f['margin']), float(f['vote'])) for f in filas
         if f['vote'] not in ('', 'NA', 'NaN')]
x, y = np.array(pares).T
seleccion = ancho_mse_piloto(x, y, piloto=20, limites=(5, 30))
h = seleccion['h']
resultado = rd_lineal(x, y, h=h, b=20)
print('n:', len(x), 'piloto:', seleccion['piloto'])
print('B:', round(seleccion['B'], 6), 'V:', round(seleccion['V'], 6))
print('h sin límite:', round(seleccion['h_sin_limitar'], 6), 'h:', round(h, 6))
for k in ('tau', 'bias', 'tau_bc', 'se', 'se_rb', 'ic_conv', 'ic_robusto', 'cov_p_sesgo', 'n_h'):
    print(k, resultado[k])

# Al cambiar b también cambian los pesos de corrección y su varianza.
otro = rd_lineal(x, y, h=10, b=15)
print('h=10 b=15:', otro)

# Verificación exacta: el modelo cuadrático se corrige sin error de truncamiento.
xx = np.linspace(-2, 2, 101)
yy = 2 + 3*xx + 4*xx**2 + (xx >= 0)*(5 + xx + 2*xx**2)
r = rd_lineal(xx, yy, h=1, b=1.5)
assert abs(r['tau_bc'] - 5) < 1e-10
assert abs(r['se_rb']) < 1e-10
print('salto corregido, cuadrática sin ruido:', round(r['tau_bc'], 8))

A simulation with fixed bandwidths and known effect compares conventional and corrected coverage. These are frequencies for this model, not a general guarantee.

[ ]rd linear coverageBrowser
# Simulación i.i.d. con verdad conocida: salto 2 en x=0.
# Se fijan los anchos para comparar cobertura, no se seleccionan con y.
rng = np.random.default_rng(20261102)
n, repeticiones = 1200, 150
anchos = (0.4, 0.6, 0.8)
cubiertos = np.zeros((len(anchos), 2), dtype=int)
for _ in range(repeticiones):
    xs = rng.uniform(-1, 1, n)
    ds = xs >= 0
    ys = 2 + 2*xs + 4*xs**2 + ds*(2 - 5*xs**2) + rng.normal(0, 1, n)
    for j, hs in enumerate(anchos):
        res = rd_lineal(xs, ys, h=hs, b=0.8)
        cubiertos[j, 0] += res['ic_conv'][0] <= 2 <= res['ic_conv'][1]
        cubiertos[j, 1] += res['ic_robusto'][0] <= 2 <= res['ic_robusto'][1]
for j, hs in enumerate(anchos):
    print('h:', hs, 'b: 0.8; cobertura convencional, robusta:',
          cubiertos[j, 0]/repeticiones, cubiertos[j, 1]/repeticiones,
          'de', repeticiones, 'réplicas')

Fuzzy RD generates monotone potential treatments using the same latent uniform variable. The ratio and delta standard error use covariance between jumps; the interval is conventional.

[ ]fuzzy rdBrowser
import numpy as np

# En cada observación, el mismo U define tratamientos potenciales monótonos.
# X es continuo y anterior a la asignación. Z indica lado del umbral.
rng = np.random.default_rng(272121)
n = 10_000
x = rng.uniform(-1, 1, n)
z = (x >= 0).astype(float)
u = rng.uniform(size=n)
d0 = (u < .15 + .10*x).astype(float)
d1 = (u < .55 + .10*x).astype(float)
d = np.where(z == 1, d1, d0)
eps = rng.normal(0, .8, n)
true_late = 3.0
y = 1 + .5*x + true_late*d + eps

def salto_e_influencia(x, target, h):
    """Salto de interceptos de rectas locales y sus aportaciones HC0."""
    estimates = []
    influence = np.zeros(len(x))
    counts = []
    for side in (-1, 1):
        select = ((x < 0) if side == -1 else (x >= 0)) & (np.abs(x) < h)
        v = x[select]/h
        design = np.column_stack((np.ones(len(v)), v))
        weight = 1 - np.abs(v)
        gram = design.T @ (weight[:, None]*design)
        if len(v) < 3 or np.linalg.matrix_rank(gram) != 2:
            raise ValueError('Faltan puntos o variación a un lado')
        inverse = np.linalg.inv(gram)
        beta = inverse @ (design.T @ (weight*target[select]))
        residual = target[select] - design @ beta
        influence[select] = side * (design @ inverse[0]) * weight * residual
        estimates.append(beta[0])
        counts.append(len(v))
    return estimates[1]-estimates[0], influence, counts

h = .4
jump_y, iy, counts = salto_e_influencia(x, y, h)
jump_d, id_, _ = salto_e_influencia(x, d, h)
if abs(jump_d) < 1e-8:
    raise ValueError('El salto estimado de tratamiento es demasiado pequeño')
ratio = jump_y / jump_d
# La misma unidad contribuye a ambos saltos: conserva su covarianza.
if_ratio = (iy - ratio*id_) / jump_d
se = np.sqrt(np.sum(if_ratio**2))
print('Muestra por lado:', counts, '| h:', h)
print('Salto del resultado:', round(jump_y, 5), '| salto tratamiento:', round(jump_d, 5))
print('Cociente fuzzy:', round(ratio, 5), '| EE delta HC0:', round(se, 5))
print('IC normal convencional:', np.round([ratio-1.96*se, ratio+1.96*se], 5))
print('LATE verdadero en el diseño:', true_late)
print('IC convencional sin corrección de sesgo; primer salto débil invalida la aproximación normal.')
assert np.all(d1 >= d0)

To study density, fit local lines to the histogram with multinomial covariance. This pedagogical test is calibrated here for densities constant on each side: it is not the general rddensity implementation and can be biased with curved densities.

[ ]local densityBrowser
"""Discontinuidad de densidad: simulación reproducible y ajuste lineal local.

Estimador pedagógico con histograma, no implementación de rddensity ni de
la prueba completa de McCrary. Sus condiciones se describen abajo.
"""
import math
import numpy as np

def contraste_densidad(x, c=0., h=.5, bins_por_lado=8):
    """Densidades, diferencia, EE multinomial y p-valor normal bilateral.

    Las unidades deben ser independientes; la aproximación centrada en cero
    es apropiada aquí para densidades constantes a cada lado en la ventana.
    Para densidades curvadas puede haber sesgo y p-valores mal calibrados.
    """
    x = np.asarray(x, dtype=float)
    if x.ndim != 1 or len(x) < 2 or not np.isfinite(x).all():
        raise ValueError('x debe ser un vector finito con al menos dos datos')
    if not np.isfinite(c) or not np.isfinite(h) or h <= 0:
        raise ValueError('El umbral debe ser finito y el ancho positivo')
    if not isinstance(bins_por_lado, int) or bins_por_lado < 2:
        raise ValueError('Se necesitan al menos dos intervalos por lado')
    n = len(x)
    m = bins_por_lado
    edges = np.linspace(-h, h, 2*m+1)
    count, _ = np.histogram(x-c, bins=edges)
    bw = h/m
    u = (edges[:-1] + edges[1:])/(2*h)
    w = 1 - np.abs(u)
    coefficients = np.zeros(2*m)
    estimates = []
    for side in (slice(0, m), slice(m, 2*m)):
        uu, ww = u[side], w[side]
        s0, s1, s2 = ww.sum(), (ww*uu).sum(), (ww*uu*uu).sum()
        a = ww*(s2-s1*uu)/(s0*s2-s1*s1)
        estimates.append(float(a @ count[side] / (n*bw)))
        coefficients[side] = a
    coefficients[:m] *= -1
    p = count/n
    var = (coefficients**2 @ p - (coefficients @ p)**2)/(n*bw*bw)
    if var <= 0:
        raise ValueError('Sin varianza estimable: revisa los datos y la ventana')
    se = math.sqrt(var)
    jump = estimates[1] - estimates[0]
    z = jump/se
    return {'izquierda': estimates[0], 'derecha': estimates[1],
            'salto': jump, 'se': se, 'z': z,
            'p': math.erfc(abs(z)/math.sqrt(2)),
            'n_izquierda': int(count[:m].sum()),
            'n_derecha': int(count[m:].sum())}

# Base uniforme y manipulación conocida: el 45 % de los valores negativos
# pasa al reflejo positivo. Las observaciones permanecen independientes.
rng = np.random.default_rng(20261102)
base = rng.uniform(-1, 1, 10000)
manipulado = base.copy()
cruzan = (base < 0) & (rng.random(len(base)) < .45)
manipulado[cruzan] *= -1
print('Saltos verdaderos: uniforme 0; manipulado 0,45.')
print('La densidad verdadera pasa de 0,275 a 0,725 con manipulación.')
for nombre, x in [('sin manipulación', base), ('con manipulación', manipulado)]:
    r = contraste_densidad(x)
    print(nombre, 'n ventana', (r['n_izquierda'], r['n_derecha']),
          'densidades', round(r['izquierda'], 4), round(r['derecha'], 4),
          'salto', round(r['salto'], 4), 'EE', round(r['se'], 4),
          'z', round(r['z'], 3), 'p', f"{r['p']:.6g}")

# Validación de álgebra, no una garantía general sobre tasas de error.
assert contraste_densidad(base)['p'] > .05
assert contraste_densidad(manipulado)['p'] < .05

The following simulation examines one prior covariate and two placebo cutoffs without crossing the real threshold. Results do not prove identification, and multiple tests require caution.

[ ]simulated validityBrowser
import math
import numpy as np

# Diagnósticos de un diseño simulado, no pruebas de identificación causal.
# Requiere rd_lineal de la celda anterior.
rg_val = np.random.default_rng(272122)
nv = 12_000
xv = rg_val.uniform(-1, 1, nv)
av = .3*xv + rg_val.normal(0, 1, nv)  # covariable anterior, CEF continua
yv = 2 + .5*xv + 1.5*(xv >= 0) + rg_val.normal(0, 1, nv)

def diagnostico(variable, corte, h=.2):
    result = rd_lineal(xv-corte, variable, h=h, b=h)
    p = math.erfc(abs(result['tau']/result['se'])/math.sqrt(2))
    return result['tau'], result['se'], p, result['n_h']

print('Balance pretratamiento en c=0:', diagnostico(av, 0))
for corte in (-.55, .55):
    print('Resultado en umbral placebo', corte, ':', diagnostico(yv, corte))
print('Las ventanas placebo de radio 0,2 no incluyen el umbral real.')
print('EE HC0 convencionales y p-valores aproximados; no hay corrección de multiplicidad.')
print('Un diagnóstico no significativo no demuestra continuidad de resultados potenciales.')

Finally, enumerate every possible assignment under an assumed completely randomized mechanism and a sharp null.

[ ]exact randomizationBrowser
from itertools import combinations
import numpy as np

# Hipótesis adicional: en la ventana se asignan 4 de 8 unidades al azar,
# todas las 70 asignaciones tienen igual probabilidad y la nula es aguda.
y = np.array([1., 2., 3., 4., 5., 6., 7., 8.])
tratados_observados = (0, 2, 4, 6)
def diferencia(indices):
    mask = np.zeros(len(y), dtype=bool)
    mask[list(indices)] = True
    return y[mask].mean() - y[~mask].mean()
obs = diferencia(tratados_observados)
valores = np.array([diferencia(c) for c in combinations(range(8), 4)])
p_exacto = np.mean(np.abs(valores) >= abs(obs)-1e-12)
print('Asignaciones equiprobables:', len(valores))
print('Diferencia observada:', obs, '| p bilateral exacto:', p_exacto)
assert len(valores) == 70
print('Exactitud bajo nula aguda y mecanismo supuesto, no por continuidad solamente.')

In a local Python environment with packages numpy, pandas, rdrobust, rddensity and matplotlib, compare original House data with Senate data. The code estimates future party victory and balance in the House, future vote share in the Senate, and compares custom lines with rdrobust. It also plots observations and runs a density diagnostic on Senate margins. HC0 errors assume independence; Lee’s original code clusters. No isolated test validates the design.

[ ]House and Senate: replication and diagnosticsLocal GPU
"""Lee (2008): Cámara de Representantes, victoria partidaria y balance previo.

Requiere numpy, pandas y rdrobust. Descarga el ZIP primario de MIT en memoria.
Este cálculo ilustra h fijos y no reproduce la especificación completa del paper.
"""
from io import BytesIO
from urllib.request import urlopen
from zipfile import ZipFile
import numpy as np
import pandas as pd
from rdrobust import rdrobust

URL = 'https://economics.mit.edu/sites/default/files/inline-files/Lee2008%20%281%29.zip'
with urlopen(URL, timeout=30) as response:
    source = response.read()
with ZipFile(BytesIO(source)) as archive:
    group = pd.read_stata(BytesIO(archive.read('Lee2008/group_final.dta')),
                          convert_categoricals=False)
    table = pd.read_stata(BytesIO(archive.read('Lee2008/table_two_final.dta')),
                          convert_categoricals=False)

# El código 100 se interpreta como demócrata con apoyo externo Voteview y
# concordancia empírica de signo; los códigos del archivo carecen de etiquetas.
used = group.loc[group['use'].eq(1)].copy()
sign = used.dropna(subset=['partywin', 'difdemshare'])
assert ((sign.partywin == 100) == (sign.difdemshare >= 0)).all()
future = used.dropna(subset=['partywin', 'partywinnext', 'difdemshare']).copy()
future['demwinnext'] = (future.partywinnext == 100).astype(float)

# El original deja right ausente en el empate exacto; filtrar esa fila reproduce
# la selección por disponibilidad de la variable right, no toda la tabla 2.
balance = table.loc[table['use'].eq(1)].dropna(
    subset=['difdemshare', 'demshareprev', 'right']).copy()
assert (balance.right == (balance.difdemshare >= 0).astype(float)).all()
print('ZIP bytes:', len(source), 'filas use:', len(used),
      'ganador actual y margen observados:', len(sign),
      'muestra victoria futura:', len(future), 'balance:', len(balance))

def propio(x, y, h):
    intercepts, variances, counts = [], [], []
    for side in (x < 0, x >= 0):
        mask = side & (np.abs(x) < h)
        u, yy = x[mask] / h, y[mask]
        w = 1 - np.abs(u)
        X = np.column_stack([np.ones(len(u)), u])
        A = X.T @ (w[:, None] * X)
        beta = np.linalg.solve(A, X.T @ (w * yy))
        e = yy - X @ beta
        B = X.T @ (((w * e)**2)[:, None] * X)
        Ainv = np.linalg.inv(A)
        intercepts.append(beta[0])
        variances.append((Ainv @ B @ Ainv)[0, 0])
        counts.append(len(u))
    return intercepts[1] - intercepts[0], np.sqrt(sum(variances)), counts

for label, df, outcome in [('victoria futura del partido demócrata', future, 'demwinnext'),
                           ('cuota demócrata previa', balance, 'demshareprev')]:
    x = df['difdemshare'].to_numpy(dtype=float)
    y = df[outcome].to_numpy(dtype=float)
    print('\nResultado:', label)
    for h in (.05, .10, .20):
        tau, se, counts = propio(x, y, h)
        r = rdrobust(y=y, x=x, c=0, p=1, q=2, h=[h, h], b=[h, h],
                     kernel='triangular', vce='hc0')
        conventional = float(r.coef.loc['Conventional'].iloc[0])
        robust = float(r.coef.loc['Robust'].iloc[0])
        se_conv = float(r.se.loc['Conventional'].iloc[0])
        np.testing.assert_allclose([tau, se], [conventional, se_conv],
                                   rtol=0, atol=1e-9)
        print('h', h, 'n', counts, 'propio tau/se', tau, se,
              'rdrobust convencional tau/se', conventional, se_conv,
              'rdrobust corregido', robust,
              'IC robusto', r.ci.loc['Robust'].to_numpy(),
              'diferencias tau/se', conventional-tau, se_conv-se)

print('La victoria futura es partidaria, no necesariamente del mismo candidato.')
print('La inferencia HC0 supone independencia; Tabla 2 original usa cluster(statedisdec).')

# Material independiente: Senado de Cattaneo, Frandsen y Titiunik (2015).
# No atribuir estos datos ni este resultado al estudio de Lee sobre la Cámara.
senate_url = ('https://raw.githubusercontent.com/rdpackages/rdrobust/'
              '7df239395c4afce2a58e22ef16a5817341683955/R/rdrobust_senate.csv')
senate = pd.read_csv(senate_url).dropna(subset=['margin', 'vote'])
x = senate['margin'].to_numpy(dtype=float)
y = senate['vote'].to_numpy(dtype=float)
print('\nSenado: cuota de voto demócrata en t+2; pares completos:', len(senate))
for h in (5., 10., 20.):
    tau, se, counts = propio(x, y, h)
    r = rdrobust(y=y, x=x, c=0, p=1, q=2, h=[h, h], b=[h, h],
                 kernel='triangular', vce='hc0')
    conventional = float(r.coef.loc['Conventional'].iloc[0])
    se_conv = float(r.se.loc['Conventional'].iloc[0])
    np.testing.assert_allclose([tau, se], [conventional, se_conv],
                               rtol=0, atol=1e-9)
    print('h', h, 'n', counts, 'propio tau/se', tau, se,
          'rdrobust convencional tau/se', conventional, se_conv,
          'corregido', float(r.coef.loc['Robust'].iloc[0]),
          'IC robusto', r.ci.loc['Robust'].to_numpy())

# Gráfico de la Cámara y pruebas de densidad del Senado.
import matplotlib.pyplot as plt
from rddensity import rddensity

xf = future['difdemshare'].to_numpy(dtype=float)
yf = future['demwinnext'].to_numpy(dtype=float)
h_grafico = .10
fig, axes = plt.subplots(1, 2, figsize=(13, 4.7))
ax = axes[0]
for lado, color, limites in [(-1, 'tab:blue', (-.20, 0)), (1, 'tab:orange', (0, .20))]:
    edges = np.linspace(limites[0], limites[1], 11)
    centros, medias = [], []
    for a, b in zip(edges[:-1], edges[1:]):
        en_bin = (xf >= a) & (xf < b)
        if np.any(en_bin):
            centros.append((a+b)/2)
            medias.append(yf[en_bin].mean())
    ax.scatter(centros, medias, color=color, s=22,
               label='Media de bin, izquierda' if lado == -1 else 'Media de bin, derecha')
    mask = ((xf < 0) if lado == -1 else (xf >= 0)) & (np.abs(xf) < h_grafico)
    u = xf[mask]/h_grafico
    X = np.column_stack((np.ones(len(u)), u))
    w = 1 - np.abs(u)
    beta = np.linalg.solve(X.T @ (w[:, None]*X), X.T @ (w*yf[mask]))
    grid = np.linspace(-h_grafico, 0, 100) if lado == -1 else np.linspace(0, h_grafico, 100)
    ax.plot(grid, beta[0]+beta[1]*grid/h_grafico, color=color,
            label='Recta local, izquierda' if lado == -1 else 'Recta local, derecha')
ax.axvline(0, color='black', linestyle=':', linewidth=1)
ax.set(xlabel='Margen demócrata actual', ylabel='Proporción de victorias futuras',
       title='Cámara: medias por bin y rectas locales')
ax.legend(fontsize=8)

# El test de densidad usa también observaciones con voto futuro ausente.
senate_full = pd.read_csv(senate_url)
score = senate_full['margin'].dropna().to_numpy(dtype=float)
score_pares = senate_full.dropna(subset=['margin', 'vote'])['margin'].to_numpy(dtype=float)
axes[1].hist(score, bins=np.arange(-40, 42, 2),
             weights=np.ones(len(score))/(2*len(score)),
             color='tab:blue', alpha=.6, edgecolor='white')
axes[1].axvline(0, color='black', linestyle=':', linewidth=1)
axes[1].set(xlabel='Margen demócrata actual (puntos porcentuales)',
            ylabel='Densidad del histograma', title='Senado: distribución del margen')
fig.tight_layout()
plt.show()

print('Senado, márgenes observados:', len(score), 'pares completos:', len(score_pares))
for nombre, s, ancho in [('todos, ancho automático', score, None),
                         ('todos, h=10', score, 10),
                         ('todos, h=20', score, 20),
                         ('pares completos, ancho automático', score_pares, None)]:
    opciones = {} if ancho is None else {'h': [ancho, ancho]}
    prueba = rddensity(s, c=0, **opciones)
    print(nombre, 'anchos:', prueba.h, 'n:', prueba.n,
          'z robusto jackknife:', float(prueba.test['t_jk']),
          'p robusto jackknife:', float(prueba.test['p_jk']))
print('La falta de rechazo no demuestra ausencia de manipulación ni continuidad causal.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe causal jump
Prove: In sharp RD with D=1{X≥c}D=1\{X\ge c\}, consistency, support on both sides, and continuous versions of E[Y(0)∣X=x]E[Y(0)\mid X=x] and E[Y(1)∣X=x]E[Y(1)\mid X=x] at cc, prove the observed mean jump identifies the average effect at the cutoff.
The proof will appear here as you work.

Step 1 of 3. Which potential outcome is observed on each side?

ProofCurvature at the boundary
Prove: For a one-sided local linear fit with triangular kernel, assume a twice-differentiable mean, positive regular density, bandwidth hh and a valid Taylor expansion. The equivalent intercept kernel is L(u)=(1−u)(6−12u)L(u)=(1-u)(6-12u), 0≤u≤10\le u\le1. Derive the leading intercept-bias term.
The proof will appear here as you work.

Step 1 of 3. Which expansion terms are fitted without leading bias?

NumericA partial first stage
The outcome mean jumps by 3.2 units and treatment probability increases by 0.4 when crossing the threshold. Under fuzzy RD assumptions, calculate the local Wald ratio.
CodeTriangular local lines from scratch
Implement rd_local_linear(x, y, c, h) for finite numeric vectors of equal length, finite threshold, and positive bandwidth. Fit weighted lines separately with triangular kernel: left c-h < x < c and right c <= x < c+h. Zero-weight endpoints do not count. Each side needs at least two distinct values and a full-rank design matrix; reject invalid inputs or singular fits with ValueError. Return a dictionary with tau, se, left, right, n_left, and n_right: intercept difference, standard error, and each intercept and size. For each side calculate A=X.T@W@X, B=X.T@diag((wresidual)*2)@X, and V=inv(A)@B@inv(A); se is the square root of the sum of both intercepts’ HC0 variances. Do not modify inputs. This conventional uncertainty assumes independent observations and neither corrects bias nor represents clustered inference.
import numpy as np

def rd_local_linear(x, y, c, h):
  """Devuelve tau, se, interceptos y tamaños laterales con núcleo triangular."""
  raise NotImplementedError('Implementa los ajustes y la varianza HC0')
Shift+Enter to run
QuizScores around the cutoff
A scholarship depends on an exam graded before candidates are known, but scores are rounded and few values lie near the cutoff. What difficulty deserves attention?
QuizA known tax threshold
Firms know a tax threshold and can precisely alter reported income. What threat should be examined?
QuizA birth date
A policy changes by date of birth. Which institutional feature might threaten comparison of nearby cohorts?
QuizA close election
Victory margin is near zero. What is the more careful interpretation?

After solving the fuzzy exercise, check the calculation:

[ ]Check the local ratioBrowser
salto_resultado, salto_tratamiento = 3.2, 0.4
assert salto_tratamiento != 0
late_ejercicio = salto_resultado / salto_tratamiento
assert abs(late_ejercicio - 8) < 1e-12
print('Cociente local del ejercicio:', late_ejercicio)