Module contents
Lesson 3 of 28Core 85 min

Generalized least squares: GLS, WLS and FGLS

Develop GLS, WLS, feasible GLS, AR(1) corrections and seemingly unrelated regressions, and weigh efficiency from modeling covariance against robust inference.

After this lesson you can

  • Prove Aitken's theorem by reducing GLS to OLS on a whitened model.
  • Implement WLS and FGLS with parametric variance and compare efficiency with OLS plus HC3.
  • Implement Cochrane-Orcutt and Prais-Winsten and explain the role of strict exogeneity.
  • Estimate SUR and show coefficient equivalence to OLS when equations share regressors.
  • Choose between modeling variance with GLS and robustifying OLS inference.

Before you start

How much weight does each mean get?

Compare mean response times of teams with very different sample sizes. If each mean comes from independent observations with the same individual variance, a large group’s mean has lower variance. Treating all means equally can waste information. But if members of a team share shocks, variance of the mean need not remain inversely proportional to size.

Modeling covariance can gain efficiency when its structure is correct. That promise depends on error assumptions and target: weighting groups can also change the population represented by the coefficient when relationships differ across groups.

Aitken and the change in geometry

Let y=Xβ+uy=X\beta+u, with full-column-rank XX, E[u∣X]=0E[u\mid X]=0 and Var⁡(u∣X)=σ2Ω\operatorname{Var}(u\mid X)=\sigma^2\Omega, where Ω\Omega is known, symmetric and positive definite. Generalized least squares is

β^G=(X⊤Ω−1X)−1X⊤Ω−1y.\hat\beta_G=(X^\top\Omega^{-1}X)^{-1}X^\top\Omega^{-1}y.

If Ω=LL⊤\Omega=LL^\top is a Cholesky factorization, C=L−1C=L^{-1} satisfies CΩC⊤=IC\Omega C^\top=I. Transformed model Cy=CXβ+CuCy=CX\beta+Cu has spherical errors and OLS on it gives the preceding formula. Symmetric root Ω−1/2\Omega^{-1/2} is another valid whitening: it need not equal L−1L^{-1}, but both transformations give the same estimator.

To prove optimality, write any conditionally unbiased linear estimator as AyAy with AX=IAX=I. Let AG=(X⊤Ω−1X)−1X⊤Ω−1A_G=(X^\top\Omega^{-1}X)^{-1}X^\top\Omega^{-1} and D=A−AGD=A-A_G. Then DX=0DX=0 and cross terms vanish:

Var⁡(Ay∣X)−Var⁡(AGy∣X)=σ2DΩD⊤⪰0.\operatorname{Var}(Ay\mid X)-\operatorname{Var}(A_Gy\mid X) =\sigma^2D\Omega D^\top\succeq0.

This is the Loewner order of Aitken’s theorem: the difference is positive semidefinite; it does not mean every GLS realization is closer to β\beta. The result compares unbiased linear estimators with correctly specified covariance; it claims neither normality nor efficiency against every biased or nonlinear estimator.

Conditional GLS covariance is σ2(X⊤Ω−1X)−1\sigma^2(X^\top\Omega^{-1}X)^{-1}. The figure uses two observations and one design column: its axes describe errors across observations, not two explanatory variables. Changing ellipse orientation or length changes the metric and can change the fitted slope. The same covariance algebra appears in Gaussian processes, although the chosen joint distribution also matters there.

Prediction Xβ^GX\hat\beta_G is an idempotent projection, generally oblique for the Euclidean product. Its residual satisfies X⊤Ω−1(y−Xβ^G)=0X^\top\Omega^{-1}(y-X\hat\beta_G)=0: it is orthogonal in the weighted product. Spherical covariance recovers ordinary geometry.

InteractiveWhitening changes geometry

The ellipse represents joint error covariance for two observations. Its semiaxes are principal standard deviations, not a confidence interval. Grey points control the original covariance; the colored ellipse shows the transformation in progress.

Error covarianceab
Original spaceyfitobservation 1obs. 2
Transformed spaceyfitobservation 1obs. 2
  • Observation y
  • Line and fit
  • Residual

