Module contents
Lesson 18 of 28Core 100 min

Instrumental variables with heterogeneous effects: LATE and compliers

With heterogeneous effects, instrumental variables may identify a local average treatment effect for compliers. Study ITT, compliance types, complier characteristics, marginal treatment effects, and judge designs.

After this lesson you can

  • Formulate IV with potential outcomes and prove the LATE theorem.
  • Distinguish ITT, treatment effect on treated units, and LATE under noncompliance.
  • Estimate complier proportions and characteristics using κ weights.
  • Explain why different valid instruments can yield different IV estimates.
  • Interpret judge designs and marginal treatment effects as LATE extensions.

Before you start

Offering is not attending

A lottery offers training to a group of developers. Some invitees do not attend and some uninvited people find another way to attend. The difference between arms preserves the benefit of random assignment and answers the effect of offering the program. Directly comparing attendees with nonattendees can mix the effect of attending with motivation, availability, or experience.

The intention-to-treat effect, or ITT, is the average outcome difference between assigned groups. It does not require universal compliance to describe the causal offer effect in a well-randomized trial, with consistency and no interference. If the offer also changes the outcome through another path, ITT still includes it; dividing by attendance does not attribute everything to attending.

The four potential types

Let Z∈{0,1}Z\in\{0,1\} be the offer and D(z)D(z) the treatment each person would receive under assignment zz. Compliance types are joint properties of two potential decisions:

TypeD(0)D(0)D(1)D(1)Response to offer
Never-taker00Never attends
Complier01Attends only if offered
Always-taker11Attends in both arms
Defier10Attends only if not offered

Each person reveals only D(Z)D(Z). Without further assumptions, seeing an invitee attend does not by itself distinguish a complier from an always-taker. The proportions and effects of all types cannot be read directly from the four observed cells.

InteractiveFour types and two arms

Each card shows the composition of a cell of assignment Z and received treatment T. Percentages refer to each whole arm, not the cell. We know types here because we define the model; in a trial only one assignment and one treatment per person are observed.

Z = 0, T = 0
80 % of the arm
Compliers: 40 %
Never treated: 40 %
Z = 0, T = 1
20 % of the arm
Always treated: 20 %
Z = 1, T = 0
40 % of the arm
Never treated: 40 %
Z = 1, T = 1
60 % of the arm
Compliers: 40 %
Always treated: 20 %
  • Compliers
  • Always treated
  • Never treated
  • Defiers

Without an offer, the treatment rate is 20 % and mean outcome 2.00; with an offer they are 60 % and 3.20. The never-treated share is the remainder to 100%. Each colored bar occupies its proportion of the whole arm.

Exact model: assignment is independent of type, and Z affects outcome only through T. For compliers, always treated, never treated and defiers, the pairs T(0), T(1) are respectively (0,1), (1,1), (0,0) and (1,0). Their Y(0) outcomes are 2, 3, 1 and 4; in each group Y(1) = Y(0) + group effect. These are model population means without sampling error.

The first stage is the proportion of compliers minus the proportion of defiers. Outcome ITT is the complier share × its effect minus the defier share × its effect. Without defiers and with a positive first stage, the ratio equals the average complier effect. A small first stage can make estimation unstable in finite samples; diagnosing weakness also requires sample size and precision.

ATE averages effects over all groups and can differ from the local effect. Identification requires independence, exclusion, consistency, a nonzero first stage and monotonicity; neither knowing this simulation result nor observing a positive first stage establishes those assumptions in real data. See Angrist, Imbens and Rubin.

40 %
20 %
0 %
3.0
1.0
-1.0
4.0
Never treated: remainder40 %
ITT on treatment0.40
ITT on outcome1.20
Population Wald ratio3.00
Model complier effect3.00
Model ATE1.00
Change each type’s proportions and effects and compare ITT, Wald, and LATE.

The Wald ratio and LATE theorem

