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)
That is because you do not actually "repair" the solution: you only map it to a feasible one before you evaluate it. Which is something you may actually do; but then you must map the solution of the GA as well, i.e. normalise the weights that the GA returns. (See for instance Maringer, D. and Oyewumi, O. (2007). Index Tracking with Constrained Portfolios.)