Hello,
I would need to calculate the annual growth rate for each year of a bactktest, in order to have those values tabulated in the optimization report. I have found a code by @fxshrat with a similar purpose.
procedure vgWinLossPerYear(YrWin, YrLoss, Yrcnt, trade, mode ) {
/// by AmiBroker.com and fxshrat@gmail.com
dt = IIf(mode == 1, trade.ExitDateTime, trade.EntryDateTime);
n = floor(DateTimeConvert(8, dt));
if( trade.GetProfit() >= 0 ) // profit only
VarSet(YrWin+n, Nz(VarGet(YrWin+n))+1);
else // loss only
VarSet(YrLoss+n, Nz(VarGet(YrLoss+n))+1);
// cnt all per year
VarSet(Yrcnt+n, Nz(VarGet(Yrcnt+n))+1);
}
/// Per year Win/Loss ratio and number of trades, code source at:
/// @link https://forum.amibroker.com/t/custom-metric-annual-trades-wins-and-losses/20241/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));
// iterate closes trades
for ( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
vgWinLossPerYear("YrWin", "YrLoss", "Yrcnt", trade, 0 );
// iterate open trades
for ( trade = bo.GetFirstOpenPos(); trade; trade = bo.GetNextOpenPos() )
vgWinLossPerYear("YrWin", "YrLoss", "Yrcnt", trade, 0 );
// Output per year stats to report file
for ( i = first_yr; i <= last_yr; i++ ) {
YrCnt = VarGet("Yrcnt"+i);
bo.AddCustomMetric( StrFormat( "Year%g (%g trades): WinRatio %1.2f%%, LossRatio %1.2f%%",
i, YrCnt, VarGet("YrWin"+i) / YrCnt * 100, VarGet("YrLoss"+i) / YrCnt * 100) );
}
}
m = MA( Close, 20 );
Buy = Cross( Close, m );
Sell = Cross( m, Close );
Short = Cover = 0;
Since I am not very familiar to custom backtester yet, I have been unable to modify it to get the metric that I need. I should appreciate it if some user would help me with it.
Thanks in beforehand.
Regards.