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.
Sharp RD: an effect at the cutoff
In sharp regression discontinuity, assignment variable and threshold determine . Let be potential outcomes. Assume consistency, support for on both sides of the cutoff, and versions continuous at for . Then
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 , triangular kernel , and bandwidth , estimate coefficients of on 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 . The first four are . With two one-sided derivatives, positive regular density at the cutoff, and a common bandwidth, the leading jump-bias expansion is
Here and are the relevant potential means on observed sides. The sign comes from the one-sided equivalent kernel : its second moment is , multiplied by . With different bandwidths retain each side’s term separately.
Leading variance decreases as , while squared bias grows as . The bandwidth minimizing mean squared error balances both terms. In the explicit lab example, is uniform on , noise variance is one, and the mean is . For the expansion gives
This is an oracle selector for that known model and an asymptotic approximation, not a universal selector knowing real-data curvature. If , this bias term vanishes and the bandwidth formula no longer applies.
With of order , 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 be the outcome-mean jump and the treatment-probability jump. With appropriate continuity of potential outcomes and treatments, cutoff-side exclusion except through treatment, monotonicity, and a nonzero first stage,
identifies a LATE for compliers at the threshold, not necessarily the whole-population effect. If 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.
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 , 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.
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.
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.
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.
# 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.
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.
"""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'] < .05The 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.
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.
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.
"""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.')npm run lab and open the connection link.Exercises
Step 1 of 3. Which potential outcome is observed on each side?
Step 1 of 3. Which expansion terms are fitted without leading bias?
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')After solving the fuzzy exercise, check the calculation:
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)