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