Let Y(d)Y(d) be potential outcomes under treatment dd. To interpret ZZ as an instrument, we need:

  1. Independence and support: ZZ is independent of (Y(0),Y(1),D(0),D(1))(Y(0),Y(1),D(0),D(1)) in the analyzed population and 0<P(Z=1)<10<P(Z=1)<1. With covariates, conditional independence can be assumed together with support for both ZZ values in relevant strata. Potential outcomes are assumed integrable.
  2. Exclusion and consistency: the offer affects YY only through DD, so Y=Y(D(Z))Y=Y(D(Z)), and D=D(Z)D=D(Z). Absence of interference between units must also be justified.
  3. Relevance: E[D∣Z=1]−E[D∣Z=0]≠0E[D\mid Z=1]-E[D\mid Z=0]\ne0.
  4. Monotonicity: D(1)≥D(0)D(1)\ge D(0) almost surely. No person is a defier for this particular instrument change.

Assignment independence may come from the lottery; exclusion and monotonicity need additional arguments. For example, an invitation can inform or motivate even someone who does not attend. Randomization does not remove that possible direct effect.

The following derivation uses unconditional independence. If plausible only conditional on XX, the raw ratio may compare arms with different covariate distributions. Under conditional assumptions and support, first standardize both differences over the same distribution of XX:

LATE=EX{E[Y∣Z=1,X]−E[Y∣Z=0,X]}EX{E[D∣Z=1,X]−E[D∣Z=0,X]}.LATE=\frac{E_X\{E[Y\mid Z=1,X]-E[Y\mid Z=0,X]\}} {E_X\{E[D\mid Z=1,X]-E[D\mid Z=0,X]\}}.

The denominator remains the population proportion of compliers, provided it is positive; standardized differences appropriately weight strata.

Under those assumptions, with τ=Y(1)−Y(0)\tau=Y(1)-Y(0) and C={D(1)>D(0)}C=\{D(1)>D(0)\},

E[Y∣Z=1]−E[Y∣Z=0]=E[Y(D(1))−Y(D(0))]=E[{D(1)−D(0)}τ]=P(C)E[τ∣C],E[D∣Z=1]−E[D∣Z=0]=E[D(1)−D(0)]=P(C).\begin{aligned} E[Y\mid Z=1]-E[Y\mid Z=0] &=E[Y(D(1))-Y(D(0))]\\ &=E[\{D(1)-D(0)\}\tau]\\ &=P(C)E[\tau\mid C],\\ E[D\mid Z=1]-E[D\mid Z=0]&=E[D(1)-D(0)]=P(C). \end{aligned}

The first equality uses independence and consistency; the second uses exclusion and binary treatment; the third uses monotonicity. If P(C)>0P(C)>0, the local average treatment effect is

LATE=E[Y(1)−Y(0)∣C]=E[Y∣Z=1]−E[Y∣Z=0]E[D∣Z=1]−E[D∣Z=0].LATE=E[Y(1)-Y(0)\mid C] =\frac{E[Y\mid Z=1]-E[Y\mid Z=0]} {E[D\mid Z=1]-E[D\mid Z=0]}.

The Wald estimator replaces expectations with sample means and converges to LATE under suitable sampling and moments. A first stage near zero destabilizes the ratio and usual delta approximation; do not confuse a mathematically positive relationship with precise information.

LATE is generally neither ATE nor the average effect among all treated. The latter can include always-takers whose untreated outcomes are not identified by this instrument. With a program that truly bars uninvited access, D(0)=0D(0)=0, there are no always-takers or defiers; even then LATE describes those who would attend if offered, not necessarily those who would never attend.

Defiers and changing the instrument

Without monotonicity, let pc,pfp_c,p_f be complier and defier proportions and τc,τf\tau_c,\tau_f their average effects. Reduced form and first stage are pcτc−pfτfp_c\tau_c-p_f\tau_f and pc−pfp_c-p_f. When the denominator is nonzero, Wald is

pcτc−pfτfpc−pf.\frac{p_c\tau_c-p_f\tau_f}{p_c-p_f}.

The negative weight for defiers can produce a value outside the range of group effects. It can accidentally coincide with a particular effect, but generally is not interpreted as a subpopulation average. If pc=pfp_c=p_f, the first stage vanishes even though people change treatment.

Two valid offers may induce different people to change their decision. With heterogeneous effects, their LATEs may differ without that difference alone proving either instrument invalid.

InteractiveDifferent instruments, different effects

