Questions regarding AFL-logic of bars

Hello,

I'm new to AFL and have some questions regarding the logic of the array/bar references. When calculating a simple moving average of length 3 and calculating the ROC of length 3. The explorer starts giving the correct values only on the 4th bar of the symbol, why is this (for SMA this is started from bar 2 and for ROC this is started from bar 1)? e.g (explorer):

image

I would expect the SMA and the ROC to be showing on bar 3 already (calculated from bar 1 to 3). This is because I know the close at the end of the day so I would take this price into account.

Please clarify. If my explanation is not clear, I'll try to elaborate and give more examples.

Code example:

mavs=3;
rankl=3;


//for debugging purposes
Filter = 1; // show all bars
AddColumn( open, "open" );
AddColumn( high, "high" );
AddColumn( low, "low" );
AddColumn( close, "Close" );
AddColumn(MA(Close,mavs);, "SMA3",1.4 );
AddColumn(ROC(Close,rankl),"ROC3",1.4);

Your picture is showing Excel not AB explorer. Also it is not really great OHLC data.
Below is better AB data output (of different symbol).


Anyway,

SMA includes "current" bar into lookback.
So for MA(C,3) it is

MA3 = (C[currentBar] + C[currentBar-1] + C[currentBar-2]) / 3;

ROC(C, 3) is doing this:

ROC3 = (C - Ref(C,-3)) / Ref(C,-3) * 100;

where Ref(C,-3) is C[currentBar-3].

So for ROC on bar 3 -> C[currentBar-3] does not exist yet. That's why first value will be at bar 4.


22


So instead you may do this:

mavs=3;
rankl=2;

Filter = 1; // show all bars
AddColumn( Open, "Open" );
AddColumn( High, "High" );
AddColumn( Low, "Low" );
AddColumn( Close, "Close" );
AddColumn(MA(Close,mavs), "SMA3",1.2);
AddColumn(ROC(Close,rankl),"ROC2",1.2);

22

1 Like

Thank you for your quick reply! I adjusted my SMA code and even made a new AFL-file with your code. The results were the same and not equal to yours. I don't understand how this is possible. The ROC code is correct now and works as expected (thank you for that one). Screenshot from my explorer in Amibroker for SMA (I took a built-in ticker now - AA):
image

Code:

mavs=3;
rankl=2;

Filter = 1; // show all bars
AddColumn( Open, "Open" );
AddColumn( High, "High" );
AddColumn( Low, "Low" );
AddColumn( Close, "Close" );
AddColumn(MA(Close,mavs), "SMA3",1.2);
AddColumn(ROC(Close,rankl),"ROC2",1.2);

Also visible on chart:

image

You are using very old (trial) version 6.0 of six years ago.

  1. It is not an error but implementation decision

  2. Since AmiBroker 6.03 it has been subject to change

    • AFL: Sum(array,N) outputs NULL values for indices starting from 0 upto index N-1 instead of N

    That change included MA() function
    Since AB 6.03 MA() function outputs start of array the way as seen in my example pictures above.

FYI, most recent public version is 6.38 (available to members only).

2 Likes

Thank you for this clarification!