The example fixes x = (1, 0.6) and y = (1.4, 2): each coordinate is an observation and the line contains vectors βx. The transformed projection is perpendicular to its residual; back in original space the projection is usually oblique. With spherical covariance, OLS and GLS coincide.

With Ω = R diag(a²,b²) Rᵀ, use T(t) = R diag(1−t+t/a, 1−t+t/b) Rᵀ. At t = 1, T = Ω⁻¹ᐟ² and TΩTᵀ = I. The displayed product is (Tx)ᵀ(Ty−βTx); at the last step it equals xᵀΩ⁻¹(y−βx). Cholesky whitening can rotate the result but gives the same GLS estimate.

This construction is geometric, not an empirical sample or a coverage test. GLS efficiency requires Ω to describe covariance correctly and the model assumptions to hold.

2.00
0.65
34°
0% whitened
OLS slope1.912
Current slope1.912
Final GLS slope1.539
Product in current metric≈ 0
Original Euclidean product0.000
Deform the covariance of two errors and observe projection before and after whitening.

Precision weights and estimand

In WLS, Ω\Omega is diagonal and minimizing (y−Xb)⊤Ω−1(y−Xb)(y-Xb)^\top\Omega^{-1}(y-Xb) weights each squared residual by inverse variance. Units matter: precision weight is proportional to 1/σi21/\sigma_i^2, not 1/σi1/\sigma_i. If an observation is a mean of mim_i iid data with common variance σ2\sigma^2, its variance is σ2/mi\sigma^2/m_i and weight proportional to mim_i is justified.

With within-group correlation that rule can fail. With heterogeneous effects, weighting by size also changes the group average approximated by regression. Specify whether you care about a team or individual mean before choosing weights.

For example, if a group contains m≥2m\ge2 observations with individual variance σ2\sigma^2 and common correlation ρ\rho, its mean variance is σ2[1+(m−1)ρ]/m\sigma^2[1+(m-1)\rho]/m. The equicorrelation matrix requires −1/(m−1)≤ρ≤1-1/(m-1)\le\rho\le1 and is singular at endpoints. With ρ>0\rho>0, multiplying the same group’s sample does not make the shared component disappear. If means of different groups are uncorrelated with positive variances, precision weight is inversely proportional to that whole expression; with between-group correlation full covariance is needed, not just its diagonal.

Even with positive weights, WLS and OLS need not share the same projection if the CEF is nonlinear. Retaining the same β\beta requires conditions such as E[w(X)Xu]=0E[w(X)X u]=0; a correctly linear CEF with conditional exogeneity suffices for suitable weights depending on XX. A counterexample: X∼N(0,1)X\sim N(0,1), Y=X2Y=X^2 and w(X)=eaXw(X)=e^{aX}. With intercept, OLS slope is zero by symmetry; under the distribution tilted by ww, X∼N(a,1)X\sim N(a,1) and weighted slope is 2a2a. Weights changed the question even though both calculations are consistent for their own projections.

Estimating variance

Feasible GLS replaces Ω\Omega with an estimate. One heteroskedasticity strategy fits OLS, models log⁡σi2\log\sigma_i^2 with covariates and refits using estimated inverse weights. This is a proposed model, not an automatic correction: if variance is misspecified or the sample small, the feasible estimator can lose precision.

If ui=σiεiu_i=\sigma_i\varepsilon_i and εi\varepsilon_i is standard normal, regressing log⁡ui2\log u_i^2 on the model of log⁡σi2\log\sigma_i^2 shifts the intercept by E[log⁡χ12]=−γ−log⁡2E[\log\chi_1^2]=-\gamma-\log2. A common multiplicative factor does not change WLS coefficients, but matters when interpreting variance scale. Zero residuals require an explicit truncation policy whose influence should be studied.

The lab first estimates the mean and uses its residuals, not true errors. That adds uncertainty and makes the auxiliary regression different from observing log⁡ui2\log u_i^2. In the experiment oracle WLS knows generator variance; it is an inaccessible reference when that variance is unknown. The figure distinguishes it from FGLS and the fit with deliberately opposite weights.

