在R中执行SQP算法

时间:2017-06-05 08:56:44

标签: r algorithm quantitative-finance

我想在R中运行以下优化:

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

该等式基于:Efficient Algorithms for Computing Risk Parity Portfolio Weights(等式10)

原作者说要使用SQP。我想遵循那个但是如何?

1 个答案:

答案 0 :(得分:0)

代码看起来像这样:

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