The error in your MATLAB script arises from the incorrect definition of the covariance matrix Sigma.
Issue:
You are calculating the covariance matrix Sigma as:
Sigma = sigma * sigma';
Where:
sigma = [0.02; 0.04; 0.07];
Thus, Sigma becomes a 3×3 matrix as the outer product of the standard deviation vector with itself.
This is not a proper covariance matrix unless all assets are perfectly correlated.
Consequences:
- The resulting matrix
H = Sigma is not positive definite, which is required by quadprog.
quadprog will throw an error or return exitflag == -2 for a non-convex problem.
Solution:
You need a valid positive definite covariance matrix, typically computed as:
Sigma = C .* (sigma * sigma');
Where C is a correlation matrix of shape 3×3. If you do not have asset correlations, you might (for now) assume the identity matrix (C = eye(3)), which implies no correlation.
Fix:
Option 1: Use a diagonal covariance matrix (no correlation)
sigma = [0.02; 0.04; 0.07];
Sigma = diag(sigma.^2); % Diagonal matrix of variances
Then everything else remains the same.
Final Corrected Code:
clearvars; clc;
mu = [0.02; 0.06; 0.07];
sigma = [0.02; 0.04; 0.07];
Sigma = diag(sigma.^2); % variance-covariance matrix
H = Sigma;
f = zeros(3, 1);
A = -mu';
b = -0.05; % Target return of 5%
Aeq = [1, 1, 1];
beq = 1;
lb = [0; 0; 0];
ub = [1; 1; 1];
options = optimoptions('quadprog', 'Display', 'off');
[w, ~, exitflag] = quadprog(H, f, A, b, Aeq, beq, lb, ub, [], options)
If you'd like to introduce correlations, you can specify a correlation matrix C, for example:
C = [1 0.2 0.1; 0.2 1 0.3; 0.1 0.3 1];
Sigma = C .* (sigma * sigma');
Let me know if you want an example with correlated assets.