When weights converge to an incorrect positive function, naive variance based on that model can be miscalibrated even if the coefficient retains its target. For independent observations, a sandwich for the weighted equation can use scores wixiu^iw_i x_i\hat u_i; temporal or clustered dependence also requires adapting the meat. OLS with HC3 or HAC may be a more robust reference if covariance structure is uncertain.

InteractiveEfficiency and wrong weights

Simulate 1800 paired samples: X uniform on [−1,1], Y=1+X+u and u=exp(γX/2)ε, with independent normal ε. The true population slope is 1. Curves connect histogram-bin centers and share a scale.

  • OLS
  • Correct WLS
  • Assumed WLS
  • FGLS

Estimates outside the displayed interval [−0.5, 2.5], in legend order: 0, 0, 1, 0. Density retains all 1800 samples in its denominator.

OLS: mean 1.008, MSE 0.0641; conventional coverage 92.4 %, HC3 94.8 %.
Correct WLS: mean 1.007, MSE 0.0368; conventional coverage 95.7 %, HC3 96.1 %.
Assumed WLS: mean 1.005, MSE 0.1984; conventional coverage 87.8 %, HC3 93.3 %.
FGLS: mean 1.006, MSE 0.0390; conventional coverage 95.3 %, HC3 96.2 %.

Monte Carlo uncertainty in each coverage is at most approximately ±2.3 percentage points at 95%. Intervals use the normal quantile; finite-sample HC3 coverage is not guaranteed either and depends on sample size.

Correct WLS uses weights exp(−γX); assumed WLS uses exp(−aX). FGLS estimates a by regressing log(û²) on a constant and X from OLS; residual squares below 10⁻¹² are floored there, and the estimated exponent is clipped to [−2.5, 2.5]. Conventional error assumes variance proportional to inverse weights; HC3 uses the weighted sandwich. FGLS readings approximate estimated weights as given.

With a correct linear mean and exogeneity, these positive deterministic weights retain the same estimand; FGLS also requires first-stage regularity. Incorrect weights can raise MSE and conventional coverage can fail, but no finite comparison has a guaranteed winner.

If the question changes and the true mean is m(x)=x², projection slope depends on weighting: OLS 0.000, correct weights −0.406, and assumed weights 0.406. These are numerically integrated population projections for uniform X, not results from the preceding linear simulations.

Observations per sample
1.5
-1.5
1
Linear estimand of all1
Mean γ estimated by FGLS1.46
Clipped FGLS fits14 of 1800
Compare estimator distributions and coverage on paired samples.

AR(1) errors: keep or discard the first observation

Suppose ut=ρut−1+εtu_t=\rho u_{t-1}+\varepsilon_t, ∣ρ∣<1|\rho|<1, spherical innovations and a stationary initial condition. For t≥2t\ge2, quasi-differencing gives

yt−ρyt−1=(xt−ρxt−1)⊤β+εt.y_t-\rho y_{t-1}=(x_t-\rho x_{t-1})^\top\beta+\varepsilon_t.

Cochrane-Orcutt discards the first transformed observation. Prais-Winsten retains it by multiplying y1y_1 and x1x_1 by 1−ρ2\sqrt{1-\rho^2} under the stationary-variance convention. If ρ\rho is unknown, transformed regression and a residual-based update can alternate. Document initialization, convergence, constraint ∣ρ∣<1|\rho|<1 and first-observation treatment; iteration does not guarantee a unique optimum.

Strict exogeneity is a common sufficient condition for conditional interpretation of these transformations. If yt−1y_{t-1} is a regressor and AR errors are correlated, the lagged term is often correlated with current error and naive fitting can be inconsistent. Not every model with a lagged dependent variable fails: with iid innovations and suitable assumptions, an autoregression can be consistently estimated.

InteractiveIterating Cochrane-Orcutt

Each point is computed on the same series. Dashed lines are the generator’s true parameters; convergence only means the iterations stop moving.

  • estimated and true ρ
  • estimated and true β

Reproducible model: uₜ = ρuₜ₋₁ + εₜ, yₜ = 0.3 + 0.35xₜ + uₜ, with independent normal innovations of variance 1. Discard 300 initial steps and retain 3000 observations. In exogenous mode xₜ is independent normal; in dynamic mode xₜ = yₜ₋₁.

