[R] Optim():Error in solve.default(crossprod(hm, xm), crossprod(hm, ym))

nourhaine nefzi nourhaine1 at hotmail.fr
Wed Jun 1 19:52:44 CEST 2016


Dear members;
I am stuck trying to find optimal parameters using optim() function. I would be veryy gateful if you could help me on this:

I have the following equation:

                                        Rp,t+1 = rf+ beta*rt+1 (1)

Rp,t+1= the return of the portfolio , fr = free risk rate , rt+1: the return of a strategy. beta has the following expression:
beta=x0+x1*A+ x2*B+ x3*C+x4*D (Estimated using Generalized Method of Moments (GMM).
A,B,C and D are the risk factors related to rt+1.

My objective is to find the optimal values of x1, x2, x3 and x4 that maximize the utility function of the investor.
The code is then :
ret<-cbind(ret)  #ret= rt+1
factors<-cbind(A,B,C,D)

func<-function(x,ret,factors) {
df <- data.frame(A=factors$A*x[1],B=factors$B*x[2],C=factors$C*x[3], D=factors$D*x[4])
H<-as.matrix(factors)
HH<-matrix(H,179,4)
m <- gmm(ret~., data=df, HH)
b<- coef(m)
beta<- b[1]+b[2]*factors$A+b[3]*factors$B+b[4]*factors$C+b[5]*D
beta=cbind(beta)

r=RF+beta*ret  #equation (1)
#Annual Sharpe ratio of the portfolio
averp<-mean(r)*12
sigmap<-sqrt(12)*sd(r)
Sharpe<-averp/sigmap

#Calculating utility
u<-1/nrow(r)*sum((1+r)^(1-5)/(1-5))
obj<-u
result <- list(obj=obj,u=u,beta=beta,r=r,averp=averp,sigmap=sigmap,Sharpe=Sharpe)
return(result)
}

#Catching the obj from the function
Final<-function(x,ret,factors){
bra<-func(x,ret,factors)
#print(bra$obj)
return(-bra$obj)
}
p<-optim(par = c(0,1,2,3),Final,method="Nelder-Mead",ret=ret,factors=factors)
bra<-func(x=p$par,ret=ret,factors=factors)

When I run the code, I get the following error:

Error in solve.default(crossprod(hm, xm), crossprod(hm, ym)) :
  Lapack routine dgesv: system is exactly singular: U[2,2] = 0

Could you please help me ! Thank you in advance

	[[alternative HTML version deleted]]



More information about the R-help mailing list