I am using a portfolio custom backtest which calculates the performance per stock (from AB KB). This part is working fine. I'm wondering is there a way to use the report list in a second layer of backtesting? ie. buy if the previous n trades (of the stock in question) are profitable. Or am I doing it the wrong way?
Still, I don't know the general process for looking at the previous n trades, then entering (or not) based upon their profitability, and doing that for each stock. Is it possible? thanks/
one possible approach can be to loop through all closed trades at each entry signal and then decide to skip it or not based on last trade result.
Maybe there are more efficient ways to do this but I'm not sure if we can access last trade result directly instead of having to loop through all closed trades each time we have an entry signal, but this is one way to do it.
// sample buy, sell rules
Buy=Cross(MA(C,20),MA(C,50));
Sell=Cross(MA(C,50),MA(C,20));
Short=Cover=0;
SetPositionSize(1,spsShares);
SetCustomBacktestProc("");
if (Status("action") == actionPortfolio)
{
StaticVarRemove("skip*");
_date=DateTime() ;
bo = GetBacktesterObject(); // Get backtester object
bo.PreProcess(); // Do pre-processing (always required)
for (i = 0; i < BarCount; i++) // Loop through all bars
{
for (sig = bo.GetFirstSignal( i ); sig; sig = bo.GetNextSignal( i ) ) // custom signal processing
{
if ( sig.IsEntry() )
{
skip=Nz(StaticVarGet("skip"+sig.Symbol)); //this variable indicates to skip signal or not
_TRACE("#AB_1 "+"date: "+DateTimeToStr(_date[i]) +" "+sig.symbol+" skip: "+skip);
if( skip==1 ) // skipped last trade so do not modify signal and pass to next signal
{
skip=0; //skip variable back to zero
StaticVarSet("skip"+sig.Symbol,skip);
_TRACE("#AB_2 "+"date: "+DateTimeToStr(_date[i])+sig.symbol+" skip variable back to zero");
continue; // pass to next signal
}
if( skip==0 ) //entry signal and not skipped trade, evaluate previous trade result
{
signalname=sig.Symbol;
for( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
{
if(trade.Symbol==signalname)
{
if (trade.getprofit()<0)
skip=1; // skip signal if last trade was a loss
else
skip=0;
}
}
StaticVarSet("skip"+sig.Symbol,skip);
_TRACE("#AB_3 "+"date: "+DateTimeToStr(_date[i])+sig.symbol+" "+skip);
}
if(skip==1 )
{
sig.Price=-1; //skip this signal
_TRACE("#AB_4 "+"date: "+DateTimeToStr(_date[i])+sig.symbol+" skip trade");
}
}
}
bo.ProcessTradeSignals( i ); // Process trades at bar (always required)
}
bo.PostProcess(); // Do post-processing (always required)
}