Starting from OLS, each iteration estimates ρ by Σeₜeₜ₋₁/Σeₜ₋₁² and regresses yₜ−ρyₜ₋₁ on constant 1−ρ and xₜ−ρxₜ₋₁. The first observation is discarded: this is Cochrane–Orcutt, not Prais–Winsten. To keep the transformation stable ρ is limited to [−0.98, 0.98]; the limit was not reached in this series.

With lagged y the regressor shares history with uₜ: initial regression lacks strict exogeneity. In this simple AR(1) model the reduced form can swap roots β and ρ; the algorithm can stabilize near the wrong root. Strict exogeneity is a common sufficient condition, not necessary for all dynamic regressions. One series or fixed point alone does not prove consistency.

Regressor
0.75
Initial OLS
Iteration0
Estimated ρNot yet estimated
Estimated β0.386
Change in βInitial
True ρ0.75
True β0.35
Seed270303
Follow estimates of ρ and coefficients in a simulated exogenous or dynamic series.

For given ρ\rho, Prais-Winsten is checked against GLS with full AR(1) covariance. statsmodels GLSAR removes initial observations when whitening; it is not the same transformation as Prais-Winsten and exact equality should not be required.

The first-observation transformation follows from the stationary distribution: if innovation variance is σε2\sigma_\varepsilon^2, that of u1u_1 is σε2/(1−ρ2)\sigma_\varepsilon^2/(1-\rho^2), and multiplying by 1−ρ2\sqrt{1-\rho^2} matches its variance to subsequent innovations. If that initial condition fails, the first row must change. Autoregressive models permit study of structures more general than AR(1), at the cost of estimating more covariance components.

A system of seemingly unrelated regressions

In SUR, each equation has its own regressors, but errors can be correlated at the same date. If KK equations share TT aligned times and cross-equation covariance is Σ\Sigma, with serial independence and constant contemporaneous covariance, covariance stacked by equation is Σ⊗IT\Sigma\otimes I_T. GLS exploits contemporaneous correlation; FGLS estimates Σ\Sigma from initial residuals.

If all regressor blocks equal the same matrix XX, SUR equals equation-by-equation OLS. The GLS normal matrix is Σ−1⊗X⊤X\Sigma^{-1}\otimes X^\top X, its inverse is Σ⊗(X⊤X)−1\Sigma\otimes(X^\top X)^{-1} and Σ\Sigma factors cancel. If Σ\Sigma is diagonal, equations also decouple even if regressors differ. Otherwise, a possible efficiency gain depends on covariance and regressor overlap; it is not guaranteed for a finite feasible estimator.

The contemporaneous-independence LM test is commonly expressed as T∑i<jr^ij2T\sum_{i<j}\hat r_{ij}^2 and uses an asymptotic reference under its assumptions. It does not demonstrate absence of temporal dependence. Zellner’s method assumes corresponding observations are aligned; in Grunfeld match years before stacking firms and recognize these are observational data.

A practical SUR review compares three distinct objects: equation-level OLS predictions, SUR coefficients and uncertainty matrices associated with the chosen model. A difference in standard errors alone does not prove the system is better specified. In the lab, cross-equation covariance is estimated from the same data and the time dimension is small, so displayed errors should be read as model-dependent Σ⊗IT\Sigma\otimes I_T.

Labs: from transformation to system

First check Cholesky GLS and WLS against statsmodels; then estimate exponential weights from residuals. The simulation’s CEF is linear: in this case the considered weights share an estimand. Comparisons are paired and variance fitting uses the same sample; results are not a guarantee for other models.

[ ]GLS and FGLS from CholeskyBrowser
"""GLS por Cholesky, WLS, FGLS de varianza exponencial y comparación simulada."""
import numpy as np
import statsmodels.api as sm
from scipy.special import digamma

assert np.allclose(digamma(.5)+np.log(2),-np.euler_gamma-np.log(2))
print('Desplazamiento E[log χ²(1)]:',digamma(.5)+np.log(2))