The band shows which people change treatment when the selected instrument moves from 0 to 1. The curve is their individual effect in the model; its average over the band is LATE.

0.000.250.500.751.002.0−0.1Resistance U
  • Effect Y(1)−Y(0)
  • Compliers

With this instrument, P(D=1|Z=0)=0.15 and P(D=1|Z=1)=0.45. Wald divides the outcome difference 0.207 by the treatment difference 0.30. These are exact model values, not sample estimates.

Shared model: U∼Uniform(0,1), Z is randomized binary and independent of U, D=1{U≤P(Z)} and Y=Y(0)+D·τ(U), with Y(0)=0.5+0.4U. The curve is τ(u)=1+s(u−0.5)+c((u−0.5)²−1/12); s and c are the controls. A uses P(0)=0.15 and P(1)=0.45; B uses 0.55 and 0.85.

Both designs satisfy independence, exclusion and monotonicity in this model, with a positive first stage. They move different U intervals, so LATE may differ even when both are valid. Agreement with ATE follows here from effect shape, not instrument validity. See Imbens and Angrist, LATE identification.

Binary instrument
1.4
0.8
Complier proportion30 %
ITT on Y0.207
Wald = LATE0.691
Population ATE1.000
Two incentive thresholds move different groups in the same population.

Who are the compliers?

Under the theorem’s assumptions the complier proportion is the first stage. To study complier characteristics, if the instrument is random only conditional on pretreatment covariates XX, write π(X)=P(Z=1∣X)\pi(X)=P(Z=1\mid X) and require 0<π(X)<10<\pi(X)<1 in relevant strata. Abadie’s weights recover complier moments. Define

κ=1−D(1−Z)1−π(X)−(1−D)Zπ(X).\kappa=1-\frac{D(1-Z)}{1-\pi(X)} -\frac{(1-D)Z}{\pi(X)}.

For an integrable function h(X)h(X),

E[κh(X)]=P(C)E[h(X)∣C],E[κ]=P(C).E[\kappa h(X)]=P(C)E[h(X)\mid C], \qquad E[\kappa]=P(C).

To see this, average κ\kappa over ZZ within each type and XX: its expectation is one for compliers and zero for other types, thanks to conditional independence and monotonicity. Therefore E[κh]/E[κ]E[\kappa h]/E[\kappa] identifies the mean of a pretreatment characteristic among compliers. Some individual weights are negative; they are not observed labels or individual compliance probabilities. A near-zero empirical denominator signals weakness and instability.

For complier potential-outcome means, also use

κ1=DZ−π(X)π(X)(1−π(X)),κ0=(1−D)π(X)−Zπ(X)(1−π(X)).\kappa_1=D\frac{Z-\pi(X)}{\pi(X)(1-\pi(X))},\qquad \kappa_0=(1-D)\frac{\pi(X)-Z}{\pi(X)(1-\pi(X))}.

Under the same assumptions, E[κdY]=P(C)E[Y(d)∣C]E[\kappa_dY]=P(C)E[Y(d)\mid C] and E[κd]=P(C)E[\kappa_d]=P(C) for d=0,1d=0,1. They may be normalized separately in the sample, but normalization does not remove negative weights or a weak first stage. If π\pi is estimated, inference must incorporate that fit and assignment design.

Multiple instruments and controls

In the exactly identified case, 2SLS with one binary instrument and only an intercept equals Wald. Adding controls residualizes treatment, outcome, and instrument; interpretation depends on how effects are adjusted and conditional independence assumptions. With multivalued instruments, ordered monotonicity, and suitable weights, a weighted average of local effects from different incentive changes may arise.

Do not turn that observation into a positive-weight rule for any 2SLS with multiple instruments and linear controls: weights can depend on specification and have problematic signs. An overidentification test detects incompatibility with joint restrictions but does not certify validity when it fails to reject. If valid instruments identify different local effects, imposing one homogeneous coefficient may cause rejection without proving which instrument violates exclusion.

From LATE to marginal effects

