% 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 = csvread('../data/sp500-ret.csv');
G  = csvread('../data/sp500-Gqr.csv');

[p,n] = size(G);
w0 = ones(n,1)/n;  % initial holdings
t  = 1.005;        % expected return

prob.a = sparse([ rT, zeros(1, 1+p); 
                  G, zeros(p,1), -eye(p);    
                  ones(1,n), zeros(1,1+p)]);
prob.c = [ zeros(n,1); 1; zeros(p,1)];
prob.cones{1}.type = 'MSK_CT_QUAD';
prob.cones{1}.sub = [n+1:n+1+p];
b = [ t - rT*w0; -G*w0; 0 ];
prob.blc = b;
prob.buc = b;

if SHORTSELLING == 0
  prob.blx = [-w0; -inf*ones(1+p,1)];
end

[err,res]=mosekopt('minimize',prob);
x = res.sol.itr.xx(1:n);
f = res.sol.itr.xx(n+1);
