R2 as custom metric

Hello.
I would like to add the R2 of the equity curve as a custom metric. I used the following code:

SetCustomBacktestProc("");

if( Status("action") == actionPortfolio )
{
    bo = GetBacktesterObject();

    bo.Backtest(); // run default backtest procedure

    st = bo.GetPerformanceStats(0); // get stats for all trades
	
	eq = bo.EquityArray;
	r2=Correlation(BarIndex(), eq, BarCount-1 ) ^ 2;
    
    // Here we add custom metric to backtest report
    bo.AddCustomMetric( "R-Squared", r2 );
}

But the result does not show a value:

r2

Help regarding this would be super...

1 Like

Try using BarCount-2 in your Correlation() call.

Thx for the quick response.

I tried your suggestion, but still no value for R2 is shown.

Per-backtest metric must be a scalar. You are passing array instead of scalar. You need to use LastValue as shown below.

SetCustomBacktestProc("");

if( Status("action") == actionPortfolio )
{
    bo = GetBacktesterObject();

    bo.Backtest(); // run default backtest procedure

    st = bo.GetPerformanceStats(0); // get stats for all trades
	
	eq = bo.EquityArray;
	r2 = Correlation(BarIndex(), eq, BarCount - 1 ) ^ 2;
    
    // Here we add custom metric to backtest report
    bo.AddCustomMetric( "R-Squared", LastValue(r2) );
}
3 Likes

Hello Tomasz,

now as you say it, it seems clear. Function reference says also Correlation returns array.

Thank you so much!

Maybe a follow-up question, if I may: Is it possible to suppress some metrics of the standard performance report?

No, you can’t suppress built-in ones. You can only add your own.

1 Like