Module contents
Lesson 1 of 28Review 75 min

Regression the econometric way: projection, FWL and asymptotics

Reinterpret OLS without Gaussian errors as the best linear approximation to a conditional expectation, develop its large-sample sandwich variance under appropriate assumptions, use Frisch-Waugh-Lovell and distinguish descriptive from causal regression.

After this lesson you can

  • Derive the population linear projection and error orthogonality without assuming a linear conditional expectation.
  • Prove Frisch-Waugh-Lovell and interpret a coefficient after controlling for variables.
  • Derive OLS consistency and asymptotic normality with sandwich variance under the stated sampling and moment assumptions.
  • Distinguish a well-estimated projection coefficient from a biased causal parameter using an example.
  • Reproduce a statsmodels OLS summary from a custom implementation.

Before you start

One slope, two questions

You want to know whether more developer training reduces the number of vulnerabilities introduced. A regression can describe how that number varies with training hours in observed data. To conclude what would change if more training were assigned, you must also justify how hours were chosen, which variables are controlled and whether selection or common causes occur.

In the Gaussian linear model, exact distributions follow under specific error assumptions. Here we drop normality and homoskedasticity, but not every assumption: moments, rank and sampling assumptions are needed to discuss limits and standard errors. A descriptive coefficient and causal effect can coincide, but that equality is a claim about the data-generating process.

Conditional expectation is the best predictor

Let YY be square integrable and m(X)=E[Y∣X]m(X)=E[Y\mid X]. The conditional-expectation decomposition writes Y=m(X)+εY=m(X)+\varepsilon with E[ε∣X]=0E[\varepsilon\mid X]=0. This is projection by conditional expectation. For every square-integrable function g(X)g(X),

E[(Y−g(X))2]=E[(Y−m(X))2]+E[(m(X)−g(X))2].E[(Y-g(X))^2]=E[(Y-m(X))^2]+E[(m(X)-g(X))^2].

The cross term is zero because E[ε{m(X)−g(X)}]=E[E[ε∣X]{m(X)−g(X)}]=0E[\varepsilon\{m(X)-g(X)\}]=E[E[\varepsilon\mid X]\{m(X)-g(X)\}]=0. Thus mm minimizes squared error among all measurable predictors of XX, up to changes on probability-zero sets. If XX takes finitely many categories, a saturated regression with one indicator per category estimates each observed group mean; in the population it recovers the CEF for positive-probability categories.

Condition E[ε∣X]=0E[\varepsilon\mid X]=0 is stronger than one zero correlation: it implies E[h(X)ε]=0E[h(X)\varepsilon]=0 for every appropriate integrable function. It follows from defining the residual relative to the CEF itself, not from a guarantee that variables missing from a causal model are irrelevant. If categories with no observations are added, their sample mean is undefined; including every indicator and a constant introduces exact linear dependence.

Projection depends on where data lie

Now restrict predictors to X⊤bX^\top b, including an intercept if desired. If E[Y2]E[Y^2] and E[∥X∥2]E[\|X\|^2] are finite and Q=E[XX⊤]Q=E[XX^\top] is positive definite, the population linear projection is unique:

β=Q−1E[XY],u=Y−X⊤β,E[Xu]=0.\beta=Q^{-1}E[XY],\qquad u=Y-X^\top\beta,\qquad E[Xu]=0.

The final equality follows from normal equations, not a randomized experiment. The CEF can be curved and E[u∣X]E[u\mid X] can be nonzero. For example, if XX is uniform on [0,2][0,2] and m(x)=x2m(x)=x^2, the slope with intercept is Cov⁡(X,X2)/Var⁡(X)=2\operatorname{Cov}(X,X^2)/\operatorname{Var}(X)=2 and intercept −2/3-2/3. The curve’s slope is 2x2x, so the line does not match all local derivatives.

CEF decomposition also explains why the same projection appears if YY is replaced by m(X)m(X): residual Y−m(X)Y-m(X) is orthogonal to every component of XX. For any bb, expanding Y−X⊤b=u+X⊤(β−b)Y-X^\top b=u+X^\top(\beta-b) gives

E[(Y−X⊤b)2]=E[u2]+(b−β)⊤Q(b−β).E[(Y-X^\top b)^2]=E[u^2]+(b-\beta)^\top Q(b-\beta).

The cross term vanishes by E[Xu]=0E[Xu]=0; positive definite QQ makes the minimum unique. If the CEF is linear it coincides with the projection and E[u∣X]=0E[u\mid X]=0. The implication does not reverse from linear orthogonality alone.

