0

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)
melo777
  • 27
  • 6
  • Provide a small, reproducible dataset so we can get some context to your problem. Look [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for instructions on how to create a reproducible example. – Riley Finn Sep 27 '19 at 18:21

1 Answers1

0

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.)

Enrico Schumann
  • 1,278
  • 7
  • 8
  • Ok I understand. So you mean that weights should also be normalised outside the GA. I used both the approaches separately. But wouldn't that make the normalisation inside the GA (the code above) redundant? – melo777 Sep 27 '19 at 19:56
  • No, it wouldn't. You want the GA to find a solution that looks good when normalised, so you need to pass such a solution to the objective function. Otherwise, the objective function may lead to a solution that looks bad when normalised. – Enrico Schumann Sep 27 '19 at 20:20