Module contents
Lesson 4 of 28Core 90 min

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 Y=α+βX+uY=\alpha+\beta X+u, endogeneity arises relative to the structural parameter when XX correlates with uu. Under a law of large numbers and suitable moments, simple regression with intercept converges to

plim⁡β^=β+Cov⁡(X,u)Var⁡(X).\operatorname{plim}\hat\beta =\beta+\frac{\operatorname{Cov}(X,u)}{\operatorname{Var}(X)}.

The linear projection residual is orthogonal to XX 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 Y=α+βX+γW+uY=\alpha+\beta X+\gamma W+u and suppose uu is orthogonal to relevant regressors. In the short regression omitting WW,

βcorta−β=γCov⁡(X,W)Var⁡(X).\beta_{\mathrm{corta}}-\beta =\gamma\frac{\operatorname{Cov}(X,W)}{\operatorname{Var}(X)}.

The omitted-variable bias formula multiplies two signs: how WW relates to YY holding XX fixed, and how WW relates to XX. 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 Cov⁡(X,Y)/Var⁡(X)\operatorname{Cov}(X,Y)/\operatorname{Var}(X). The intercept disappears from covariance and term Cov⁡(X,u)\operatorname{Cov}(X,u) vanishes by assumption. If it does not vanish, additional bias remains: attributing the entire difference to WW would be incorrect.

Relationship of W with Y, given XRelationship of W with XShift in short slope
PositivePositivePositive
PositiveNegativeNegative
NegativePositiveNegative
NegativeNegativePositive

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.

InteractiveA map of bias signs

Population model: X and W have zero mean, unit variance and correlation ρ; Y=0.7X+γW+ε, with independent centered ε. Omitting W makes the coefficient of X equal 0.7+γρ. Change both parameters to find a negative slope.

  • Positive bias
  • Negative bias
−0.950.000.95-202Correlation ρEffect γ0
  • Structural effect β
  • Short-regression slope

The short-regression slope remains positive. A negative slope requires γρ<−0.7; negative correlation alone is not enough.

Color shows γρ: greater intensity means greater magnitude. On either axis bias is zero. The identity uses Var(X)=Var(W)=1; with other scales it becomes γCov(X,W)/Var(X). Causal interpretation comes from assumptions of the structural equation, not regression alone.

-0.60
1.0
Structural effect β0.70
Bias γρ−0.600
Short-regression slope β+γρ0.100
Change the omitted variable's effect and its correlation with the regressor.

With controls ZZ and the same sample, Frisch-Waugh-Lovell gives the exact identity

β^corta−β^larga=γ^largaπ^,π^=(MZx)⊤MZw(MZx)⊤MZx.\hat\beta_{\mathrm{corta}}-\hat\beta_{\mathrm{larga}} =\hat\gamma_{\mathrm{larga}}\hat\pi, \qquad \hat\pi=\frac{(M_Zx)^\top M_Zw}{(M_Zx)^\top M_Zx}.

The relationship is algebraic for appropriately ranked designs: π^\hat\pi is the coefficient of xx when regressing ww on xx and ZZ. It does not prove the long model controls every common cause or that β^larga\hat\beta_{\mathrm{larga}} is causal. Comparing models with different rows breaks this direct identity; use the intersection of observations before comparing.

Classical measurement error

Let X=X∗+ηX=X^*+\eta, with E[η]=0E[\eta]=0, measurement error independent of X∗X^* and structural error, and Cov⁡(X∗,u)=0\operatorname{Cov}(X^*,u)=0. If Y=α+βX∗+uY=\alpha+\beta X^*+u, classical measurement-error attenuation in simple regression with intercept is