The distribution of XX also matters: the criterion integrates squared error with respect to that distribution. Changing where observations concentrate can change the best line even if the conditional curve is identical. If QQ is singular, unique projected predictions may exist in the closed linear space but coefficients are not uniquely identified.

[ ]Check projection and confounding examplesBrowser
from scipy.integrate import quad

# Densidad uniforme en [0,2] y CEF x².
moment = lambda k: quad(lambda x: x**k/2, 0, 2)[0]
ex, ex2, ex3 = moment(1), moment(2), moment(3)
slope = (ex3-ex*ex2)/(ex2-ex**2)
intercept = ex2-slope*ex
print('Uniforme, intercepto y pendiente:', intercept, slope)
# D=U+V; U y V independientes con varianza 1; efecto estructural de D igual a 1.
var_d, cov_du, structural_effect = 2., 1., 1.
descriptive = structural_effect+cov_du/var_d
print('Efecto estructural y pendiente descriptiva:', structural_effect, descriptive)
InteractiveA line weighted by density

Drag with a mouse or finger over the canvas to draw a function. The polyline represents g(x)=E[Y|X=x]; the line minimizes its squared distance weighted by the distribution of X.

  • CEF g(x)
  • Linear projection
-101-101

Density fₐ(x)=(1+ax)/2 on [−1,1]. The control shifts weight toward one end without changing the drawn CEF.

α=E[g(X)]−βE[X] and β=Cov(X,g(X))/Var(X). The curve is integrated piecewise using two-node quadrature, exact for the polynomials here. The button’s quadratic function is approximated by 41 points: its figures correspond to that polyline.

The error shown is E[(g(X)−α−βX)²], not total Y prediction error when there is conditional noise. Orthogonality to 1 and X characterizes this projection; it does not imply zero conditional mean residual or prove causality.

0.00
Intercept α0.3337
Slope β0.0000
Squared distance to CEF0.08889
E[residual]0.000000
E[X · residual]0.000000
E[X]0.000
Var(X)0.3333
Draw a CEF and change the distribution of X to observe its linear projection.

Controlling means residualizing

Partition the design matrix into X=[X1 X2]X=[X_1\ X_2], with full rank, and define M2=I−X2(X2⊤X2)−1X2⊤M_2=I-X_2(X_2^\top X_2)^{-1}X_2^\top. This is a projection matrix onto the complement of the control space. The Frisch-Waugh-Lovell theorem states

β^1=(X1⊤M2X1)−1X1⊤M2y.\hat\beta_1=(X_1^\top M_2X_1)^{-1}X_1^\top M_2y.

The proof eliminates β^2\hat\beta_2 from the normal equations: project y−X1β^1−X2β^2y-X_1\hat\beta_1-X_2\hat\beta_2 onto the orthogonal complement of columns of X2X_2, then impose orthogonality to X1X_1. M2M_2 is symmetric and idempotent, so the expression is also the regression of M2yM_2y on M2X1M_2X_1. If the residualized block lacks full rank, the coefficient is not unique.

With one regressor of interest, residualizing only X1X_1 and regressing yy on it without an intercept gives the same slope because M2X1M_2X_1 is orthogonal to X2X_2. If the constant belongs to X2X_2, adding an intercept to that auxiliary regression also leaves the slope unchanged, since the residualized regressor has mean zero. This is a sample algebraic identity. For standard errors and tests, retain the full model and its degrees of freedom; do not confuse the number of columns in the residual auxiliary regression with the number of parameters originally estimated.

Geometrically, M2X1M_2X_1 is the part of the regressor outside the space spanned by controls. If two regressors are nearly collinear, that vector can have very small norm: the coefficient exists while rank remains, but becomes sensitive to noise. Under spherical errors its scalar conditional variance is σ2/(X1⊤M2X1)\sigma^2/(X_1^\top M_2X_1). The graph uses a reproducible construction with controlled sample correlation to isolate that effect; it does not by itself prove coverage.

InteractiveControlling means residualizing

The plane fits the 90 points. During playback, the portions explained by the constant and x₂ are progressively subtracted from x₁ and y; the scene’s vertical scale is multiplied by 0.5 for visibility.

The residual-plane cloud is fixed for the chosen correlation. Its line has exactly the partial slope of the multiple fit: each point is an observation after removing the projection of both variables on [1, x₂].

  • Observations
  • Residual line

