How to find average MDD

Hello,

May i know how to find the 5 largest MDD in CBT. After that, i will calculate the avg of it and create a custom metric.

Thank you for yr help.

Cesar Alvarez has generously shared code for that and several other afl's on his web site. He also offers courses on learning AmiBroker. You can find his code by scrolling down the page at

But for this specifically,

// Provided by Cesar Alvarez www.AlvarezQuantTrading.com
// this code is for daily bar tests

numberDrawdowns = 5;

////////////////////////////////////////////////////////////
// Repalce with your code
SetOption("MaxOpenPositions",10);
SetPositionSize(10,spsPercentOfEquity);

Buy = RSI(2) < 5;
Sell = RSI(2) > 80;

Short = Cover = 0;
// End of replace
///////////////////////////////////////////////////////////


// Or you can add the following to the end of your current code
// will not output anything if there are less than 200 bars in your test
SetCustomBacktestProc("");
if(Status("action") == actionPortfolio)
{
	dnStart = Status("rangefromdate");
	dnEnd = Status("rangetodate");
	yrStart = int(dnStart/10000);
	yrEnd = int(dnEnd/10000);

	bo = GetBacktesterObject();
	bo.backtest();

	if(BarCount > 200)
	{
		VarSet("DD2", 100);
		eq = bo.EquityArray();
		drPerc = -100*(eq/Highest(eq) - 1);

		dd = 0;
		bslh = HighestBars(eq);
		bslh[BarCount-1] = 0; // need to catch last DD
		dd = IIf(bslh == 0, IIf(Ref(bslh, -1)==0, 0, HHV(drPerc, Ref(bslh, -1)+1)), 0);
		
		ddLast = LastValue(Highest(dd));
		VarSet("DD1", ddLast);
		bo.AddCustomMetric("DD1", ddLast);
		for (nDD = 2; nDD <= numberDrawdowns; nDD++)
		{
			ddNew = LastValue(Highest(IIf(dd < ddLast, dd, 0)));
			VarSet("DD" + nDD, ddNew);
			ddLast = ddNew;
			bo.AddCustomMetric("DD"+nDD, ddLast);
		}
		bo.AddCustomMetric("MDD Cur", LastValue(drPerc));
	}
}
5 Likes

Thank you. The website is very good!

It does not calculate average but is supposed to list 5 worst drawdown periods.
But AFAICS it does not do that, too.
See here why I think so (and includes code for average):

1 Like