Search code examples
ralgorithmquantitative-finance

Perform a SQP algorithm in R


I would like to run following optimization in R:

u.c.: 0 <= x <= 1 and Sum(x)=1

The equation is based on: Efficient Algorithms for Computing Risk Parity Portfolio Weights (equation 10)

The original authors say to use SQP. I would like to follow that but how?


Solution

  • the code could look like this:

    fn <- function(w){return( 
          ((w[1] * w %*% Mat[1,]) - (w[1] * w %*% Mat[1,]))^2 +
          ((w[1] * w %*% Mat[1,]) - (w[2] * w %*% Mat[2,]))^2 + 
          ((w[1] * w %*% Mat[1,]) - (w[3] * w %*% Mat[3,]))^2 +
    
          ((w[2] * w %*% Mat[2,]) - (w[1] * w %*% Mat[1,]))^2 +
          ((w[2] * w %*% Mat[2,]) - (w[2] * w %*% Mat[2,]))^2 + 
          ((w[2] * w %*% Mat[2,]) - (w[3] * w %*% Mat[3,]))^2 +
    
          ((w[3] * w %*% Mat[3,]) - (w[1] * w %*% Mat[1,]))^2 +
          ((w[3] * w %*% Mat[3,]) - (w[2] * w %*% Mat[2,]))^2 + 
          ((w[3] * w %*% Mat[3,]) - (w[3] * w %*% Mat[3,]))^2
      )
      }
    
      library(Rsolnp)
    
      #start values
      w0 <- c(0.3, 0.6, 0.1)
    
      #constrain function
      eqcon <- function(w){(w[1]+w[2]+w[3])}
      ebcon <- 1
    
      #optimizer
      sqp <- solnp(pars = w0,
                   fun = fn2,
                   eqfun = eqcon,
                   eqB = ebcon, 
                   LB = c(0,0,0),
                   UB = c(1,1,1))
    
      sqp$pars