Reputation: 73
I have the following equation:
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) (1).
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.
with U(Rp,t+1;x)
is the investor utility
x
is the vector of parameters to maximize
Zt
presents the 4 risk factors.
The code is:
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 errors: for p -->
Error in solve.default(crossprod(hm, xm), crossprod(hm, ym)) :
Lapack routine dgesv: system is exactly singular: U[2,2] = 0
for bra -->
Error in is.data.frame(x) :
(list) object cannot be coerced to type 'double'
I am would be veryy grateful if you could help me on this ! Thank you
Upvotes: 1
Views: 1088
Reputation: 522
I would write a unit test for your func function. You can use browser()
to step through it.
Put ret and factors into a data frame. df <- data.frame(ret, A=factors$A*x[1], ...)
Then run m <- gmm(ret~., data=df); beta <- coef(m)
Upvotes: 1