新手,修改程序时输出总显示错误,程序如下:
#----------------------------------------------------------------------------
# Define the moment equations
#----------------------------------------------------------------------------
meqn <- function(b,Rct,Rbt,Rst,zt) {
cols <- ncol(zt)
rows <- nrow(zt)
beta <- b[1] # Relative risk aversion parameter
gam <- b[2] # Discount parameter
ut1 <- beta*(1+Rct)^(-gam) * (1 + Rbt) - 1
ut2 <- beta*(1+Rct)^(-gam) * (1 + Rst) - 1
ut<- cbind(ut1,ut2)
k <- 2
mt <- array(0, c(rows,cols))
for (j in seq(cols)) {
mt[,k] <- zt[,j]*ut1
k <- k+1
}
return(mt)
}
#----------------------------------------------------------------------------
# Defines the mean of the moment conditions
#----------------------------------------------------------------------------
meaneqn <- function(b,Rct,Rbt,Rst,zt) {
ret <- colMeans(meqn(b,Rct,Rbt,Rst,zt))
return(ret)
}
#----------------------------------------------------------------------------
# GMM objective function which also computes the optimal w
#----------------------------------------------------------------------------
q <- function(b,Rct,Rbt,Rst,zt,lmax){
d <- meqn(b,Rct,Rbt,Rst,zt)
g <- cbind(colMeans(d))
w <- t(1) %*% 1
tau <- 1
while (tau <= lmax) {
wtau <- t( d[(tau+1):nrow(d),] ) %*% d[1:(nrow(d)-tau),]
w <- w + (1.0-tau/(lmax+1))*(wtau + t(wtau))
tau <- tau + 1
}
t <- length(Rct)
ret <- t(g) %*% inv(w) %*% g
return(ret)
}
#
#----------------------- The equity_mp Based on Gmm --------------------
#
##gmm_ccapm <- function()
##{
load('equity_mp.Rdata')
St<-data[,2]
Dt<-data[,3]
Ct<-data[,4]
Rt<-data[,5]
Pt<-data[,6]
Rst<-(trimr(St,1,0)+trimr(Dt,0,1)-trimr(St,0,1))/trimr(St,0,1)
Rbt<-(1+trimr(Rt,0,1))*(trimr(Pt,0,1)/trimr(Pt,1,0))-1
Rct<-(trimr(Ct,1,0)-trimr(Ct,0,1))/trimr(Ct,0,1)
ydata<-cbind(Rst,Rbt,Rct)
Rst<-ydata[,1]
Rbt<-ydata[,2]
Rct<-ydata[,3]
t <- length(Rct)-1
# Instruments <- {const,Rbtlag,Rstlag}
zt <- cbind(rep(1, t),trimr(Rbt,0,1),trimr(Rst,0,1)
estResults <- optim(q, Rct=Rct, Rbt=Rbt, Rst=Rst,zt=zt, lmax=0, method="BFGS")
bgmm <- estResults$par
qmin <- estResults$value