def fit_weighted(y, X, weights):
    """QR de sqrt(w)X; devuelve beta y covarianzas modelada, HC0 y HC3."""
    y=np.asarray(y,float); X=np.asarray(X,float); weights=np.asarray(weights,float)
    n,p=X.shape
    if len(y)!=n or weights.shape!=(n,) or n<=p or np.any(weights<=0) or not np.isfinite(weights).all():
        raise ValueError('Pesos, datos o dimensiones inválidos')
    if np.linalg.matrix_rank(X)!=p: raise ValueError('Diseño sin rango completo')
    root=np.sqrt(weights)
    Z=X*root[:,None]; z=y*root
    Q,R=np.linalg.qr(Z,mode='reduced')
    beta=np.linalg.solve(R,Q.T@z)
    error=y-X@beta
    invR=np.linalg.solve(R,np.eye(p)); [email protected]
    classic=bread*np.sum(weights*error**2)/(n-p)
    score=X*(weights*error)[:,None]
    robust=bread@(score.T@score)@bread
    leverage=np.sum(Q*Q,axis=1)
    if np.any(leverage>=1-1e-12): raise ValueError('Apalancamiento demasiado alto')
    adjusted=score/(1-leverage)[:,None]
    hc3=bread@(adjusted.T@adjusted)@bread
    return beta,classic,robust,hc3,error

def gls_cholesky(y,X,omega):
    """omega=LLᵀ, blanqueo mediante L⁻¹, sin formar Ω⁻¹."""
    L=np.linalg.cholesky(omega)
    Xw=np.linalg.solve(L,X); yw=np.linalg.solve(L,y)
    Q,R=np.linalg.qr(Xw,mode='reduced')
    return np.linalg.solve(R,Q.T@yw)

rng=np.random.default_rng(270301)
n=120
x=rng.uniform(-1,1,n)
X=np.column_stack((np.ones(n),x))
variance=np.exp(1.5*x)
y=1+2*x+np.sqrt(variance)*rng.normal(size=n)
omega=np.diag(variance)
b_gls=gls_cholesky(y,X,omega)
b_wls,c_wls,c_robust,c_hc3,resid=fit_weighted(y,X,1/variance)
assert np.allclose(b_gls,sm.GLS(y,X,sigma=omega).fit().params,rtol=1e-10,atol=1e-10)
reference=sm.WLS(y,X,weights=1/variance).fit()
assert np.allclose(b_wls,b_gls) and np.allclose(b_wls,reference.params)
assert np.allclose(c_wls,reference.cov_params())
assert np.allclose(c_robust,reference.get_robustcov_results(cov_type='HC0').cov_params())
assert np.allclose(c_hc3,reference.get_robustcov_results(cov_type='HC3').cov_params())
print('GLS, WLS y statsmodels, coeficientes:',b_gls,b_wls,reference.params)
print('EE WLS modelo / HC0 transformado:',np.sqrt(np.diag(c_wls)),np.sqrt(np.diag(c_robust)))

# El modelo condicional es lineal; la media OLS y las medias ponderadas tienen
# el mismo parámetro. La varianza verdadera solo se usa como oráculo.
REPS=400
errors=[]
cover=[]
for _ in range(REPS):
    x=rng.uniform(-1,1,n)
    X=np.column_stack((np.ones(n),x))
    y=1+2*x+np.exp(.75*x)*rng.normal(size=n)
    b0,c0,h0,h3,e0=fit_weighted(y,X,np.ones(n))
    be,ce,he,he3,_=fit_weighted(y,X,np.exp(-1.5*x))
    bw,cw,hw,hw3,_=fit_weighted(y,X,np.exp(1.5*x))
    # E[log(u²)|x]=log σ²(x)+E[log ε²]; la constante común cancela en WLS.
    # El suelo limita log(0), y puede introducir sesgo en muestras finitas.
    logvariance=np.linalg.lstsq(X,np.log(np.maximum(e0**2,1e-12)),rcond=None)[0]
    bf,cf,hf,hf3,_=fit_weighted(y,X,np.exp(-X@logvariance))
    estimates=np.array([b0[1],be[1],bw[1],bf[1]])
    errors.append((estimates-2)**2)
    z=1.959963984540054
    cover.append([abs(b0[1]-2)<=z*np.sqrt(h3[1,1]),abs(bw[1]-2)<=z*np.sqrt(cw[1,1]),abs(bw[1]-2)<=z*np.sqrt(hw3[1,1])])
