Is this cautious coding practice still needed?

I have some code similar to the following in a custom backtest procedure. This code was written many years ago to compute various metrics. It is important to calculate the metrics properly – respecting the bars-in-range during a walk-forward optimization. I’m wondering if this style of programming is still needed?

barsInRange = LastValue(Cum(Status("BarInRange")));
arrayStart = LastValue(ValueWhen(Status("FirstBarInRange"), array));
arrayEnd = LastValue(ValueWhen(Status("LastBarInRange"), array));
metric = (arrayEnd - arrayStart) / barsInRange;
bo.AddCustomMetric("Metric", metric);

Is it safe to rewrite the above code like this?

arrayStart = array[0];
arrayEnd  = LastValue(array);
metric = (arrayEnd - arrayStart) / BarCount;
bo.AddCustomMetric("Metric", metric);

In custom backtest code short version should be fine, as custom backtester works on ~~~EQUITY so it has number of bars equal to range, but general code (non custom backtest) usually has MORE bars than range because MAs, Ref() and all other functions require certrain number of bars BEFORE start of the range to be able to produce results from the start of the range. Say 10-bar MA needs 10 bars before start of the range to produce average since first bar in range.

1 Like

@Tomasz Thank you for the prompt reply. Was the long code truly ever needed in much older versions of AmiBroker?

No, it wasn’t needed in custom backtester.

@Tomasz After dozens of tests, I observed a run where BarCount was larger than the range. It happened during the custom-backtest portion of a walk-forward optimization. QuickAfl was enabled. I observed these values in a debug trace:

0 == BarIndex of firstBarInRange
3775 = BarIndex of lastBarInRange
4026 = BarCount

BarCount was exactly 250 bars longer than range. The walk-forward test was stepping forward one year at a time. I cannot reproduce this.

You are looking at wrong place. You are looking in FIRST phase NOT in custom backtester.

This has been already discussed on this forum dozens of times and is also explained in Knowledge Base exactly 10 years ago.

In FIRST phase of backtest you get 250 more bars than range BECAUSE YOUR INDICATORS in YOUR FORMULA require this (as explained in KB).

But In CUSTOM BACKTESTER (i.e. second phase of backtest) you don’t get those.