ApplyStop and move to safe haven

Hi,

I have a simple rotational model. At the end of the year it’s ranking all the stocks of the S&P500 based on the returns of that year. Then it will buy the 5 best performing stocks for the next year. If one of the stocks hit a loss of 25% this stock will be sold.

totalPositions = 5;

SetOption("InitialEquity", 100000);
SetOption("MaxOpenPositions", totalPositions);
SetOption("AllowPositionShrinking", True );
SetPositionSize(100 / totalPositions, spsPercentOfEquity);
SetOption("AllowSameBarExit", True );
SetOption("HoldMinBars", 1);

lastDayOfYear = Year() != Ref(Year(), 1);

score = ROC(Close, 252);
PositionScore = 1000 + score;

Sell = lastDayOfYear;
Buy = lastDayOfYear;
Short = 0;
Cover = 0;

ApplyStop(stopTypeLoss,stopModePercent, 25, False);

This code works fine, but I want to make one addition. When the ApplyStop is hit I want to move this position to a “safe haven” stock or ETF. In this case TLT.

Any idea how to program this?

Kind regards,
Hans

@Hans, try this quick attempt (without changing a lot of code):

totalPositions = 5;

SetBacktestMode( backtestRegularRawMulti ); // allow multiple TLT positions

SetOption( "InitialEquity", 100000 );
SetOption( "MaxOpenPositions", totalPositions );
SetOption( "AllowPositionShrinking", True );
SetPositionSize( 100 / totalPositions, spsPercentOfEquity );
SetOption( "AllowSameBarExit", True );
SetOption( "HoldMinBars", 1 );
lastDayOfYear = Year() != Ref( Year(), 1 );

score = ROC( Close, 252 );
TLTScore = iif( Name() == "TLT", 10000, 0 );
PositionScore = iif( lastDayofYear, 1000 + score, TLTScore );
Sell = lastDayOfYear;
Buy = lastDayOfYear OR( NOT lastDayOfYear AND Name() == "TLT" );

ApplyStop( stopTypeLoss, stopModePercent, 25, False );

(Add TLT to your selected watchlist or use multiple watchlist in the Analysis dialog).

This seems to work... almost: you need to start your test on the first day of an year and in few cases when multiple Stop are triggered on the same day the TLT (multiple positions) are entered
one at time in successive days.

Let's see if any other users have a better and more accurate idea.

3 Likes

Hi @beppe ,

This is working fine. Thanks for your help and your effort!

Kind regards,
Hans

1 Like