Synthetic construction: x₂, z and ε are centered, sample-orthogonalized normal vectors. Then x₁=ρx₂+√(1−ρ²)z and y=1+1.8x₁+1.2x₂+0.6ε. This fixes correlation exactly and isolates the geometry; the errors are not an iid sample.

The animation transforms components obtained by projecting vectors of 90 observations; it does not project individual 3D points onto a plane. As |ρ| approaches 1, less residual variation remains in x₁ and the classical standard error grows. Its inferential interpretation assumes homoskedastic errors; this figure does not demonstrate coverage or causality.

0.60
0% residualized
Observed correlation0.600
Residual x₁ deviation0.800
Multiple-regression slope1.8000
FWL slope1.8000
Numerical difference< 10⁻¹⁰
Classical slope standard error0.0804
Seed2701
Compare multiple regression with the residual slope and change correlation between regressors.

Law of large numbers and sandwich variance

For an iid sample of (Xi,Yi)(X_i,Y_i), positive definite QQ, E∥X∥2<∞E\|X\|^2<\infty and sufficient moments for products, OLS asymptotics begin with

β^−β=(1n∑iXiXi⊤)−1(1n∑iXiui).\hat\beta-\beta= \left(\frac1n\sum_iX_iX_i^\top\right)^{-1} \left(\frac1n\sum_iX_iu_i\right).

The law of large numbers and E[Xu]=0E[Xu]=0 give consistency. If Ω=E[u2XX⊤]\Omega=E[u^2XX^\top] is also finite, the multivariate CLT and Slutsky imply

n(β^−β) →d N(0,Q−1ΩQ−1).\sqrt n(\hat\beta-\beta)\ \xrightarrow{d}\ N(0,Q^{-1}\Omega Q^{-1}).

Orthogonality alone supplies neither independence, LLN nor CLT. A dependent time sample can require other assumptions and long-run covariance. HC0 estimation replaces moments with

Var⁡^HC0(β^)=(X⊤X)−1(∑iXiXi⊤u^i2)(X⊤X)−1.\widehat{\operatorname{Var}}_{\mathrm{HC0}}(\hat\beta) =(X^\top X)^{-1}\left(\sum_iX_iX_i^\top\hat u_i^2\right)(X^\top X)^{-1}.

The inner matrix retains the relationship between size of XiX_i and squared residual. The classical formula replaces this structure with a common variance. HC0 needs its own convergence conditions and its intervals have no guaranteed exact finite-sample coverage. It does not by itself correct temporal dependence, selection, causal bias or infinite moments.

The robust construction relates to White’s (1980) estimator. Projection, least-squares algebra and asymptotics are developed further in the open text Hansen’s Econometrics.

Sandwich variance does not assume a correctly linear CEF: it estimates uncertainty of the projection coefficient under corresponding sampling and moment conditions. In the special case E[u2∣X]=σ2E[u^2\mid X]=\sigma^2, Ω=σ2Q\Omega=\sigma^2Q and asymptotic variance simplifies to σ2Q−1\sigma^2Q^{-1}. Outside that case, two observations with the same residual error can contribute differently because product XiuiX_iu_i also depends on the regressor vector.

In the figure’s heteroskedastic example, XX and ε\varepsilon are independent standard normals and u=Xεu=X\varepsilon. With intercept, limiting variance of n(β^1−β1)\sqrt n(\hat\beta_1-\beta_1) is E[X4ε2]=3E[X^4\varepsilon^2]=3, while the classical formula converges to E[u2]=1E[u^2]=1. Thus the nominal 95% classical normal interval has limiting coverage 2Φ(1,96/3)−1≈0,7422\Phi(1{,}96/\sqrt3)-1\approx0{,}742, not 0.95. Robust estimation converges to the correct value under the example’s assumptions, but a finite simulation fluctuates randomly and improvement need not be monotonic.

InteractiveClassical and robust coverage

Each sample contains 200 independent pairs. The histogram shows √n(β̂₁−1) for 3000 regressions with an intercept; the curve compares their normal limit for the chosen model.

  • Simulated slopes
  • Asymptotic normal

The plot clips to [−8, 8]: 0 of 3000 slopes fall outside. Density remains normalized over all replicates.

Coverage and 95% Wilson interval across simulations

Classical
74.3 %; Monte Carlo CI [72.7 %, 75.8 %]
HC0
93.0 %; Monte Carlo CI [92.0 %, 93.9 %]
0 %100 %

The vertical mark shows nominal 95%. HC0 minus classical: 18.7 percentage points; approximate paired normal interval [17.3, 20.1]. Both intervals use each same sample, so uncertainty in the difference uses paired disagreements.

