Code Ambiguity

momentumPeriod = Param("Momentum Period", 10, 5, 20, 1);
momentum = (C / (Ref(C, momentumPeriod) + 1e-10) - 1) * 100; // % change

Hi, is the above code correct? Does the code lookback or look into the future?

I check on several AI its correct but Amibroker give warning 1001 the function ref() used here may be looking into the future 10 bars and result return is also not correct.

Can anyone help?

Refer the manual.
Positive values which you are using will reference the future.
Use negative if you want to refer to past bars.

1 Like

@Cubocubo, in addition to the correct answer from @nsm51, take a look at this modified code:

momentumPeriod = Param( "Momentum Period", 10, 5, 20, 1 );
momentum = ( C / ( Ref( C, -momentumPeriod ) /*+ 1e-10 */ ) - 1 ) * 100; // % change
rocxbars = ROC( C, momentumPeriod );

Filter = 1;
AddColumn( momentum, "Mom" );
AddColumn( rocxbars, "RocXBars" );

The Ref() function requires a negative value to reference past bars, so in my example I added a minus sign.

That said, your second line may not be necessary at all, because AmiBroker AFL already provides a built-in function to calculate the rate of change for a given period: ROC (as shown in the snippet).

Also, in this case there’s no need to add +1e-10 to the denominator, since you’re using Close prices, which will never be zero. More generally, when you do need to guard against potential division by zero in AFL, you can use the function SafeDivide().

Finally, I added a simple exploration to confirm that your (modified) line and the ROC function produce the same results.

While AI models can be helpful, I strongly recommend also getting familiar with the AmiBroker documentation and regularly checking the list of available AFL functions.

3 Likes

Cool Nsm and beppe...Many thanks, indeed AI can sometimes add confusion...

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