# GA, How to modify the requied return to requied risk in a Genetic Algorithm

1 回表示 (過去 30 日間)
Santiago 2021 年 12 月 20 日

As you may see, this code have a requied return as a constraint, but I'm triying to modify it, to give a requied risk instead of a requied return.
If someone can help me I would be amazing, I've been trying to modify the code but I haven't had many results.
Thanks.
format long g
nAssets = size(data, 2);
%Returns and covariance
mu = mean(data);
mu.'
sigma = cov(data);
%formulate the problem/optimization
r_target = 0.004; %r_target is the required return
f = zeros(nAssets, 1); %there is no constant
A = [-mu; -eye(nAssets)] %besides the returns we forbid short selling
b = [-r_target; zeros(nAssets, 1)] % required return and weights greater/eqauls 0
Aeq = ones(1, nAssets) %All weights should sum up...
beq = 1 %... to one (1)
%solve the optimization
fcn = @(w)MaxReturn(w,mu);
[w, fval, flag, output] = ga(fcn, nAssets, A, b, Aeq, beq)
if isempty(w)
warning('could not find any solution')
else
%print the solution
fprintf(2, 'Risk: %.3f%%\n', sqrt(w*sigma*w')*100);
fprintf(2, 'Ret: %.3f%%\n', w*mu'*100);
end
function f = MaxReturn(w,mu)
f = w * mu';
end

サインインしてコメントする。

### 回答 (1 件)

Aman 2024 年 4 月 23 日
Hi Santiago,
As per my understanding, you want to now get the required risk instead of the required returns.
In order to do so, you need to make the below two changes:
1. Instead of maximizing the return, you now need to minimize the portfolio risk.
2. Instead of putting a cap on the minimum return, you now need to cap the maximum allowable risk.
With the above-mentioned changes, the updated code will look like below:
format long g
nAssets = size(data, 2);
% Returns and covariance
mu = mean(data);
mu.';
sigma = cov(data);
% formulate the problem/optimization
risk_target = 0.004; % risk_target is the maximum allowable risk
f = zeros(nAssets, 1); % there is no constant in the objective function for risk minimization
% Objective function is now to minimize risk, so we do not use mu in constraints
A = -eye(nAssets); % Forbid short selling
b = zeros(nAssets, 1); % Weights greater/equal 0
Aeq = ones(1, nAssets); % All weights should sum up...
beq = 1; % ... to one (1)
% solve the optimization
fcn = @(w)PortfolioRisk(w, sigma);
options = optimoptions('fmincon', 'Display', 'iter', 'Algorithm', 'sqp');
[w, risk, flag, output] = fmincon(fcn, ones(nAssets, 1)/nAssets, A, b, Aeq, beq, [], [], [], options);
if isempty(w)
warning('could not find any solution')
else
% print the solution
fprintf(2, 'Risk: %.3f%%\n', sqrt(w'*sigma*w)*100);
fprintf(2, 'Ret: %.3f%%\n', w'*mu'*100);
end
function risk = PortfolioRisk(w, sigma)
risk = sqrt(w' * sigma * w); % Minimize this function
end
I hope it works for you!

サインインしてコメントする。

### カテゴリ

Help Center および File ExchangeGenetic Algorithm についてさらに検索

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by