In a latent selection model, let U∼Uniforme(0,1)U\sim Uniforme(0,1) be unobserved resistance and D=1{U≤p(Z)}D=1\{U\le p(Z)\}, where p(Z)p(Z) is treatment propensity. For this derivation assume ZZ is independent of (Y(0),Y(1),U)(Y(0),Y(1),U) and required exclusion and regularity hold. The marginal treatment effect is

MTE(u)=E[Y(1)−Y(0)∣U=u].MTE(u)=E[Y(1)-Y(0)\mid U=u].

By independence,

E[Y∣p(Z)=p]=E[Y(0)]+∫0pMTE(u) du.E[Y\mid p(Z)=p]=E[Y(0)]+\int_0^p MTE(u)\,du.

Where pp varies continuously and the derivative exists, the local instrumental ratio is the derivative of that mean with respect to pp. Between two values p0<p1p_0<p_1, LATE is the average of MTE(u)MTE(u) over [p0,p1][p_0,p_1]. If propensity has support only over part of [0,1][0,1], the curve outside that portion and its full integral require extrapolation or extra assumptions.

In this model without covariates, if P=p(Z)P=p(Z) has the distribution induced by the instrument, normalized weights for ATE, ATT, and ATU respectively are

wATE(u)=1,wATT(u)=P(P≥u)E[P],wATU(u)=P(P<u)1−E[P].w_{\rm ATE}(u)=1,\quad w_{\rm ATT}(u)=\frac{P(P\ge u)}{E[P]},\quad w_{\rm ATU}(u)=\frac{P(P<u)}{1-E[P]}.

Integrating each weight against MTE(u)MTE(u) gives its population effect, provided quantities are identified and denominators positive. The mean between p0p_0 and p1p_1 uses uniform weight over that interval. Selection is a substantive model, not an automatic property of every valid IV.

InteractiveThe marginal-effect curve

Top: marginal effect by resistance U. The band marks propensity support; outside it, the dashed curve comes from the model. Bottom: each curve is a weight density integrating to one.

2.0−0.1Weights on U2.200.000.250.500.751.00Resistance U
  • ATE
  • ATT
  • ATU
  • Interval LATE

With this support, ATE, ATT, ATU generally depend on MTE values outside it; displayed figures use the assumed full shape and are not identified without extrapolation. Interval LATE uses the portion between its endpoints.

Model: U∼Uniform(0,1), P∼Uniform(a,b) independent of U, D=1{U≤P}, Y(0)=0.5+0.4U and Y(1)=Y(0)+τ(U), with τ(u)=1+s(u−0.5)+c((u−0.5)²−1/12). Endpoints a and b are the selected support; s and c control the curve. The treated proportion is E[P]=(a+b)/2.

Weights are 1 for ATE, P(P≥u)/E[P] for ATT, P(P<u)/(1−E[P]) for ATU and 1{a≤u≤b}/(b−a) for LATE. Integrating τ(u) with each weight gives exact model values, not sample estimates. Independence of P and U and exclusion are assumptions; a zero first stage does not identify a LATE. See Heckman and Vytlacil (2005).

0.20
0.80
1.4
0.8
Model ATE1.000
Model ATT0.692
Model ATU1.308
Interval LATE0.957
Change heterogeneity and support; weights show which population each estimand addresses.

A judge design compares assignments of cases to judges differing in severity. It can approach an experiment if cases are effectively randomized within the relevant unit. Exclusion is questionable if judges affect outcomes through other decisions, and ranking judges by average severity does not ensure all individuals respond in the same direction. With multiple decisions and treatments, local interpretation must be justified for the particular design.

Two historical instruments

In the Vietnam draft lottery, eligibility cutoffs were 195, 125, and 95 for the 1970, 1971, and 1972 lotteries. Eligibility changed service probability but did not determine it: there were volunteers and exemptions. Angrist estimated civilian earnings of white veterans were approximately 15% lower in the early 1980s in the comparison studied. That figure pertains to that analysis and period; causal interpretation requires eligibility not to affect earnings through other channels.

Angrist and Krueger used quarter of birth as an instrument for years of schooling through school entry and leaving rules. For men aged 40–49 in the 1970 census, their table IV reports an OLS slope of 0.080 and 2SLS slope of 0.077 with birth-year effects. Treatment there is years of education, not binary attendance: the four-type binary table cannot simply be transferred or the coefficient called a universal ATE. Quarter exclusion is an assumption about other seasonal paths, not an automatic consequence of birth date.

