fmincon is not working
조회 수: 2 (최근 30일)
이전 댓글 표시
I'm trying to optimize the weights of a stock portfolio to maximize returns. I checked if expected_returns is a vector, and it is, but I still get the error message :
Error using fmincon (line 504)
Supplied objective function must return a scalar value.
Error in igggg (line 7652)
[weights, fval] = fmincon(objective, w0, A, b, Aeq, beq, lb, ub, nonlincon, options);
% Risk limits L
risk_limits = [0.02, 0.015, 0.01];
% Number of assets
num_assets = length(expected_returns);
% Run optimization for each L
for L = risk_limits
% Objective function: maximize expected return (minimize negative return)
objective = @(w) -sum(w .* expected_returns);
% Constraints:
% - Portfolio standard deviation <= L
% - Sum of weights = 1
A = [];
b = [];
Aeq = ones(1, num_assets); % Sum of weights = 1
beq = 1;
lb = zeros(num_assets, 1); % Weights >= 0
ub = ones(num_assets, 1); % Weights <= 1
% Nonlinear constraint: portfolio standard deviation <= L
nonlincon = @(w) deal([], sqrt(w' * cov_matrix * w) - L);
% Initial guess (equal weights)
w0 = ones(num_assets, 1) / num_assets;
% Solve optimization problem
options = optimoptions('fmincon', 'Display', 'iter', 'Algorithm', 'sqp');
[weights, fval] = fmincon(objective, w0, A, b, Aeq, beq, lb, ub, nonlincon, options);
end
댓글 수: 1
Torsten
2024년 12월 4일
Be careful:
Your nonlinear constraint as implemented is
w' * cov_matrix * w = L^2
not
w' * cov_matrix * w <= L^2
답변 (1개)
Walter Roberson
2024년 12월 4일
I bet expected_returns is a row vector.
fmincon() passes values to the objective function in the shape of the x0 array. Here your x0 is w0, which is ones(num_assets,1) so it is a column vector that will be passed to the objective function.
If the objective function is passed a column vector and exxpected_returns is a row vector, then w.*expected_returns would be column vector .* row vector, which would give a 2D result. sum() of a 2D result would be a vector.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Nonlinear Optimization에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!