plim⁡β^=βVar⁡(X∗)Var⁡(X∗)+Var⁡(η).\operatorname{plim}\hat\beta =\beta\frac{\operatorname{Var}(X^*)} {\operatorname{Var}(X^*)+\operatorname{Var}(\eta)}.

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 Cov⁡(X,Y)=βVar⁡(X∗)\operatorname{Cov}(X,Y)=\beta\operatorname{Var}(X^*) and Var⁡(X)=Var⁡(X∗)+Var⁡(η)\operatorname{Var}(X)=\operatorname{Var}(X^*)+\operatorname{Var}(\eta). If η\eta relates to uu or X∗X^*, 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 ZZ, replace X∗X^* by its linear residual against a constant and ZZ and require it to be orthogonal to the linear residual of uu. With measurement error independent of ZZ, X∗X^* and uu, 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 0/00/0 and partial slope is undefined. This is not a law for every control or error: a control can induce residual correlation with uu, and nonclassical errors, noisy controls or correlation of η\eta 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.

InteractiveNoise that flattens slopes

Each point comes from a reproducible sample of 360 observations. The cloud and line use centered variables; when controlling, the displayed values are residuals of observed X and Y after projecting each on a constant and Z.

Horizontal axis: centered observed X. Vertical axis: centered Y.

  • Observations
  • OLS slope

Explicit model: Z and V are independent standard normals; true X = ρZ+√(1−ρ²)V; observed X = true X+ση; Y=2 true X+0.6ε. Errors η and ε are normal and independent of Z and V. The sample is finite and may differ from the theoretical limit.

Without a control reliability is 1/(1+σ²); with Z it is (1−ρ²)/(1−ρ²+σ²). Increasing ρ leaves less true residual variation while measurement-error variance stays fixed. The conclusion depends on those classical assumptions; nonclassical errors may behave differently.

0.7
0.60
Sample slope1.322
Population limit1.342
Reliability ratio0.671
Structural slope2
Add measurement error and compare the slope with and without residualizing by a control.

Equilibria: supply and demand move together

Simultaneity arises when price and quantity are jointly determined. Consider

Qd=a−bP+εd,Qs=c+dP+εs,b,d>0.Q^d=a-bP+\varepsilon_d,\qquad Q^s=c+dP+\varepsilon_s, \qquad b,d>0.

Imposing Qd=QsQ^d=Q^s and assuming independent zero-mean shocks with variances vdv_d and vsv_s, the population coefficient of regressing equilibrium quantity on price is

Cov⁡(P,Q)Var⁡(P)=d vd−b vsvd+vs,vd+vs>0.\frac{\operatorname{Cov}(P,Q)}{\operatorname{Var}(P)} =\frac{d\,v_d-b\,v_s}{v_d+v_s}, \qquad v_d+v_s>0.

To derive it, substitute P=(a−c+εd−εs)/(b+d)P=(a-c+\varepsilon_d-\varepsilon_s)/(b+d) into either curve. Covariance with PP 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 −b-b and dd 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 (dεd+bεs)/(b+d)(d\varepsilon_d+b\varepsilon_s)/(b+d). Independence implies Var⁡(P)=(vd+vs)/(b+d)2\operatorname{Var}(P)=(v_d+v_s)/(b+d)^2 and Cov⁡(P,Q)=(dvd−bvs)/(b+d)2\operatorname{Cov}(P,Q)=(dv_d-bv_s)/(b+d)^2. Division cancels the common denominator. If both shocks are constant, price does not vary and the quantity-on-price regression has no identified slope.

InteractiveWorking's equilibrium cloud

Each point is an equilibrium calculated by equating supply and demand after two independent shocks. Dashed curves show structural functions without shocks; the solid line fits the equilibrium cloud.

  • Equilibria
  • Demand without shock
  • Supply without shock
  • OLS on equilibria

Synthetic linear model: Qᵈ = 10 − P + uᵈ and Qˢ = 2 + 0.7P + uˢ, with centered independent normal shocks. Every point satisfies Qᵈ = Qˢ. This approximation has no positivity constraints, so large shocks may produce negative prices or quantities.

