Problem with closing positions in delisted stocks

I am using following code together with Norgate Data:

#include_once "Formulas\Norgate Data\Norgate Data"

SetOption ("MaxOpenPositions" , 15); 
SetOption ("allowsamebarexit",false); 

OnSecondLastBarOfDelistedSecurity = BarIndex() == (LastValue(BarIndex()) -1) AND !IsNull(GetFnData("DelistingDate")); 
OnLastTwoBarsOfDelistedSecurity = BarIndex() >= (LastValue(BarIndex()) -1) AND !IsNull(GetFnData("DelistingDate")); 

bi = BarIndex();
exitLastBar = bi == LastValue( bi - 1 );
Buysetup = C > 5 
AND C > Ref(HHV(H,40),-1) 
AND NorgateIndexConstituentTimeSeries("$SPX")
AND NOT OnLastTwoBarsOfDelistedSecurity; 
Buy = Ref(buysetup,-1); 
Sell = OnSecondLastBarOfDelistedSecurity OR exitLastBar;

BuyPrice = Open; 
SellPrice = Close; 

SetPositionSize( 15, spsPercentOfEquity );
PositionScore = 1000+Ref(ROC(C,252),-1); 

ApplyStop( stopTypeTrailing,stopModePoint, 10*ATR(5), 0,false);

Although I have tried the Norgate data function to close delisted stocks as well the advice found here I still do have a lots of delisted stocks left in my backtest run on SP500 (the stocks stop trading even few years before my backtest end setting):


what I am doing wrong? How can I close the delisted stocks in the backtest?

I have "pad and align" selected in Backtester settings:


Thank you.

If you're using Pad & Align, then you can't use delisting logic that assumes that the symbol stops trading at bar number BarCount()-1.

1 Like

OK, I did not know that.

I am not sure - if the code also contains conditions referencing other market using Foreign("spy","c"); it should generaly use Pad & Align, right?

Than I found out that condition sell = DateTime() >= GetFnData("DelistingDate"); closes the delisted stocks. Is there any problem using this code?

Thank you.

That code on its own won't accommodate the below:


Try this:

securityGoneToGod = DateTime() >= GetFnData("DelistingDate");
barsBeforeSecurityGoneToGod = (LastValue(ValueWhen(DateTime() == GetFnData("DelistingDate"), BarIndex(), 1))) - BarIndex();

Sell = yourSellRules OR Ref(securityGoneToGod, 2) OR Ref(securityGoneToGod, 1);

Filter = 1;

AddColumn(Close, "Close");
AddColumn(BarIndex(), "BarIndex");
AddColumn(barsBeforeSecurityGoneToGod, "Bars Before Delisting");
AddColumn(securityGoneToGod, "Security is Delisted");


1 Like