Model: X and ε independent, X standard normal, Y=1+X+u. Depending on the control, u is normal ε, conditionally normal Xε, or a t with 3 degrees of freedom divided by √3. Intervals use normal quantile 1.96; the classical interval estimates common residual variance and HC0 uses squared residuals. The heavy-tail model has finite variance and infinite fourth moment.

With u=Xε, √n(β̂₁−1) has limiting variance 3, but the classical standard error converges to the value based on 1: its limiting coverage is 74.2 %. In the other two cases its limit is 95%. These are model limits, not finite-sample guarantees: HC0 can undercover too.

Error distribution
200
1
Classical coverage74.3 %
HC0 coverage93.0 %
HC0 minus classical18.7 percentage points
n × slope mean squared error3.03
Simulate paired samples and compare both intervals, with Monte Carlo uncertainty.
[ ]Limiting coverage of the classical intervalBrowser
import numpy as np
from scipy.stats import norm
z = norm.ppf(.975)
print('Varianza límite verdadera:', 3., 'varianza clásica:', 1.)
print('Cobertura límite clásica:', 2*norm.cdf(z/np.sqrt(3))-1)

Partial association and causal effect

The distinction between descriptive and causal regression appears in an example. Let D=U+VD=U+V and Y=D+U+εY=D+U+\varepsilon, with independent, centered U,V,εU,V,\varepsilon and unit-variance U,VU,V. The population projection of YY on an intercept and DD has slope 1+Cov⁡(D,U)/Var⁡(D)=1+1/2=1,51+\operatorname{Cov}(D,U)/\operatorname{Var}(D)=1+1/2=1{,}5. However, in the structural equation, changing DD by one unit while holding UU and ε\varepsilon fixed changes YY by one unit. The descriptive coefficient is well defined but does not identify that effect.

Conditioning on appropriate common causes can help under explicit identification assumptions. Condition E[u∣X]=0E[u\mid X]=0 in a structural model does not follow automatically from normal equations; nor does it turn an arbitrary control set, such as post-treatment variables, into valid causal adjustment. High or low R2R^2 measures sample fit under a specific definition, not validity of that assumption.

In the structural example, omitted variable UU changes both exposure DD and outcome. Term E[Du]=E[D(U+ε)]=1E[Du]=E[D(U+\varepsilon)]=1 is nonzero for the structural error. By contrast, if projection error is defined as Y−1,5DY-1{,}5D, it is orthogonal to DD by construction. These are different residuals: calling both uu without specifying the model is a common source of confusion. Even when measuring a common cause, ask whether it precedes treatment and suffices for the identification strategy.

Lab: reconstruct a regression

Longley has 16 observations and six regressors plus an intercept. The lab uses QR to estimate coefficients, derives classical and HC0 errors and compares each result with statsmodels. The condition number of an unscaled matrix depends on units: also compare the centered and scaled design. Normal equations form X⊤XX^\top X, whose condition number is the square of that of XX for full rank; this can amplify rounding errors.

The default summary shows classical intervals and statistics, alongside diagnostics and criteria calculated under its conventions. Exact t and F tests depend on their error assumptions; the displayed log-likelihood uses a concentrated Gaussian likelihood. None automatically makes data Gaussian or independent. The cell also calculates HC0, checks each component and verifies FWL with YEAR as the regressor of interest. Longley is a small time series: numerical comparison does not establish HC0 is sufficient for its temporal dependence.

[ ]OLS from QR, errors and conditioningBrowser
"""OLS por QR; summary clásico de Longley y HC0 con comparación independiente."""
import numpy as np
import statsmodels.api as sm
from scipy import stats

data = sm.datasets.longley.load()
X = np.asarray(sm.add_constant(data.exog), dtype=float)
y = np.asarray(data.endog, dtype=float)
names = ['const', *list(data.exog.columns)]
n, p = X.shape
q, r = np.linalg.qr(X, mode='reduced')
if np.linalg.matrix_rank(X) != p:
    raise ValueError('El diseño no tiene rango completo')
