For a non-linearity test of the CAPM (Captial asset pricing model), I want to test the parameter stability under the assumption that betas (bi) and expected returns(x) are linear functions of the conditioning variables (z).
Following Ghysels (1998) I want to use the GMM to calculate the parameters under the following moment conditions: GMM moment conditions
This is my code:
gl <- function(theta, x) { 
  g_PF <- function(a) {
      aa1 <- (x[,a] * z[,1]) - ((z[,1:3] %*% matrix(theta[(a*3-2):(a*3)],3,1)) * z[,1])
      aa2 <- (x[,a] * z[,2]) - ((z[,1:3] %*% matrix(theta[(a*3-2):(a*3)],3,1)) * z[,2])
      aa3 <- (x[,a] * z[,3]) - ((z[,1:3] %*% matrix(theta[(a*3-2):(a*3)],3,1)) * z[,3])
      ab1 <- (((z[,1:3] %*% matrix(theta[(a*3-2):(a*3)],3,1)) * z[,1]) - ((z[,1:3] %*% matrix(bi[((a+2)/3), 1:3], 3, 1) * z[,1:3] %*% matrix(theta[19:21],3,1)) * z[,1]))
      ab2 <- (((z[,1:3] %*% matrix(theta[(a*3-2):(a*3)],3,1)) * z[,2]) - ((z[,1:3] %*% matrix(bi[((a+2)/3), 1:3], 3, 1) * z[,1:3] %*% matrix(theta[19:21],3,1)) * z[,2]))
      ab3 <- (((z[,1:3] %*% matrix(theta[(a*3-2):(a*3)],3,1)) * z[,3]) - ((z[,1:3] %*% matrix(bi[((a+2)/3), 1:3], 3, 1) * z[,1:3] %*% matrix(theta[19:21],3,1)) * z[,3]))
      mocon <- cbind(aa1, aa2, aa3, ab1, ab2, ab3)
      return(mocon)
    }
  g_M <- function(b) {
        bb1 <- (x[,b] * z[,1]) - ((z[,1:3] %*% matrix(theta[(b*3-2):(b*3)],3,1)) * z[,1])
        bb2 <- (x[,b] * z[,2]) - ((z[,1:3] %*% matrix(theta[(b*3-2):(b*3)],3,1)) * z[,2])
        bb3 <- (x[,b] * z[,3]) - ((z[,1:3] %*% matrix(theta[(b*3-2):(b*3)],3,1)) * z[,3])
        mocon1 <- cbind(bb1, bb2, bb3)
        return(mocon1)
        }
  #Moment conditions:
  MSL <- g_PF(a = 1)
  MSM <- g_PF(a = 2)
  MSB <- g_PF(a = 3)
  MHL <- g_PF(a = 4)
  MHM <- g_PF(a = 5)
  MHB <- g_PF(a = 6)
  MM <- g_M(b = 7)
  gmat <- cbind(MSL, MSM, MSB, MHL, MHM, MHB, MM)
  return(gmat)
}
ress <- gmm(g = gl,x = x,  rep(0,21))
summary(ress)
The function gl serves to generate the moment conditions while the desired output would be a vector of 21 parameters (3 parameters - two conditioning variables + constant - for the six test portfolios + the market portfolio).
When I run my code I get the following error message:
Error in AA %*% t(X) : requires numeric/complex matrix/vector arguments
In addition: Warning message:
In ar.ols(x, aic = aic, order.max = order.max, na.action = na.action,  :
  model order:  1 singularities in the computation of the projection matrix results are only valid up to model order 0
This is my data for the returns, the betas and the conditoning variables:
 
    