The following comparison uses the aggregate file from Angrist’s replication documentation, downloaded from a browser-accessible mirror and hash-checked against the original. The earnings numerator and first stage come from different sources; the file filters positive earnings and smooths the first stage across cohorts. Thus the ratio is an illustrative reproduction under comparability and selection assumptions, not automatic proof of LATE. The result does not exactly reproduce every published row.

[ ]vietnam downloadBrowser
import io
import hashlib
import pandas as pd
from pyodide.http import pyfetch

# Copia del archivo de replicación distribuido por Angrist; la fuente oficial
# MIT no ofrece CORS al navegador. La huella cotejada con el original MIT.
url='https://raw.githubusercontent.com/acmi-lab/online-moment-selection/main/data/cwhsc_new.dta'
response=await pyfetch(url)
if not response.ok: raise RuntimeError(f'Error HTTP {response.status}')
contenido=await response.bytes()
huella=hashlib.sha256(contenido).hexdigest()
esperada='a2804a64979cc236dfc341cf22e457a3b49f334d453426e09f0121e5ceb118f3'
if huella!=esperada: raise ValueError('La copia ya no coincide con el archivo de MIT')
datos=pd.read_stata(io.BytesIO(contenido))
print('Datos originales replicados: filas y columnas',datos.shape)
print('SHA-256 comprobado:',huella)
[ ]vietnam waldBrowser
import numpy as np

# En cohorte 1950 el fichero ya agrupa números de lotería en dos intervalos:
# intervalo 1 elegible, intervalo 2 no elegible. No son datos individuales.
# Fuentes y construcción descritas en Angrist (1990), tablas 2 y 3 y código MIT.
grupo=datos[(datos.byr==50)&(datos.race==1)&(datos.type=='ADJ')&datos.year.isin([81,82,83,84])]
print('Cohorte 1950, hombres blancos, ingresos FICA ajustados, dólares de 1978')
for año in (81,82,83,84):
    filas=grupo[grupo.year==año].set_index('interval')
    assert len(filas)==2 and set(filas.index)=={1,2}
    elegible=filas.loc[1]; no_elegible=filas.loc[2]
    efecto_y=float(elegible.earnings-no_elegible.earnings)
    etapa1=float(elegible.ps_r-no_elegible.ps_r)
    if etapa1<=0: raise ValueError('Primera etapa no positiva')
    print('Año',1900+año,'medias Y:',round(float(elegible.earnings),2),
          round(float(no_elegible.earnings),2),'diferencia de medias:',round(efecto_y,2),
          'primera etapa:',round(etapa1,4),'cociente:',round(efecto_y/etapa1,2))

print('El cociente combina ingresos de CWHS con tasas SIPP ponderadas y suavizadas en tres cohortes.')
print('Las medias de ingresos condicionan en ingresos positivos; la selección podría depender del servicio.')
print('Un LATE requiere independencia, exclusión, monotonía y poblaciones/selección compatibles.')

Lab: noncompliance in a trial

Assignment is random by construction and potential outcomes are known only to audit the experiment. The per-protocol comparison retains treated invitees and untreated noninvitees: it conditions on receipt, which follows randomization. Wald’s delta standard error assumes a suitable first stage and moments.

[ ]noncompliance setupBrowser
import numpy as np

def noncompliance_sample(n=12000,seed=181801,defiers=False):
    """Tipos y resultados potenciales; Z es independiente de todos ellos."""
    rng=np.random.default_rng(seed)
    # Tipo 0 nunca, 1 cumplidor, 2 siempre, 3 desafiante.
    probs=np.array([.30,.50,.20,0.]) if not defiers else np.array([.25,.45,.20,.10])
    kind=rng.choice(4,size=n,p=probs)
    # X y Y(0) dependen del tipo: as-treated está sometido a selección.
    x=rng.normal(loc=np.array([-.5,.4,1.,-.2])[kind],scale=1.)
    y0=1+.8*x+np.array([-.2,.2,.8,-.4])[kind]+rng.normal(size=n)
    treatment_effect=np.array([.5,2.,3.,-1.])[kind]+.3*x
    y1=y0+treatment_effect
    d0=np.isin(kind,[2,3]).astype(int)
    d1=np.isin(kind,[1,2]).astype(int)
    z=rng.binomial(1,.5,size=n)
    d=np.where(z==1,d1,d0)
    y=np.where(d==1,y1,y0)
    return dict(x=x,y=y,z=z,d=d,d0=d0,d1=d1,kind=kind,y0=y0,y1=y1,tau=treatment_effect)

