function [weights,fval,qpExit] = minvar(covMat,indvRet,targetRet)
% Oren Rosen
% Copyright 2008 The MathWorks, Inc.
% This function calculates the optimal weights for a minimium variance
% portfolio with a given target return.
% covMat - Covariance matrix for equity returns.
% indvRet - Returns vector for individual equities.
% targetRet - Target return for total portfolio.
% This function is essentially a wrapper for quadprog. Linear equality
% constraints enforce that the weights sum to one and that the target
% portfolio return is achieved. The minimal function value returned by
% quadprog is scaled to represent the portfolio variance.
portSize = length(indvRet);
% No linear term in objective function.
f = zeros(portSize,1);
% Enforce target return and 100% portfolio allocation with linear equality
Aeq = [ ones(1,portSize); indvRet' ];
beq = [ 1; targetRet ];
% All weights bounded between zero and one.
lbnds = zeros(portSize,1);
ubnds = ones(portSize,1);
% Turn off progress display - use medium scale algorithm.
qoptions = optimset('Display','off','LargeScale','off');
% Compute optimized weights
[weights,fval,qpExit] = quadprog(covMat,f,,,Aeq,beq,lbnds,ubnds,,qoptions);
% Double minimal function value for variance - quadprog minimizes (1/2)w'Hw
fval = 2*fval;