b = np.linalg.solve(r, q.T @ y)
residual = y-X@b
sse = residual@residual
centered = y-y.mean()
tss = centered@centered
df = n-p
sigma2 = sse/df
r_inv = np.linalg.solve(r, np.eye(p))
bread = r_inv @ r_inv.T
se = np.sqrt(sigma2*np.diag(bread))
influence = r_inv @ (q.T * residual)
cov_hc0 = influence @ influence.T
se_hc0 = np.sqrt(np.diag(cov_hc0))
t = b/se
p_values = 2*stats.t.sf(np.abs(t), df)
critical = stats.t.ppf(.975, df)
ci = np.column_stack((b-critical*se, b+critical*se))
r2 = 1-sse/tss
r2_adj = 1-(1-r2)*(n-1)/df
f = ((tss-sse)/(p-1))/sigma2
f_p = stats.f.sf(f, p-1, df)
loglike = -n/2*(np.log(2*np.pi)+1+np.log(sse/n))
aic, bic = -2*loglike+2*p, -2*loglike+np.log(n)*p
skew = stats.skew(residual)
kurt = stats.kurtosis(residual, fisher=False)
jb = n/6*(skew**2+(kurt-3)**2/4)
jb_p = stats.chi2.sf(jb, 2)
omnibus, omnibus_p = stats.normaltest(residual)
dw = np.sum(np.diff(residual)**2)/sse

fit = sm.OLS(y, X).fit()
assert np.allclose(b, fit.params, rtol=1e-8, atol=1e-7)
assert np.allclose(se, fit.bse, rtol=1e-8)
assert np.allclose(se_hc0, fit.HC0_se, rtol=1e-8)
assert np.allclose(p_values, fit.pvalues, rtol=1e-8)
assert np.allclose(ci, fit.conf_int(), rtol=1e-8, atol=1e-7)
assert np.allclose([r2, r2_adj, f, f_p, loglike, aic, bic],
                   [fit.rsquared, fit.rsquared_adj, fit.fvalue, fit.f_pvalue, fit.llf, fit.aic, fit.bic], rtol=1e-8)
jb_ref = sm.stats.stattools.jarque_bera(residual)
assert np.allclose([jb, jb_p, skew, kurt], jb_ref)
assert np.allclose([omnibus, omnibus_p], sm.stats.stattools.omni_normtest(residual))
assert np.allclose(dw, sm.stats.stattools.durbin_watson(residual))
print('Desde QR: coeficiente, EE clásico, t, p, IC95, EE HC0')
for i, name in enumerate(names):
    print(f'{name:8s} {b[i]:.6g} {se[i]:.6g} {t[i]:.4g} {p_values[i]:.4g} '
          f'[{ci[i,0]:.6g},{ci[i,1]:.6g}] {se_hc0[i]:.6g}')
print('R², R² ajustado, F, p(F):', *(f'{v:.6g}' for v in (r2,r2_adj,f,f_p)))
print('logL gaussiana concentrada, AIC, BIC:', *(f'{v:.6g}' for v in (loglike,aic,bic)))
print('Omnibus, p, JB, p, asimetría, curtosis, DW:',
      *(f'{v:.6g}' for v in (omnibus,omnibus_p,jb,jb_p,skew,kurt,dw)))
print('Coeficientes, errores, p, intervalos, diagnóstico y resumen contrastados con statsmodels.')

# Las ecuaciones normales elevan al cuadrado el número de condición de X.
means = X[:,1:].mean(axis=0)
scales = X[:,1:].std(axis=0)
Z = np.column_stack((np.ones(n), (X[:,1:]-means)/scales))
qz, rz = np.linalg.qr(Z, mode='reduced')
bz = np.linalg.solve(rz, qz.T@y)
back = np.r_[bz[0]-np.sum(means*bz[1:]/scales), bz[1:]/scales]
assert np.allclose(X@b, X@back, rtol=1e-9, atol=1e-6)
try:
    normal_b = np.linalg.solve(X.T@X, X.T@y)
    print('Ecuaciones normales: máxima diferencia coeficiente frente a QR:', np.max(np.abs(normal_b-b)))
    print('Ecuaciones normales: SSE y SSE QR:', np.sum((y-X@normal_b)**2), sse)
except np.linalg.LinAlgError as error:
    print('Ecuaciones normales no resolubles numéricamente:', error)
print('Rango, condición original, condición centrada/escalada:', np.linalg.matrix_rank(X), np.linalg.cond(X), np.linalg.cond(Z))
print('El número de condición sin escalar depende de unidades; centrar y escalar separa ese efecto de la colinealidad.')
[ ]FWL and statsmodels summaryBrowser
"""Comprueba FWL y muestra el summary tras ejecutar la celda anterior."""
# Trata YEAR como regresor de interés y las seis columnas restantes como controles.
x1 = X[:,-1]
x2 = X[:,:-1]
q2, r2_control = np.linalg.qr(x2, mode='reduced')
res_x = x1-q2@(q2.T@x1)
res_y = y-q2@(q2.T@y)
b_fwl = (res_x@res_y)/(res_x@res_x)
assert np.allclose(b_fwl,b[-1],rtol=1e-8)
print('YEAR: coeficiente regresión múltiple y FWL:', b[-1], b_fwl)
print(fit.summary(xname=names, yname='TOTEMP'))
[ ]Curved CEF and projection in growing samplesBrowser
"""Proyección ponderada por la distribución y regresión saturada."""
import numpy as np
from scipy.integrate import quad