errors=np.asarray(errors); cover=np.asarray(cover)
print('Réplica:',REPS,'ECM pendiente OLS / WLS oráculo / WLS inverso / FGLS:',errors.mean(axis=0))
print('Cobertura normal: OLS HC3 / WLS inverso modelo / WLS inverso HC3:',cover.mean(axis=0),
      'EE Monte Carlo:',np.sqrt(cover.mean(axis=0)*(1-cover.mean(axis=0))/REPS))
print('Comparaciones emparejadas; la eficiencia estimada es de esta simulación, no una garantía finita.')

With fixed ρ, compare Prais-Winsten with full GLS and Cochrane-Orcutt with GLSAR; then run the iteration. The next simulation cell reuses those functions: run them in order.

[ ]Prais-Winsten and Cochrane-OrcuttBrowser
"""Prais-Winsten y Cochrane-Orcutt, mismos datos y convenciones explícitas."""
import numpy as np
import statsmodels.api as sm

def pw_at_rho(y,X,rho):
    if not -1<rho<1: raise ValueError('Prais-Winsten requiere |rho|<1')
    y_t=np.r_[np.sqrt(1-rho*rho)*y[0],y[1:]-rho*y[:-1]]
    X_t=np.vstack((np.sqrt(1-rho*rho)*X[0],X[1:]-rho*X[:-1]))
    return np.linalg.lstsq(X_t,y_t,rcond=None)[0]

def co_at_rho(y,X,rho):
    return np.linalg.lstsq(X[1:]-rho*X[:-1],y[1:]-rho*y[:-1],rcond=None)[0]

def prais_winsten(y,X,tol=1e-8,maxiter=200):
    beta=np.linalg.lstsq(X,y,rcond=None)[0]
    rho=0.
    for iteration in range(1,maxiter+1):
        resid=y-X@beta
        denom=resid[:-1]@resid[:-1]
        if denom<=1e-14: raise ValueError('No se puede estimar rho')
        newrho=(resid[1:]@resid[:-1])/denom
        if abs(newrho)>=1: raise ValueError('Estimación de rho fuera de (−1,1)')
        updated=pw_at_rho(y,X,newrho)
        if abs(newrho-rho)<tol and np.linalg.norm(updated-beta)<tol:
            return updated,float(newrho),iteration,True
        beta,rho=updated,newrho
    return beta,float(rho),maxiter,False

gen=np.random.default_rng(270302)
n=140; rho_true=.65
x=gen.normal(size=n)
error=np.empty(n); error[0]=gen.normal()
for i in range(1,n):
    error[i]=rho_true*error[i-1]+np.sqrt(1-rho_true**2)*gen.normal()
X=np.column_stack((np.ones(n),x)); y=1+1.5*x+error
omega=rho_true**np.abs(np.arange(n)[:,None]-np.arange(n)[None,:])
pw=pw_at_rho(y,X,rho_true)
ref=sm.GLS(y,X,sigma=omega).fit().params
co=co_at_rho(y,X,rho_true)
glsar=sm.GLSAR(y,X,rho=[rho_true]).fit().params
assert np.allclose(pw,ref,atol=1e-10) and np.allclose(co,glsar,atol=1e-10)
print('ρ fijado, PW y GLS con covarianza completa:',pw,ref)
print('ρ fijado, Cochrane-Orcutt y GLSAR (primera observación excluida):',co,glsar)
bp,rhop,niter,converged=prais_winsten(y,X)
assert converged
other=sm.GLSAR(y,X,rho=1); fitted=other.iterative_fit(maxiter=200,rtol=1e-8)
print('Prais-Winsten iterado: coeficientes, ρ, pasos, convergió:',bp,rhop,niter,converged)
print('GLSAR iterado: coeficientes, ρ:',fitted.params,other.rho)
print('Las diferencias reflejan primera observación y actualización: no se presupone igualdad de las iteraciones.')
print('ρ fijado blanquea solo bajo el modelo AR(1) estacionario; la interpretación requiere exogeneidad del diseño.')
[ ]Squared error under AR(1) errorsBrowser
"""ECM emparejado para OLS, PW oráculo y PW iterado con regresor exógeno."""
gen_eff=np.random.default_rng(270303)
replicas=240
size=80
rho_data=.65
squared=[]
failed=0
for _ in range(replicas):
    xe=gen_eff.normal(size=size)
    ue=np.empty(size); ue[0]=gen_eff.normal()
    for j in range(1,size):
        ue[j]=rho_data*ue[j-1]+np.sqrt(1-rho_data**2)*gen_eff.normal()
    Xe=np.column_stack((np.ones(size),xe))
    ye=1+1.5*xe+ue
    bol=np.linalg.lstsq(Xe,ye,rcond=None)[0]
    b_oracle=pw_at_rho(ye,Xe,rho_data)
    try:
        b_iter,_,_,converged=prais_winsten(ye,Xe)
    except ValueError:
        converged=False
    if not converged:
        failed+=1
        continue
    squared.append((np.array([bol[1],b_oracle[1],b_iter[1]])-1.5)**2)
