fmincon is not working

5 ビュー (過去 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 Center および File ExchangeNonlinear Optimization についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by