Finding down days

Hola AB denizens,

I'd like to have an array returned in which down days = one and other days equal zero.

What is there a difference between these two lines?

downDay = IIf(Close < Ref(Close, -1), 1, 0);
downDay = Close < Ref(Close, -1)

The second is intuitive to me, both work as expected.

Is there a better way?

Long explanations welcome.

Best,

 John

There is no difference. Second one returns array of zeroes and ones too. Iif() is not required.

"Better" a la "Shorter"?

downDay = ROC(C,1) < 0;

Well, it's not really shorter if you do this one

downDay = C < Ref(C,-1);
2 Likes

Well there is a difference. Shorter one (without IIf) is better because it does not do useless thing and is faster. The one with IIF() is simply redundant. It is like saying "if yes then yes else no".

In AFL "yes" (true) is 1 and "no" (false) is zero. Therefore there is absolutely no reason to use IIF in that case.

2 Likes

Just for the record and to avoid misunderstanding... by "There is no difference" I was referring to the resulting "downDay" array being filled with same 1 or 0 content at same locations in the array in both cases. Resulting conclusion... Iif() not necessary in first line.
So since second line is less code resulting in very same outcome it is preferable one. But I understand that some newbies would find first line better readable as it looks like a sentence telling what shall be done.

2 Likes

When I started out, I didn't realize its full potential but the IIf() is a really useful and powerful function.

In most cases, when the Vector needs to be processed in a single iteration, then the plain line

downDay = Close < Ref(Close, -1);

would simply suffice as discussed by the Veterans above :slight_smile:

A practical example of the Power of IIf() would be in these two examples which make a vast difference in computation cycles required and more efficient.

One of the best examples is explained here:
http://www.amibroker.org/userkb/2007/04/20/plotting-trade-zigzag-lines/

CombinedLine = IIf( IsNull( la ), CombinedLine, la );

This single Line computes and stores each individual segment of Line Array into the CombineLine Array and the result is to call the Plot() function just once at the end.

As opposed to running Plot() for each bar in the less efficient code

Plot( LineArray( x0, x1, y0, y1 ), "", Co, 1 );

Another example I'd bookmarked was its use here:

3rd Last line from the bottom

result = IIf( period == p, ind, result );

Another example when the results can be computed in a Loop and accumulated in a single Array Variable for later use.

The manual for IIf() explicitly explains how it works as a function with a code snippet that shows how it is implemented internally and that the condition is tested for each bar and the resultant array indexes are populated with the True or False values provided.

Just my thoughts if someone else ever landed here.

4 Likes