squared=np.asarray(squared)
print('ECM de pendiente OLS, PW con ρ verdadero y PW iterado:',squared.mean(axis=0))
print('EE Monte Carlo de cada ECM:',squared.std(axis=0,ddof=1)/np.sqrt(len(squared)))
print('Réplicas completas / totales; fallidas:',len(squared),replicas,failed)
print('Se usan las mismas réplicas y el mismo subconjunto; resultados condicionados a convergencia.')

In Grunfeld, years of three firms are aligned and contemporaneous covariance is estimated using OLS residuals. Standard errors depend on the time model and do not imply causality.

[ ]Feasible SUR in GrunfeldBrowser
"""SUR factible de tres empresas de Grunfeld y propiedades verificables."""
import numpy as np
import statsmodels.api as sm
from scipy.stats import chi2

data=sm.datasets.grunfeld.load_pandas().data
firms=['General Motors','General Electric','US Steel']
frames=[data.loc[data.firm==name].sort_values('year').reset_index(drop=True) for name in firms]
years=frames[0].year.to_numpy()
assert all(np.array_equal(frame.year.to_numpy(),years) for frame in frames)
T=len(years); K=len(firms)
# Cambiar unidades afecta coeficientes numéricos, no al ajuste.
X=[np.column_stack([np.ones(T),frame.value.to_numpy()/1000,frame.capital.to_numpy()/1000]) for frame in frames]
y=[frame.invest.to_numpy()/1000 for frame in frames]
betas_ols=[np.linalg.lstsq(X[i],y[i],rcond=None)[0] for i in range(K)]
resid=np.column_stack([y[i]-X[i]@betas_ols[i] for i in range(K)])
sigma=resid.T@resid/T
if np.min(np.linalg.eigvalsh(sigma))<=0: raise ValueError('Covarianza entre ecuaciones singular')

def sur(designs,outcomes,covariance):
    """GLS del sistema con Ω=Σ⊗I_T, ordenado por ecuaciones."""
    eqs=len(designs); n=len(outcomes[0])
    if any(len(v)!=n for v in outcomes): raise ValueError('Panel no balanceado')
    rows=eqs*n; p_total=sum(x.shape[1] for x in designs)
    stacked=np.zeros((rows,p_total))
    pos=0
    for i,x in enumerate(designs):
        p=x.shape[1]; stacked[i*n:(i+1)*n,pos:pos+p]=x; pos+=p
    vector=np.concatenate(outcomes)
    omega=np.kron(covariance,np.eye(n))
    L=np.linalg.cholesky(omega)
    weighted=np.linalg.solve(L,stacked); transformed=np.linalg.solve(L,vector)
    Q,R=np.linalg.qr(weighted,mode='reduced')
    beta=np.linalg.solve(R,Q.T@transformed)
    invR=np.linalg.solve(R,np.eye(p_total))
    return beta,[email protected]

