TakeProfit- Stop loss
Show older comments
I generated a function that allows to invest into risky and/or riskless asset
But now i dont know how i can implement a certain limit, so that if reached, it closes the risky asset and invests everything into the riskless asset
This is what I got.
I tried something like this:
While S > P (which is one of the critical values)... then take the profits and invest into the riskfree asset.
clear
%% market data & investor's preferences
% market
rF = 0.01; %Fixed return for riskfree asset
mu = 0.0031; %mean log return r- N(mu,sigma)
sigma = 0.19; %volatility
S0 = 100; %initial price
%investor
V0 = 100; %amount to invest, initial wealth
T = 1; %investment horizon years
adjust_every = 1; %daily adjustmend
P = (0.05 * V0) + V0; %critical value of profit %take profit TP
Lc = V0 - (0.03 * V0); %critical value of losses %stop losses SL
alpha = 1; %fraction of wealth in risky asset
dt = 1/250; %time increments.. daily
nExp = 1; %number of simulations
%% simulate 250 days of risky stock
%initialize variables for over time
M = round(T/dt) +1; %number of points in time to consider (we start at point 0)
rSim = randn(M,nExp) * sigma * sqrt(dt)+ mu * dt;
rSim(1,:) = 0;
S = S0 .* exp(cumsum(rSim));
for adjust_every =[1]
cash = nan(M,nExp);
risky = nan(M,nExp);
nStock = nan(M,nExp);
wealth = nan(M,nExp);
t = 1; %at the beginning of the investment horizon ...
cash(t,:) = V0 * (1-alpha); %cash initially
nStock(t,:) = (V0 * alpha) / S0;
risky(t,:) = nStock(t,:) .* S(t,:); % the risky asset is worth...
wealth(t,:) = cash(t,:) + risky(t,:);
% over time (what is happening)
for t = 1:(M-1)
%at tb (begining of period t)
tb = t;
if mod(tb-1, adjust_every) == 0
%while S > P
% nOpt = 0;
%end
%while S < Lc
%nOpt = 0;
%end
nOpt = wealth(tb,:) * alpha ./ S(tb,:); %optimal number of risky assets you want to own
alphaCur = risky(tb,:) ./ wealth(tb,:); %current alpha , current fraction in risky asset
deltaN = nOpt - nStock(tb,:); % how many stocks to buy/sell ? if delta is pos-> buy , neg-> sell
% changing postitions... what happened ?
nStock(tb,:) = nStock(tb,:) + deltaN;
risky(tb,:) = nStock(tb,:) .* S(tb,:);
cash(tb,:) = cash(tb,:) - deltaN.*S(tb,:);
wealth(tb,:) = cash(tb,:) + risky(tb,:);
end
%at te (end of period t)
te = t+1;
nStock(te,:) = nStock(tb,:);
risky(te,:) = nStock(te,:) .* S(te,:);
cash(te,:) = cash(tb,:) * exp(rF*dt);
wealth(te,:) = cash(te,:) + risky(te,:);
end
end
%results
area([cash,risky])
plot(wealth)
VT = wealth(end,:);
%hist(VT,20);
rT = VT./V0-1; %result of overall performance
Answers (0)
Categories
Find more on Portfolio Optimization and Asset Allocation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!