def diff_z(v,z):
    if not np.any(z==0) or not np.any(z==1):
        raise ValueError('Se necesitan ambos brazos de asignación')
    return float(v[z==1].mean()-v[z==0].mean())

def fit_estimands(sample):
    y,d,z,x=(sample[k] for k in ('y','d','z','x'))
    first=diff_z(d,z);itt=diff_z(y,z)
    if abs(first)<1e-10: raise ValueError('Primera etapa nula')
    theta=itt/first
    p=z.mean();res=y-theta*d
    inf=(z/p-(1-z)/(1-p))*(res-np.where(z==1,res[z==1].mean(),res[z==0].mean()))/first
    se=inf.std(ddof=1)/np.sqrt(len(y))
    # κ de Abadie puede tomar valores negativos en muestras finitas.
    kappa=1-d*(1-z)/(1-p)-(1-d)*z/p
    k1=d*(z/p-(1-z)/(1-p))
    k0=(1-d)*((1-z)/(1-p)-z/p)
    if min(abs(kappa.mean()),abs(k0.mean()),abs(k1.mean()))<1e-10:
        raise ValueError('Peso de cumplidores nulo')
    complier_x=np.mean(kappa*x)/kappa.mean()
    complier_y1=np.mean(k1*y)/k1.mean()
    complier_y0=np.mean(k0*y)/k0.mean()
    # 2SLS con intercepto: proyección explícita, no productos de matrices n×n.
    W=np.column_stack((np.ones(len(z)),z)); A=np.column_stack((np.ones(len(d)),d))
    [email protected](W,A,rcond=None)[0]
    coef=np.linalg.lstsq(pred,y,rcond=None)[0][1]
    assert np.isclose(coef,theta,atol=1e-10)
    return first,itt,theta,se,complier_x,complier_y0,complier_y1,float(kappa.mean()),float(np.mean(kappa<0))

print('SCM de tipos de cumplimiento, tratamiento y resultados potenciales; Z aleatoria.')
[ ]noncompliance trialBrowser
s=noncompliance_sample()
first,itt,theta,se,cx,c0,c1,pi,neg=fit_estimands(s)
z,d,y,kind,x=(s[k] for k in ('z','d','y','kind','x'))
compliers=kind==1
as_treated=y[d==1].mean()-y[d==0].mean()
# Comparación por protocolo: asignados al tratamiento y tratados frente a
# asignados al control y no tratados. Selecciona en variable posterior.
per_protocol=y[(z==1)&(d==1)].mean()-y[(z==0)&(d==0)].mean()
print('n:',len(y),'proporciones de tipos:',np.round(np.bincount(kind,minlength=4)/len(y),4))
print('ITT Y:',round(itt,4),'primera etapa:',round(first,4),'Wald = MC2E:',round(theta,4),'EE delta:',round(se,4))
print('LATE verdadero de esta muestra:',round(s['tau'][compliers].mean(),4),'ATE muestra:',round(s['tau'].mean(),4))
print('As-treated:',round(as_treated,4),'por protocolo:',round(per_protocol,4))
print('κ: proporción',round(pi,4),'media X',round(cx,4),'Y0/Y1',round(c0,4),round(c1,4),'pesos negativos:',round(neg,4))
print('Verdad de cumplidores: proporción',round(compliers.mean(),4),'media X',round(x[compliers].mean(),4),
      'Y0/Y1',round(s['y0'][compliers].mean(),4),round(s['y1'][compliers].mean(),4))
