# Simple Portfolio optimization problem of the form
#
# max. mu*w - gamma*w*Sigma*w
# s.t.    w>= 0;  sum(w_i) = 1
#
# where w_i is the weight of investment in the i-th asset.


library(CVXR)


set.seed(10)
n <- 10
mu <- matrix(abs(rnorm(n)), nrow = n)
Sigma <- matrix(rnorm(n^2), nrow = n, ncol = n)
Sigma <- t(Sigma) %*% Sigma

w <- Variable(n)
ret <- t(mu) %*% w
risk <- quad_form(w, Sigma)
constraints <- list(w >= 0, sum(w) == 1)

gamma <- 10^(-2)
objective <- ret - gamma * risk
prob <- Problem(Maximize(objective), constraints)

# iparam: integer parameters (similar names for double and string parameters)
iparam <- list()
iparam$MSK_IPAR_SOLVE_FORM="MSK_SOLVE_DUAL"
result <- solve(prob, solver="MOSEK", verbose=TRUE, iparam=iparam)

stopifnot(abs(result$getValue(risk) - 8.825) <= 0.001)
stopifnot(abs(result$getValue(ret) - 1.626) <= 0.001)
