Endogeneity: omitted variables, measurement error and simultaneity
Derive omitted-variable, measurement-error and simultaneity bias; examine post-treatment controls and selection; and reason about bias and identification before estimation.
After this lesson you can
- Derive omitted-variable bias and predict its sign in applications.
- Derive classical measurement-error attenuation and assess how controls affect residual reliability.
- Derive the OLS limit in supply and demand and explain why it identifies neither curve.
- Identify post-treatment controls and quantify their effects in simulation.
- Specify the structural model and identifying variation in writing before estimation.
Before you start
An association can be precise and answer another question
Does education increase wages, or do people who study more also differ in difficult-to-observe ability and opportunity? In engineering, an association between code review and fewer errors may reflect review’s effect, but also that teams with better processes review more and prevent errors in other ways. Before interpreting a slope, write down the intervention imagined, factors affecting it and variation that would distinguish its effects.
In , endogeneity arises relative to the structural parameter when correlates with . Under a law of large numbers and suitable moments, simple regression with intercept converges to
The linear projection residual is orthogonal to by construction; do not confuse it with the structural error. A larger sample reduces sampling error around the projection but does not remove a persistent difference from the effect of interest.
The sign of an omitted variable
Let and suppose is orthogonal to relevant regressors. In the short regression omitting ,
The omitted-variable bias formula multiplies two signs: how relates to holding fixed, and how relates to . Matching signs raise the short slope; opposite signs lower it. If the product is sufficiently negative it can reverse the effect’s sign. If either factor is zero, this particular mechanism produces no linear bias.
The population derivation substitutes the structural equation into . The intercept disappears from covariance and term vanishes by assumption. If it does not vanish, additional bias remains: attributing the entire difference to would be incorrect.
| Relationship of W with Y, given X | Relationship of W with X | Shift in short slope |
|---|---|---|
| Positive | Positive | Positive |
| Positive | Negative | Negative |
| Negative | Positive | Negative |
| Negative | Negative | Positive |
The table describes this linear model and signs, not the effect of adding an arbitrary variable. For example, more experienced teams reviewing more code and producing fewer errors predict a negative shift if omitted experience has those relationships and other assumptions hold. Identifying how much comes from review still requires exogenous variation or a defensible design.
With controls and the same sample, Frisch-Waugh-Lovell gives the exact identity
The relationship is algebraic for appropriately ranked designs: is the coefficient of when regressing on and . It does not prove the long model controls every common cause or that is causal. Comparing models with different rows breaks this direct identity; use the intersection of observations before comparing.
Classical measurement error
Let , with , measurement error independent of and structural error, and . If , classical measurement-error attenuation in simple regression with intercept is
The fraction is the reliability ratio. It approaches one without noise and zero when error variance dominates. This is a claim about the limit under assumptions, not every sample: a finite estimate can move away from zero.
The calculation uses and . If relates to or , additional covariances appear in numerator or denominator: direction need not remain toward zero. The figure’s exercise fixes the generator so changing noise compares the same underlying sample.
If controlling for , replace by its linear residual against a constant and and require it to be orthogonal to the linear residual of . With measurement error independent of , and , its variance remains in the denominator and residual signal can shrink. If true variance and residual denominator are positive, residual reliability is at most original reliability. In the degenerate case without residual signal or noise, the ratio is and partial slope is undefined. This is not a law for every control or error: a control can induce residual correlation with , and nonclassical errors, noisy controls or correlation of with the outcome can change magnitude and sign. Fixed effects can similarly reduce true variation, but the conclusion also depends on how noise changes under transformation.
Equilibria: supply and demand move together
Simultaneity arises when price and quantity are jointly determined. Consider
Imposing and assuming independent zero-mean shocks with variances and , the population coefficient of regressing equilibrium quantity on price is
To derive it, substitute into either curve. Covariance with contains both demand and supply shifts. If only supply varies, points trace demand; if only demand varies, they trace supply. With both variances positive, the slope lies between and and identifies neither. With correlated shocks the formula changes and that average interpretation need not hold. The equilibrium identification problem dates to Working.
More explicitly, the random component of quantity is . Independence implies and . Division cancels the common denominator. If both shocks are constant, price does not vary and the quantity-on-price regression has no identified slope.
Bad controls and selection
A bad control depends on the causal question. If intervention affects mediator , controlling for removes part of the total effect; it may be relevant to a direct effect under additional assumptions but does not automatically answer the same question. If also , conditioning on can open an association between and . A mediator is not necessarily a collider: it is one in that example because it receives two causes.
To see this algebraically, let be independent and centered, and . The total effect of intervening on is . Including and in regression and substituting gives an coefficient equal to . The difference includes mediation and the path opened by the control; signs depend on parameters.
Selecting the sample using the outcome, for example observing only people above a wage threshold, can also make regressor and error dependent within the sample. Direction is not universal. Comparing coefficients before and after adding an observed control informs that specification, but little change does not rule out other omitted variables.
The lab includes a closed-form case: and independent standard normals, and selection . Before selection, slope is one. Afterwards, for each value of , and . The variance of a centered normal with variance two conditional on being positive is ; thus the selected slope is . This direction belongs to the specified generator, not all selection.
From suspicion to identification
For each analysis first write the target effect, structural equation, omitted factors and identifying variation. Random assignment can separate treatment and prior causes; an instrument needs exclusion and relevance; panels require assumptions about unobserved factors; discontinuities and difference-in-differences require specific design conditions. These strategies are developed later: none is validated by obtaining a small standard error.
Lab: mechanisms with known truth
Generate independent samples for omission, measurement error, simultaneity, post-treatment control and selection. Each result is compared with its generator’s limit; Monte Carlo spread indicates precision of the simulated mean and does not remove finite bias. A fixed-effects example with independent noise is also shown: its result depends on transient signal and does not transfer to every panel without conditions.
"""Cinco mecanismos con parámetros conocidos; 1000 muestras por mecanismo."""
import numpy as np
N=600
REPS=1000
rng=np.random.default_rng(270401)
def slope(x,y):
"""Pendiente con intercepto; cada fila es una muestra independiente."""
xc=x-x.mean(axis=1,keepdims=True)
yc=y-y.mean(axis=1,keepdims=True)
return np.sum(xc*yc,axis=1)/np.sum(xc*xc,axis=1)
def partial_slope(x,y,z):
"""FWL con intercepto y un control; regresión de residuos sobre residuos."""
xc=x-x.mean(axis=1,keepdims=True)
yc=y-y.mean(axis=1,keepdims=True)
zc=z-z.mean(axis=1,keepdims=True)
zz=np.sum(zc*zc,axis=1,keepdims=True)
rx=xc-zc*np.sum(zc*xc,axis=1,keepdims=True)/zz
ry=yc-zc*np.sum(zc*yc,axis=1,keepdims=True)/zz
return np.sum(rx*ry,axis=1)/np.sum(rx*rx,axis=1)
def report(name,estimates,limit):
estimates=np.asarray(estimates)
mean=float(estimates.mean())
mc_se=float(estimates.std(ddof=1)/np.sqrt(len(estimates)))
print(name,'media:',mean,'EE Monte Carlo:',mc_se,'límite teórico:',limit,
'diferencia:',mean-limit,'réplicas:',len(estimates))
# Omisión: Y=βX+γU+ε, X=ρU+√(1−ρ²)V, variables normales independientes.
rho=.6; beta=.8; gamma=1.2
U=rng.normal(size=(REPS,N)); V=rng.normal(size=(REPS,N)); E=rng.normal(size=(REPS,N))
X=rho*U+np.sqrt(1-rho**2)*V
Y=beta*X+gamma*U+E
short=slope(X,Y)
long=partial_slope(X,Y,U)
ability_slope=slope(X,U)
ability_effect=partial_slope(U,Y,X)
assert np.allclose(short-long,ability_effect*ability_slope,atol=1e-10)
report('Omisión: regresión corta',short,beta+gamma*rho)
report('Omisión: ajustada por U',long,beta)
print('FWL: máxima diferencia de la identidad exacta:',np.max(np.abs(short-long-ability_effect*ability_slope)))
# Error clásico independiente, sin efecto directo de Z en el resultado.
# Al residualizar X* respecto a Z queda varianza 1-rho², menor que la inicial.
rho=.8; beta=2.; noise_variance=1.
Z=rng.normal(size=(REPS,N)); V=rng.normal(size=(REPS,N)); E=rng.normal(size=(REPS,N))
X_true=rho*Z+np.sqrt(1-rho**2)*V
X_obs=X_true+np.sqrt(noise_variance)*rng.normal(size=(REPS,N))
Y=beta*X_true+E
naive=slope(X_obs,Y); conditional=partial_slope(X_obs,Y,Z)
unconditional_limit=beta/(1+noise_variance)
conditional_limit=beta*(1-rho**2)/(1-rho**2+noise_variance)
report('Medida: sin control',naive,unconditional_limit)
report('Medida: con Z',conditional,conditional_limit)
print('La mayor atenuación usa estos supuestos clásicos; no es una regla para cualquier error o control.')
# Panel con errores de medida iid: al eliminar la media individual, la
# señal entre individuos desaparece. Aquí el ruido tiene la misma estructura
# temporal que el componente transitorio verdadero, no es un resultado universal.
groups,periods=150,4
panel_rng=np.random.default_rng(270402)
permanent=panel_rng.normal(size=(REPS,groups,1))
transitory=panel_rng.normal(size=(REPS,groups,periods))
Xstar=np.sqrt(.75)*permanent+np.sqrt(.25)*transitory
error_measure=panel_rng.normal(size=(REPS,groups,periods))
observed=Xstar+error_measure
individual_effect=panel_rng.normal(size=(REPS,groups,1))
outcome=2*Xstar+individual_effect+panel_rng.normal(size=(REPS,groups,periods))
pooled=slope(observed.reshape(REPS,-1),outcome.reshape(REPS,-1))
within_x=observed-observed.mean(axis=2,keepdims=True)
within_y=outcome-outcome.mean(axis=2,keepdims=True)
within=np.sum(within_x*within_y,axis=(1,2))/np.sum(within_x**2,axis=(1,2))
report('Panel: regresión agrupada',pooled,2/(1+1))
report('Panel: efectos fijos individuales',within,2*.25/(.25+1))
print('La comparación depende de ruido de medida iid y de los componentes transitorios elegidos.')
# Equilibrio: demanda Q=a-bP+εd; oferta Q=c+dP+εs, shocks independientes.
b=2.; d=1.; var_d=1.; var_s=4.
shock_d=np.sqrt(var_d)*rng.normal(size=(REPS,N))
shock_s=np.sqrt(var_s)*rng.normal(size=(REPS,N))
P=(shock_d-shock_s)/(b+d)
Q=(d*shock_d+b*shock_s)/(b+d)
market=slope(P,Q)
market_limit=(d*var_d-b*var_s)/(var_d+var_s)
report('Simultaneidad: cantidad sobre precio',market,market_limit)
print('Pendientes estructurales: demanda',-b,'y oferta',d,'; shocks con ambas varianzas positivas.')
# M es simultáneamente mediador y colisionador de D y U en este modelo.
a=.7; tau=1.; gamma=.8; delta=.6
D=rng.normal(size=(REPS,N)); U=rng.normal(size=(REPS,N)); E=rng.normal(size=(REPS,N))
M=a*D+U; Y=tau*D+gamma*M+delta*U+E
report('Control posterior: sin M',slope(D,Y),tau+gamma*a)
report('Control posterior: con M',partial_slope(D,Y,M),tau-a*delta)
print('Efecto directo estructural:',tau,'efecto total:',tau+gamma*a,
'; el coeficiente controlado contiene además sesgo de colisión.')
# Selección por el resultado: X,E iid normales; Y=X+E; se conservan Y>0.
X=rng.normal(size=(REPS,N)); E=rng.normal(size=(REPS,N)); Y=X+E
selected=Y>0
counts=selected.sum(axis=1)
if np.any(counts<3): raise ValueError('Muestra seleccionada insuficiente')
mx=np.sum(np.where(selected,X,0.),axis=1)/counts
my=np.sum(np.where(selected,Y,0.),axis=1)/counts
xc=np.where(selected,X-mx[:,None],0.)
yc=np.where(selected,Y-my[:,None],0.)
selected_slope=np.sum(xc*yc,axis=1)/np.sum(xc*xc,axis=1)
limit=(np.pi-2)/(np.pi-1)
report('Selección Y>0: pendiente',selected_slope,limit)
print('La dirección de este sesgo depende del modelo; no es universal.')Local lab: education and wages
Install wooldridge alongside NumPy and statsmodels in your local environment. In wage2 one common sample is used and experience, tenure and urban status are controlled. The difference between slopes with and without IQ exactly matches the product of auxiliary coefficients: it is a descriptive identity. IQ is an incomplete proxy for ability and these observational data do not prove the remaining coefficient is causal.
"""wage2: descomposición de variable omitida en una misma muestra.
Requiere numpy, pandas, statsmodels y wooldridge. IQ es un proxy imperfecto,
no garantiza ausencia de confusión ni identifica el rendimiento causal.
"""
import numpy as np
import statsmodels.api as sm
import wooldridge as woo
columns=['lwage','educ','IQ','exper','tenure','urban']
data=woo.data('wage2')[columns].dropna().copy()
if not np.isfinite(data.to_numpy(dtype=float)).all(): raise ValueError('Datos no finitos')
controls=['exper','tenure','urban']
short_X=sm.add_constant(data[['educ',*controls]],has_constant='add')
long_X=sm.add_constant(data[['educ','IQ',*controls]],has_constant='add')
aux_X=short_X.copy()
short=sm.OLS(data.lwage,short_X).fit()
long=sm.OLS(data.lwage,long_X).fit()
aux=sm.OLS(data.IQ,aux_X).fit()
difference=float(short.params['educ']-long.params['educ'])
product=float(long.params['IQ']*aux.params['educ'])
assert np.isclose(difference,product,rtol=1e-10,atol=1e-10)
# FWL: proyecta educación e IQ sobre los mismos controles y una constante.
control_X=sm.add_constant(data[controls],has_constant='add').to_numpy()
q,_=np.linalg.qr(control_X,mode='reduced')
educ=data.educ.to_numpy(); ability=data.IQ.to_numpy()
education_res=educ-q@(q.T@educ)
ability_res=ability-q@(q.T@ability)
partial=(education_res@ability_res)/(education_res@education_res)
assert np.isclose(partial,aux.params['educ'],rtol=1e-10,atol=1e-10)
print('wage2, muestra completa común:',len(data),'controles:',controls)
print('Coef. educación: corto',short.params['educ'],'largo',long.params['educ'])
print('Coef. IQ en larga:',long.params['IQ'],'coef. parcial IQ sobre educación:',partial)
print('Diferencia corto menos largo:',difference,'producto:',product)
print('Las magnitudes son asociaciones de esta muestra; IQ no mide toda la capacidad ni garantiza exogeneidad.')npm run lab and open the connection link.Exercises
Step 1 of 3. What remains of the long regression after multiplying by M_Z?
Step 1 of 3. What is the equilibrium price?
import numpy as np
def ovb_decomposition(y,x,w):
passvariance_true,variance_noise,beta=4.,1.,2.
print('Fiabilidad y pendiente límite:',variance_true/(variance_true+variance_noise),beta*variance_true/(variance_true+variance_noise))