bsur,covsur=sur(X,y,sigma)
bd,cd=sur(X,y,np.diag(np.diag(sigma)))
stacked_ols=np.concatenate(betas_ols)
assert np.allclose(bd,stacked_ols,atol=1e-9,rtol=1e-9)
# Con mismo diseño en cada ecuación, GLS equivale a OLS para Σ no diagonal.
shared=[X[0]]*K
common_ols=np.concatenate([np.linalg.lstsq(X[0],yi,rcond=None)[0] for yi in y])
common_sur,_=sur(shared,y,sigma)
assert np.allclose(common_sur,common_ols,atol=1e-9,rtol=1e-9)
print('Grunfeld:',firms,'años:',int(years[0]),int(years[-1]),'observaciones por ecuación:',T)
print('Σ de residuos OLS dividida por T:\n',sigma)
for i,name in enumerate(firms):
    se_ols=np.sqrt(np.diag(cd)[3*i:3*i+3])
    se_sur=np.sqrt(np.diag(covsur)[3*i:3*i+3])
    print(name,'coef. OLS:',betas_ols[i],'coef. FGLS SUR:',bsur[3*i:3*i+3])
    print('EE modelo diagonal y SUR, escala Σ/T:',se_ols,se_sur)
print('Máx. diferencia OLS/SUR con Σ diagonal:',np.max(np.abs(bd-stacked_ols)))
print('Máx. diferencia OLS/SUR con regresores comunes:',np.max(np.abs(common_sur-common_ols)))

# LM de independencia contemporánea bajo hipótesis del contraste clásico.
corr=np.corrcoef(resid,rowvar=False)
lm=T*sum(corr[i,j]**2 for i in range(K) for j in range(i+1,K))
df=K*(K-1)//2
print('BP entre ecuaciones: LM, gl, p:',lm,df,chi2.sf(lm,df))
print('Referencia χ²: hipótesis iid temporal apropiadas; no prueba ausencia de dependencia temporal.')
print('Datos observacionales, T pequeño y covarianza estimada: EE modelados no prueban eficiencia ni causalidad.')

Exercises

ProofProve Aitken optimality
Prove: Let y=Xβ+u, with full-rank X, E[u|X]=0 and Var(u|X)=σ²Ω, where Ω is known positive definite. Prove GLS optimality among conditionally unbiased linear estimators.
0
Write A=A_G+D, where A_G is the GLS matrix.

Step 1 of 3. What follows from AX=A_GX=I?

ProofWhen SUR equals OLS
Prove: There are K equations with the same full-rank X and error covariance Σ⊗Iₜ, with Σ positive definite. Show system GLS equals equation-by-equation OLS.
0
Stack by equation and use Kronecker-product identities.

Step 1 of 2. What is the system normal matrix?

NumericWeight independent means
Three independent means come from 4, 16 and 64 iid individual observations with common variance. What normalized WLS weight does the mean of the size-16 group receive?
QuizEfficiency versus robustness
When is it best justified to expect FGLS to gain over OLS with HC3?
CodeIterated Prais-Winsten
Implement prais_winsten(y,X,tol=1e-8,maxiter=200). Start with OLS and ρ=0; estimate ρ as Σûₜûₜ₋₁/Σûₜ₋₁², transform the first observation by √(1−ρ²) and the rest by quasi-differences. Stop when changes in ρ and β are below tol. Return β, ρ, iterations and convergence; reject invalid data, insufficient rank or |ρ|≥1.
import numpy as np

def prais_winsten(y,X,tol=1e-8,maxiter=200):
  pass
Shift+Enter to run
[ ]Check the exercise weightsBrowser
import numpy as np
sizes=np.array([4.,16.,64.])
weights=sizes/sizes.sum()
print('Pesos de precisión normalizados:',weights,'suma:',weights.sum())
# Compara la varianza teórica de una media equicorrelacionada con la suma matricial.
m,rho=10,.2
cov=np.full((m,m),rho)
np.fill_diagonal(cov,1.)
variance_matrix=np.ones(m)@[email protected](m)/m**2
variance_formula=(1+(m-1)*rho)/m
assert np.allclose(variance_matrix,variance_formula)
print('Varianza de media equicorrelacionada: matriz y fórmula:',variance_matrix,variance_formula)