fmincon is not working

조회 수: 2 (최근 30일)
Olivia
Olivia 2024년 12월 3일
댓글: Torsten 2024년 12월 4일
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);
Unrecognized function or variable '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
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
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.

카테고리

Help CenterFile Exchange에서 Nonlinear Optimization에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by