print('Estimaciones muestrales sujetas a azar; p de asignación estimado por proporción observada.')
[ ]noncompliance defiersBrowser
s_def=noncompliance_sample(seed=181802,defiers=True)
dfirst,ditt,dtheta,_,_,_,_,_,_=fit_estimands(s_def)
cc=s_def['kind']==1; dd=s_def['kind']==3
pc,pd=cc.mean(),dd.mean()
late_c=s_def['tau'][cc].mean(); late_d=s_def['tau'][dd].mean()
identity=(pc*late_c-pd*late_d)/(pc-pd)
print('Desafiantes: primera etapa observada',round(dfirst,4),'Wald',round(dtheta,4))
print('Identidad poblacional empírica de tipos:',round(identity,4),
      'LATE cumplidores',round(late_c,4),'efecto desafiantes',round(late_d,4))
print('La identidad de tipos y Wald difieren en muestra finita por la asignación aleatoria.')
print('Con desafiantes, κ pondera cumplidores +1 y desafiantes −1 en esperanza; no identifica solo cumplidores.')

Lab: local instruments and MTE

Here instrument and latent resistance are independent uniform variables. We fit a linear propensity and quadratic conditional mean; the resulting derivative depends on that functional form. Theoretical support reaches the endpoints, but information there may be sparse. Counterfactuals are used only for auditing, not estimating the curve.

[ ]mte 01 estimationBrowser
import numpy as np

# Z y U son independientes uniformes: la asignación instrumental es válida
# en este modelo explícito. U es resistencia no observada para el estimador.
rng = np.random.default_rng(271818)
n = 100_000
z = rng.uniform(0,1,n)
u = rng.uniform(0,1,n)
error = rng.normal(0,0.35,n)
y0 = 2+u+error
tau = 1+2*u
y1 = y0+tau
tratamiento = (u <= z).astype(float)
y = np.where(tratamiento == 1,y1,y0)

# Primera etapa: el modelo correcto aquí es P(D=1|Z)=a+bZ=Z.
design_p = np.column_stack([np.ones(n),z])
alpha = np.linalg.lstsq(design_p,tratamiento,rcond=None)[0]
p_bruto = design_p@alpha
p_estimado = np.clip(p_bruto,0,1)

# Segunda etapa paramétrica: E[Y|P=p] = c0+c1 p+c2 p².
# El estimador usa Y, D y Z, nunca observa U ni los contrafactuales.
design_y = np.column_stack([np.ones(n),p_estimado,p_estimado**2])
beta = np.linalg.lstsq(design_y,y,rcond=None)[0]
puntos = np.array([0.1,0.25,0.5,0.75,0.9])
mte_estimada = beta[1]+2*beta[2]*puntos
print('n y tasa tratada:',n,tratamiento.mean())
print('Propensity: intercepto, pendiente y número recortado a [0,1]:',
      alpha, int(np.count_nonzero((p_bruto<0)|(p_bruto>1))))
print('Soporte muestral de propensity estimada:',p_estimado.min(),p_estimado.max())
print('Coeficientes de E[Y|p], estimados:',beta)
print('MTE por derivada, p=',puntos,':',np.round(mte_estimada,4))
print('MTE teórica en esos puntos:',1+2*puntos)
[ ]mte 02 integralsBrowser
# Para evaluar la curva derivada, promediamos con pesos propios de cada estimando.
grid = np.linspace(0,1,2001)
curva = beta[1]+2*beta[2]*grid
sorted_p = np.sort(p_estimado)
# Distribución estimada del propensity: Pr(P>u) y Pr(P<=u).
below = np.searchsorted(sorted_p,grid,side='right')/len(sorted_p)
mean_p = p_estimado.mean()
w_att = (1-below)/mean_p
w_atu = below/(1-mean_p)
mask = (grid >= 0.2) & (grid <= 0.4)
ate_hat = np.trapezoid(curva,grid)
att_hat = np.trapezoid(curva*w_att,grid)
atu_hat = np.trapezoid(curva*w_atu,grid)
late_hat = np.trapezoid(curva[mask],grid[mask])/(0.4-0.2)
print('Área de los pesos ATT y ATU:',np.trapezoid(w_att,grid),np.trapezoid(w_atu,grid))
print('Estimaciones ATE, ATT, ATU, LATE(0,2 a 0,4):',
      np.round([ate_hat,att_hat,atu_hat,late_hat],4))
