[R] Constraint Optimization with constrOptim

Raimund Grundböck
Mon, 17 Sep 2012 17:11:51 -0000

Hi,

I am having trouble using constrOptim. My target is to do a portfolio
optimization and there some constraints have to be fulfilled.

1) The weight of each share of the portfolio has to be greater than 0
2) The sum of these weights has to be 1

I am able to fulfill either the first or the second constraint but not both.

One simple way would be to fulfill the first constraint by using optim as I have
the possibility of using bounds (lower=0, upper=1) but then I am not able to
implement the second constraint.

Has anybody an idea to implement both constraints. Or, does anybody know the
fault in the code (I try to solve it since many days)?

Thank you for your help

Raimund


Here is the simplified code:

#Computation of the minimum-variance portfolio

library(tawny)
library(fBasics)

#Rendite - data
dataset <- matrix(c(0.019120,  0.033820, -0.053180,  0.036220, -0.021480,
-0.029380, -0.012180, -0.076980, -0.060380,
                    0.038901, -0.032107, -0.034153, -0.031944,  0.006494,
-0.021062, -0.058497,  0.050473,  0.026086,
                    0.004916, -0.015996,  0.003968,  0.030721,  0.034774,
-0.004972,  0.019459,  0.000196, -0.001849), nrow=3, ncol=9, byrow=TRUE)

#Computation of the means
tableMeans <- colMeans(dataset)

#Computation of the variance-covariance matrix
covarianceMatrix <- ((t(dataset)) %*% dataset) / 3

#--------------------SOLVER-START-----------------------------

#start estimates
startingEstimates = rep(1/9, 9)
matrixStartingEstimates = matrix(startingEstimates, nrow=1, ncol=9, byrow=TRUE)

matrixStartingEstimatesNegativ = matrix(rep(-1/9, 9), nrow=1, ncol=9,
byrow=TRUE)

#The function which should be minimized
x <- matrixStartingEstimates
fkt <- function(x) {t(x) %*% covarianceMatrix %*% x}

#The constraints
#The results should be greater 0                            !DOES NOT WORK!
constraint1 <- x[1:9]
#The summ of the results should be between 0.999 and 1.001
constraint2 <- sum(matrixStartingEstimatesNegativ)
constraint3 <- sum(x)

constraintMatrix <- rbind(constraint1, constraint2, constraint3)
constraintVektor <- c(0, -1.00001, 0.99999)

#Optimization
constrOptim(startingEstimates, fkt, NULL, ui = constraintMatrix, ci =
constraintVektor)


#------------------------SOLVER-END-----------------------------
	[[alternative HTML version deleted]]