########################################################################################################################################

#CAPM: GMM estimation


#3 different codes for estimating the parameters of the standard CAPM

#Code written by Ricardo Buscariolli - RStudio Version 1.1.463 - 2019

#I would like to thank Pierre Chausse for suggestions (and for developing the GMM package!).


########################################################################################################################################

#LIBRARIES AND DATA (FROM THE GMM PACKAGE BY PIERRE CHAUSSE)


library(gmm)

library(devtools)

library(broom)


#Getting Data and creating matrix


data(Finance)

r <- Finance[1:300, 1:10]

rm <- Finance[1:300, "rm"]

rf <- Finance[1:300, "rf"]

z <- as.matrix(r-rf)

t <- nrow(z)

zm <- rm-rf

vz<-c(z)

final<-length(vz)

nstocks<-ncol(z)

nper<-nrow(z)

z <- as.matrix(r-rf)

t <- nrow(z)

zm <- rm-rf

h <- matrix(zm, t, 1)


########################################################################################################################################

#1. BENCHMARK: LINEAR MODEL (Chaussé, Pierre. "Computing generalized method of moments and generalized empirical likelihood with R." #Journal of Statistical Software 34.11 (2010): 1-35.


reslin <- gmm(z ~ zm, x = h)

summary(reslin)



########################################################################################################################################

#2. WRITING THE MOMENT CONDITIONS


h<-cbind(zm,z)


g2 <- function(tet, x)

{

nstocks<-ncol(x)-1

e <- numeric()

for(i in 1:nstocks){

m <- nstocks+i

r0<-x[,i+1]-tet[i]-tet[m]*x[,1]

r1<-(x[,i+1]-tet[i]-tet[m]*x[,1])*x[,1]

e <- cbind(e,r0,r1)

}

return(e)

}


res<-gmm(g2,h,c(rep(1,nstocks),rep(0,nstocks)),

method="BFGS", control=list(maxit=3000))


summary(res)


#Comparing of the results: mean difference of the values of the estimated coefficients is very low


mean(abs(coef(res)-coef(reslin)))



########################################################################################################################################

#3. WRITING BETAS


g3 <- function(tet, x)

{

nstocks<-ncol(x)-1

n1<-2*nstocks+1

n2<-2*nstocks+2

e <- numeric()

rme <- (x[,1]-tet[n1])

sigma2 <- ((x[,1] - tet[n1])^2)

for(i in 1:nstocks){

m<-nstocks+i

ri<-x[,i+1]-tet[i]

e <- cbind(e,ri)

}


for(i in 1:nstocks){

m<-nstocks+i

beta<-tet[m]*sigma2-(x[,i+1]-tet[i])*(x[,1]-tet[n1])

e <- cbind(e,beta)

}


e <- cbind(e,rme)


return(e)

}



res2<-gmm(g3,h,c(rep(0,nstocks),rep(1,nstocks),0),

method="BFGS", control=list(maxit=3000))


summary(res2)


#The intercepts are different but betas are similar


cbind(coef(res2)[1:10], coef(res)[1:10])

cbind(coef(res2)[11:20], coef(res)[11:20])