If only supply varies, points trace demand; if only demand varies, they trace supply. When both vary, the population slope of Q on P is [0.7 Var(uᵈ) − Var(uˢ)] / [Var(uᵈ) + Var(uˢ)]. The sample slope fluctuates around that limit and can coincide with a curve by chance. If both variances are zero, all points coincide and the OLS slope is undefined.

Variation is simulated with a fixed seed, not from an observed market. The variances change the spread of the same normalized shocks until you select “New shocks”.

1.0
2.0
OLS slope of scatter−0.418
OLS population limit−0.433
Demand slope−1.00
Supply slope0.70
Equilibria300
Seed270404
Change shock variance and compare structural and equilibrium slopes.

Bad controls and selection

A bad control depends on the causal question. If intervention DD affects mediator MM, controlling for MM 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 D→M←U→YD\to M\leftarrow U\to Y, conditioning on MM can open an association between DD and UU. A mediator is not necessarily a collider: it is one in that example because it receives two causes.

To see this algebraically, let D,U,εD,U,\varepsilon be independent and centered, M=aD+UM=aD+U and Y=τD+γM+δU+εY=\tau D+\gamma M+\delta U+\varepsilon. The total effect of intervening on DD is τ+γa\tau+\gamma a. Including DD and MM in regression and substituting U=M−aDU=M-aD gives an DD coefficient equal to τ−aδ\tau-a\delta. 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: XX and ε\varepsilon independent standard normals, Y=X+εY=X+\varepsilon and selection Y>0Y>0. Before selection, slope is one. Afterwards, for each value of YY, E[X∣Y]=Y/2E[X\mid Y]=Y/2 and Var⁡(X∣Y)=1/2\operatorname{Var}(X\mid Y)=1/2. The variance of a centered normal with variance two conditional on being positive is 2(1−2/π)2(1-2/\pi); thus the selected slope is (π−2)/(π−1)(\pi-2)/(\pi-1). 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.

[ ]Simulate five sources of biasBrowser
"""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.

[ ]FWL decomposition in wage2Local GPU
"""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.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofSample omitted-variable identity
Prove: On the same sample, compare regressions of y on [Z,x] and [Z,x,w], with full-rank designs. Show the difference between x coefficients is γ̂π̂.
0
Use M_Z to residualize the common block Z.

Step 1 of 3. What remains of the long regression after multiplying by M_Z?

NumericReliability and slope limit
If Var(X*)=4, Var(η)=1 and β=2, under independent classical error, what does the simple slope with intercept converge to?
ProofDerive the equilibrium slope
Prove: With Qd=a−bP+εd, Qs=c+dP+εs, b,d>0 and independent shocks of variances vd and vs, derive the population slope of Q on P.
0
First solve equilibrium, then calculate covariances.

Step 1 of 3. What is the equilibrium price?

QuizPre- and post-treatment controls
An intervention changes review practice, which later affects defects. Prior experience also influences assignment and defects. For the total effect, which decision requires most caution?
QuizEducation and occupation
To estimate the total effect of education on wages, which variable requires particular caution if determined after studying?
QuizAdvertising and traffic
A campaign affects visits, which affect sales. Which control can block part of the campaign’s total effect?
QuizTreatment and recovery
In a medical treatment study, which variable can occur after treatment and mediate its total effect on recovery?
QuizTraining and hiring
When studying training’s effect on hiring, what selection can induce an unrepresentative sample if hiring affects who appears in the register?
CodeCheck the omission identity
Implement ovb_decomposition(y,x,w): with equal-length finite vectors, calculate with intercept the short slope of y on x, the long x slope in y on x and w, the coefficient of w in that regression and the slope of w on x. Return (short,long,product). Reject rank-deficient designs.
import numpy as np

def ovb_decomposition(y,x,w):
  pass
Shift+Enter to run
[ ]Check the reliability exerciseBrowser
variance_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))