I am running a genetic algorithm in R, to select weights for the stocks in a portfolio while having the highest return/risk ratio. The problem is that weights need to sum up to 1 but the code that I have tried so far doesn't work. Any help would be appreciated.
This is my code:
normalise=function(v){v/sum(v)}
f=function(weights){
weights=normalise(weights)
(weights%*%returns)/(weights%*%variances)
}
GA=ga(type="real",fitness=f,lower=rep(0,length(positive)),
upper=rep(1,length(positive)),maxiter=20000,run=300)