*
*  SWAMY.PRG
*  Manual example 14.3
*
cal(panelobs=20) 1935
all 10//1954:1
open data grunfeld.dat
data(format=prn,org=cols)
compute nindiv=10

dec vect[symm] xxmats(nindiv)
dec vect[vect] betas(nindiv)
dec vect       sigmas(nindiv)
dec symm delta(3,3)
dec symm xxgls(3,3)
dec vect betagls(3)
dec integer k
*
*  First pass, run OLS regressions over each individual. Save %xx, %beta
*  and %seesq. Also accumulate the sum of the coefficients and their
*  outer product.
*
compute delta=%const(0.0)
compute betagls=%const(0.0)
do i=1,nindiv
   linreg(noprint) invest i//1 i//20
   # constant firmvalue cstock
   compute xxmats(i)=%xx
   compute betas(i)=%beta
   compute sigmas(i)=%seesq
   ewise delta(j,k)=delta(j,k)+%beta(j)*%beta(k)
   compute betagls=betagls+%beta
end do i
*
*  Estimate the covariance matrix of beta's
*
ewise delta(j,k)=1.0/(nindiv-1)*(delta(j,k)-(1.0/nindiv)*betagls(j)*betagls(k))
*
*  Second pass. Compute the GLS covariance matrix. While we're at it,
*  replace xxmats with the precision.
*
compute xxgls=%const(0.0)
do i=1,nindiv
   compute xxmats(i)=inv(delta+sigmas(i)*xxmats(i))
   compute xxgls=xxgls+xxmats(i)
end do i
compute xxgls=inv(xxgls)
*
*  Final pass. Compute the grand coefficient matrix
*
compute betagls=%const(0.0)
do i=1,nindiv
   compute betagls=betagls+xxgls*xxmats(i)*betas(i)
end do i
linreg(create,coeffs=betagls,covmat=xxgls,noscale) invest
# constant firmvalue cstock

