Backtester stats output for defined year ranges

Hi, is it possible to have stats in a backtest or optimisation output for defined year ranges, in particular %Wins and AvgProfitPerTrade and AvgLossPerTrade:

Full Optimisation Range = 2000-2020

Backtester report:
% Wins from 2000 to 2010 = xxx
% Wins from 2010 to 2020 = yyy
% Average Profit Made per trade 2000 to 2010 = zzz
% Average Profit Made per trade 2010 to 2020 = zzzzzz
% Loss per trade 2000 to 2010, etc....

Thank you :slight_smile:

Look here

You just have to modify/add few things.

procedure vgWinLossPerDecade(YrWin, YrLoss, Yrcnt, trade, range, mode ) {
	/// by AmiBroker.com and fxshrat@gmail.com
	local dt, n, prof;
	dt = IIf(mode == 1, trade.ExitDateTime, trade.EntryDateTime);
	n = floor(DateTimeConvert(8, dt)/range)*range;
	prof = trade.GetProfit();   
	if( prof >= 0 ) { // profit only
		VarSet(YrWin+"_cnt"+n, Nz(VarGet(YrWin+"_cnt"+n))+1);
		VarSet(YrWin+n, Nz(VarGet(YrWin+n))+prof); 
	} else { // loss only
		VarSet(YrLoss+"_cnt"+n, Nz(VarGet(YrLoss+"_cnt"+n))+1); 
		VarSet(YrLoss+n, Nz(VarGet(YrLoss+n))+prof);   
	} 
	// cnt all per year
	VarSet(Yrcnt+n, Nz(VarGet(Yrcnt+n))+1);
}

/// Per year or decade Win/Loss ration and number of trades, code source at:
/// @link https://forum.amibroker.com/t/custom-metric-annual-trades-wins-and-losses/20241/2
/// @link https://forum.amibroker.com/t/backtester-stats-output-for-defined-year-ranges/29598/2
SetCustomBacktestProc("");
if ( Status( "action" ) == actionPortfolio ) {
	bo = GetBacktesterObject();
	bo.Backtest();

	yr = Year();
	fbr = Status("FirstBarInRange");
	lbr = Status("LastBarInRange");
	first_yr = LastValue(ValueWhen(fbr, yr));
	last_yr = LastValue(ValueWhen(lbr, yr));
	
	mode = 1;
	yr_range = 10;
   
	// iterate closes trades
	for ( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() ) 
		vgWinLossPerDecade("YrWin", "YrLoss", "Yrcnt", trade, yr_range, mode );

	// iterate open trades
	for ( trade = bo.GetFirstOpenPos(); trade; trade = bo.GetNextOpenPos() )
		vgWinLossPerDecade("YrWin", "YrLoss", "Yrcnt", trade, yr_range, mode );

	// Output per decade stats to report file
	for ( i = first_yr; i <= last_yr; i++ ) {
		YrCnt = VarGet("Yrcnt"+i);
		if ( NOT IsNull(YrCnt) ) {
			win_cnt = VarGet("YrWin_cnt"+i);
			loss_cnt = VarGet("YrLoss_cnt"+i);							
			bo.AddCustomMetric( StrFormat( "Decade from %g to end of %g (%g trades): WinRatio %1.2f%%, LossRatio %1.2f%%", 
								i, i+yr_range-1, YrCnt, win_cnt / YrCnt * 100, loss_cnt / YrCnt * 100) ); 
			bo.AddCustomMetric( StrFormat( "Avg.Win %1.2f, Avg.Loss %1.2f", 
								VarGet("YrWin"+i) / win_cnt, VarGet("YrLoss"+i) / loss_cnt) ); 
		}
    }  
}

m = MA( Close, 20 ); 
Buy = Cross( Close, m );
Sell = Cross( m, Close ); 
Short = Cover = 0;

34

4 Likes

Thanks fxhsrat - another fantastic solution :slight_smile:

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.