# Minimum risk Markowitz portfolio selection example
#
#   minimize    f
#   subject to  r'*(w0 + x) = t
#               G*(w0 + x) = g,  ||g||_2 < f
#               sum(x) = 0.
#               and optionally w0 + x >= 0
# or equivalently 
# 
#   minimize     f
#   subject to  [ r'  0   0 ] [ x ]   [ t-r'*w0 ] 
#               [ G   0  -I ]*[ f ] = [  -G*w0  ] 
#               [ e'  0   0 ] [ g ]   [    0    ]    
#               ||g||_2 <= f
#               and optionally w0 + x >= 0    

SHORTSELLING <- 1;

# Read expected returns and covariance factor
rT <- as.matrix(read.csv("../data/sp500-ret.csv", header=F))
G  <- as.matrix(read.csv("../data/sp500-Gqr.csv", header=F))

p <- nrow(G); n <- ncol(G);
w0 <- matrix(1/n,nrow=n); # initial holdings
t  <- 1.005;              # expected return

prob <- list(sense="minimize")
prob$A <- rBind(
  cBind(rT, Matrix(0, ncol=1+p)),
  cBind(G, Matrix(0, nrow=p), -diag(p)),
  cBind(Matrix(1,ncol=n), Matrix(0,ncol=1+p))
)
prob$c <- c(rep(0,n), 1, rep(0,p));
prob$cones <- cBind( list('MSK_CT_QUAD', (n+1):(n+1+p)) )
b <- c(t - rT%*%w0 , -G%*%w0 ,  0 );
prob$bc <- rbind(b, b);
prob$bx <- matrix(c(-Inf,Inf), nrow=2, ncol=n+1+p);

if (SHORTSELLING == 0) {
  prob$bx[1,] <- c(-w0, rep(-Inf,1+p));
}

res<-mosek(prob);
x <- res$sol$itr$xx[1:n];
f <- res$sol$itr$xx[n+1];

