fmincon is not working

2 Ansichten (letzte 30 Tage)
Olivia
Olivia am 3 Dez. 2024
Kommentiert: Torsten am 4 Dez. 2024
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 Kommentar
Torsten
Torsten am 4 Dez. 2024
Be careful:
Your nonlinear constraint as implemented is
w' * cov_matrix * w = L^2
not
w' * cov_matrix * w <= L^2

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Walter Roberson
Walter Roberson am 4 Dez. 2024
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.

Kategorien

Mehr zu Nonlinear Optimization finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by