# Problem with SUM function and variable periods

Hello,

Looked everywhere and cannot find the answer ... I am getting weird results from the SUM function with an array input for the periods. I am trying to sum "high minus low" bar ranges over a variable number of bars (array refbars, equal to the bars since the 5 period lowest low). Here is the code:

Filter = True;

refbars = LLVBars(L,5);
range = H - L;
sumofranges = IIf(refbars > 0, SUM(range, refbars), 0);

Here is the ouput for symbol XLY, starting on Jan 4, 2021:

Ticker Date/Time RefBars Range SumOfRanges
XLY 01/04/2021 0.00 4.44 0.00
XLY 01/05/2021 1.00 2.61 2.61
XLY 01/06/2021 2.00 3.85 6.46
XLY 01/07/2021 3.00 2.37 8.83
XLY 01/08/2021 4.00 2.67 11.49
XLY 01/11/2021 4.00 2.31 11.19
XLY 01/12/2021 4.00 2.49 9.82
XLY 01/13/2021 4.00 1.48 8.94
XLY 01/14/2021 3.00 2.28 6.25
XLY 01/15/2021 0.00 2.20 0.00
XLY 01/19/2021 1.00 1.39 1.39
XLY 01/20/2021 2.00 2.58 3.96
XLY 01/21/2021 3.00 1.30 5.26
XLY 01/22/2021 4.00 1.29 6.56
XLY 01/25/2021 4.00 4.62 9.78
XLY 01/26/2021 1.00 1.50 1.50
XLY 01/27/2021 0.00 4.25 0.00
XLY 01/28/2021 0.00 3.90 0.00
XLY 01/29/2021 0.00 4.19 0.00
XLY 02/01/2021 1.00 3.50 -0.69
XLY 02/02/2021 2.00 3.37 2.69
XLY 02/03/2021 3.00 1.78 4.47
XLY 02/04/2021 4.00 1.54 6.01
XLY 02/05/2021 4.00 1.95 4.45
XLY 02/08/2021 4.00 1.31 2.38
XLY 02/09/2021 4.00 1.04 1.64
XLY 02/10/2021 4.00 3.55 3.65

Notice that on 02/01/2021 the SUM function seems to get "confused" and provides a result that is equal to the difference between the previous bar range and the current bar range (3.50 - 4.19). From here on the SumOfRanges values are nonsense.

Tried to restart, but the result is exactly the same.

I must be doing something stupid, but can't figure it out ...

Thanks!

Robert

You should not pass ZERO or negative range to Sum(). You are doing that right now. Instead you should be calling it

SUM(range, max( 1, refbars ) )

Thanks a lot Tomasz! In a way I was trying to do this with

sumofranges = Iif(refbars > 0, SUM(range, refbars), 0)

At first sight and looking at the array implementation of IIf in the reference I don't see how it would fail, but to catch this nuance I guess I need to read a bit more in Understanding AFL, as suggested.

No, iif is a function so ALL arguments are evaluated regardlless of condition. A must read is here:

Your code does not prevent calling sum with incorrect argument values. It just merely masks output value, but sum is called anyway with wrong params.

BTW it is better (faster) to use SumSince function instead

Late reply .... thanks Tomasz, it's clear now

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