# X=2*sqrt(U), U uniforme en [0,1]: densidad f(x)=x/2 en [0,2].
# La CEF es m(x)=x² y la perturbación independiente tiene media cero.
density = lambda x: x / 2
moment = lambda k: quad(lambda x: x**k * density(x), 0, 2)[0]
ex, ex2, ex3 = (moment(k) for k in (1, 2, 3))
slope = (ex3 - ex*ex2) / (ex2 - ex**2)
intercept = ex2 - slope*ex
assert np.allclose([ex, ex2, ex3, intercept, slope], [4/3, 2, 16/5, -6/5, 12/5])
print('Proyección poblacional (integración): intercepto, pendiente =', intercept, slope)
print('Pendiente local m\'(x) en x=1:', 2., '; no tiene por qué coincidir con la proyección')

gen = np.random.default_rng(270101)
u = gen.uniform(size=20000)
x = 2*np.sqrt(u)
y_sim = x*x + gen.normal(scale=.5, size=len(x))
for n_sim in (200, 2000, 20000):
    X_sim = np.column_stack((np.ones(n_sim), x[:n_sim]))
    q_sim, r_sim = np.linalg.qr(X_sim, mode='reduced')
    beta = np.linalg.solve(r_sim, q_sim.T @ y_sim[:n_sim])
    print('n:', n_sim, 'intercepto y pendiente estimados:', beta)

# El ruido impide igualdad exacta entre medias de muestra y CEF poblacional.
categories = gen.choice(3, size=6000, p=[.2, .5, .3])
cef = np.array([0., 1., 4.])
observed = cef[categories] + gen.normal(scale=.5, size=len(categories))
D = np.eye(3)[categories]  # Una columna por categoría, sin constante adicional.
q_sim, r_sim = np.linalg.qr(D, mode='reduced')
coeff = np.linalg.solve(r_sim, q_sim.T @ observed)
sample_means = np.array([observed[categories == j].mean() for j in range(3)])
assert np.allclose(coeff, sample_means)
print('CEF poblacional por categoría:', cef)
print('Regresión saturada = medias empíricas:', coeff)
print('Diferencia respecto de la CEF poblacional:', coeff-cef)

Exercises

ProofProve Frisch-Waugh-Lovell
Prove: Let X=[X₁ X₂] have full column rank. Show the first-block coefficient in multiple regression equals that from regressing M₂y on M₂X₁, with M₂=I−X₂(X₂ᵀX₂)⁻¹X₂ᵀ.
0
Start with normal equations and eliminate the second block.

Step 1 of 3. What identity does M₂ satisfy for the control block?

ProofConsistency and normality of projection
Prove: Assume iid observations, positive definite Q=E[XXᵀ], finite second moments of X and Xu, and β the population projection. Prove the OLS limiting distribution.
0
Separate the second-moment matrix from the average of Xᵢuᵢ.

Step 1 of 3. What does the law of large numbers imply for the average of Xᵢuᵢ?

NumericA curve and its best line
If X is uniform on [0,3] and E[Y|X]=X², what is the slope of the population linear projection with intercept?
QuizSignificance, fit and causality
A regression has R²=0.02 and t=9 for a slope. What is the most defensible interpretation?
CodeOLS and robust covariance from QR
Implement ols(X,y) for a finite matrix with n>p and full column rank and a finite vector y of length n. Return coefficients, classical standard errors and HC0. Use QR and reject invalid inputs or rank.
import numpy as np

def ols(X,y):
  pass
Shift+Enter to run
[ ]Check the numerical exerciseBrowser
from scipy.integrate import quad

moment_ejercicio = lambda k: quad(lambda x: x**k/3, 0, 3)[0]
cov = moment_ejercicio(3)-moment_ejercicio(1)*moment_ejercicio(2)
variance = moment_ejercicio(2)-moment_ejercicio(1)**2
print('Covarianza, varianza y pendiente:', cov, variance, cov/variance)