Here\'s the code (I\'m sorry if it\'s so long, but it was the first example I had); I\'m using the CVaR example from CreditMetrics
package by A. Wittmann and
Try:
w <- w / sum(w)
and if DEoptim
gives you an optimal solution w*
such that sum(w*) != 1
then w*/sum(w*)
should be your optimal solution.
Another approach is to solve over all your variables but one. We know the value of the last variable must be 1 - sum(w)
so in the body of the function, have:
w <- c(w, 1-sum(w))
and do the same to the optimal solution returned by DEoptim
: w* <- c(w*, 1-sum(w*))
Both solutions require that you re-formulate your problem into an unconstrained (not counting for variable bounds) optimization so DEoptim
can be used; which forces you to do a little extra work outside of DEoptim
to recover the solution to the original problem.
In reply to your comment, if you want DEoptim
to give you the correct answer right away (i.e. without the need for a post-transformation), you could also try to include a penalty cost to your objective function: for example add B * abs(sum(w)-1)
where B
is some arbitrary large number so sum(w)
will be forced to 1
.
I think you should add a penalty for any deviation from one.
Add to your minimizing problem the term +(sum(weights) - 1)^2 * 1e10
. You should see that this huge penalty will force the weights to sum to 1!