*
*  Swamy computes a GLS matrix weighted estimator for a panel data set. The procedure MeanGroup.src
*  does a simple weighted average of the coefficient vectors.
*
*  Syntax:
*     @Swamy( options )  depvar start end
*     # list of regressors
*
*     Parameters:
*       depvar      dependent variable
*       start end   range to estimate
*
*     Note: This procedure uses start and end only to determine the range of individuals
*     to use in the estimation. It will use all valid observations for each individual
*     within that range. Use the SMPL option if you want to skip observations for reasons
*     other than lack of data.
*
*     Options:
*       define=equation to define [none]
*       smpl  =SMPL series [none]
*
*  Revision schedule
*    10/02 Converted by procedure by Estima
*
procedure Swamy depvar start end
type series depvar
type integer start end
*
option equation *define
option series   smpl
*
local vect[integer] reglist
local integer startl endl
local integer i j k
local integer nindiv ncoeff ntime firsti lasti
local vect[symm] xxmats
local vect[vect] betas
local vector sigmas
local symm xxgls delta
local vect betagls
local equation paneleqn
*
enter(varying) reglist
*
inquire(regressorlist) startl>>start endl>>end
# depvar reglist
equation paneleqn depvar
# reglist
*
compute ncoeff=%eqnsize(paneleqn)
compute firsti=%indiv(startl),lasti=%indiv(endl)
compute nindiv=%indiv(endl)-%indiv(startl)+1
compute ntime =2//1-1//1
dim xxmats(nindiv) betas(nindiv) sigmas(nindiv)
dim xxgls(ncoeff,ncoeff) betagls(ncoeff) delta(ncoeff,ncoeff)
*
*  First pass, run OLS regressions over each individual. Save %xx, %beta
*  and %seesq.
*
compute delta=%const(0.0)
compute betagls=%const(0.0)
do i=1,nindiv
   linreg(smpl=smpl,noprint,equation=paneleqn) * (firsti+i-1)//1 (firsti+i-1)//ntime
   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,equation=paneleqn,define=define,coeffs=betagls,covmat=xxgls,noscale) *
end