print('Verdades poblacionales:',[2,5/3,7/3,1.6])
print('Verdades finitas de esta muestra (solo para auditar la simulación):',
      np.round([tau.mean(),tau[tratamiento==1].mean(),tau[tratamiento==0].mean(),
                tau[(u>0.2)&(u<=0.4)].mean()],4))
print('El ATE y ATT integran hasta 0 y 1: aquí se usa la forma cuadrática supuesta.')

Exercises

ProofProve LATE
Prove: Assume a binary instrument independent of potential outcomes and treatments, 0<P(Z=1)<10<P(Z=1)<1, integrable potential outcomes, exclusion, consistency, monotonicity D(1)≥D(0)D(1)\ge D(0) and a positive first stage. Prove that the Wald ratio identifies the complier effect.
The proof will appear here as you work.

Step 1 of 3. What does the outcome difference by assignment represent?

ProofFirst stage and types
Prove: Assume instrument independence, consistency D=D(Z)D=D(Z), 0<P(Z=1)<10<P(Z=1)<1 and monotonicity. Prove the difference in treatment rates between arms is the proportion of compliers.
The proof will appear here as you work.

Step 1 of 2. What equality does independence of Z allow?

NumericFrom ITT to LATE
In a trial satisfying IV assumptions, ITT on Y is 2.4 and the difference in treatment rates between arms is 0.6. Calculate Wald LATE.
CodeMoments with κ weights
Implement complier_means(y, d, z, x) for an outcome, treatment, instrument, and one or more covariates. y, d, and z are finite length-n vectors; x is a length-n vector or n by p matrix of finite covariates. d and z are binary and both z values must occur. Let p=mean(z) and pi=mean(d[z==1])-mean(d[z==0]). Require pi to be strictly positive in the sample; reject invalid inputs with ValueError. Calculate Abadie weights k=1-d(1-z)/(1-p)-(1-d)z/p, k1=d(z/p-(1-z)/(1-p)) and k0=(1-d)((1-z)/(1-p)-z/p). Return a dictionary with proporcion=pi, x=mean(kx)/pi (by column for a matrix), y1=mean(k1y)/pi, y0=mean(k0*y)/pi and late=y1-y0. Do not trim negative weights or claim a weak observed first stage proves no causal effect. The ratios identify population complier quantities under instrument independence, exclusion, consistency, monotonicity, and relevance, not from the formula alone.
def complier_means(y, d, z, x):
  # Valida datos y primera etapa; calcula los tres pesos de Abadie.
  # Devuelve proporción, media de x, medias potenciales y LATE.
  raise NotImplementedError
Shift+Enter to run
QuizTwo incentives
Two instruments satisfy IV assumptions for the same treatment but move different people and yield different LATEs. What follows?
QuizAn offer that also informs
The invitation lottery is perfect, but an invitation changes behavior even for nonattendees. What changes?
QuizTypes who respond in reverse
There are compliers and defiers, with a nonzero first stage. How is Wald generally interpreted?

After attempting the numeric exercise, check its calculations and compare two resistance intervals:

[ ]Check Wald and two local effectsBrowser
import numpy as np

# Valores del ejercicio Wald: comprobar después de responder.
itt=2.4
first_stage=.6
assert first_stage>0
wald=itt/first_stage
assert np.isclose(wald,4.)
print('LATE de Wald, ITT 2,4 y primera etapa 0,6:',wald)

# Ejemplo de dos políticas con complidores distintos, no datos de estudios.
# U es uniforme; τ(u)=1+2u. Cada intervalo corresponde a un par de tasas
# de participación y la media se obtiene integrando la curva exactamente.
def late_lineal(a,b):
    if not (0<=a<b<=1): raise ValueError('Intervalo inválido')
    return ((b+b*b)-(a+a*a))/(b-a)
print('LATE del modelo τ(u)=1+2u: intervalos [0,2;0,4] y [0,6;0,8]:',
      round(late_lineal(.2,.4),6),round(late_lineal(.6,.8),6))
print('Dos instrumentos válidos pueden desplazar grupos distintos; no demuestra validez por sí solo.')