I am trying to do a mean-variance function manually in R and I am stuck on one problem.
This is how i have defined a for loop to calculate the Portfolio Risk if I know the weights of elements in portfolio (w) in advance:
for (i in 1:nrow(databcpp)) {
for (j in 1:nrow(databcpp)){
datavarhelp[i,j] <- w[i]*w[j]*databcpp$StdDev[i]*databcpp$StdDev[j]*corrplot_res$corr[i,j]
}
databcpp$PortRisk[i] <- sum(datavarhelp[,j])
}
sum(databcpp$PortRisk)
However when I try to use this in optimization with unknown weights (using CVXR package) trying to minimize the risk like this...:
w_fun <- Variable(nrow(databcpp))
PortRisk = NULL
for (i in 1:nrow(databcpp)) {
for (j in 1:nrow(databcpp)){
datavarhelp[i,j] <- w_fun[i]*w_fun[j]*databcpp$StdDev[i]*databcpp$StdDev[j]*corrplot_res$corr[i,j]
}
PortRisk[i] <- sum(datavarhelp[,j])
}
obj <- sum(PortRisk)
constraint1 <- w_fun >= 0
constraint2 <- sum(w_fun)==1
YrRet <- databcpp$YrRet
constraint3 <- sum(w_fun * YrRet) >= 0.05
prob <- Problem(Minimize(obj), constraints = list(constraint1, constraint2, constraint3))
result <- solve(prob)
str(result)
... I am getting an error message:
Error in x[[jj]][iseq] <- vjj :
incompatible types (from S4 to double) in subassignment type fix
I know it's because the w_fun is in S4 Class, however I have no idea how to advance with this. Anybody would be so kind to bring an idea?
And please apologize possible terminology mistakes, I am quite a beginner with R :)