I have a problem with some simple loop code and am hoping someone can point me in the right direction. I am using the code below to simply count the number of Closing UP days. However, in the Exploration results, I am getting Empty (or Null) values for the UpDays calculation. I think the problem is related to my use of TrendUp[i-1] in the loop code, but since I initiated TrendUp=0 prior to the loop, I don’t understand why this code won’t work. Any guidance would be appreciated. Thanks.
DayTrend = ( C - Ref( C, -1 ) > 0);
TrendUp = 0;
for ( i = 1;i < BarCount;i++ )
TrendUp[i] = DayTrend[i] + TrendUp[i-1];
UpDays = TrendUp;
Filter = 1;
AddColumn(C, "Close", 1.2);
The first thing you should be aware of is that Bar 0 does not correspond to the beginning of your date range. So, even if this code was working, the first value of Up Days reported by your exploration will not be 0 or 1 as you expect.
Second, if you’re using Pad & Align, it’s possible that DayTrend (and beyond) may be null. That means that all values of TrendUp will be null as well, because adding anything to null results in null.
Third, you don’t need to loop to achieve your goal. In fact, you should use AmiBroker’s built-in array processing whenever possible. For example, this single line of code produces what I THINK you’re trying to accomplish:
myTrendUp = Cum(IIf(Status("BarInRange"), C > Ref(C,-1), 0));
If you don’t yet understand why that code works, then you need to spend some more time studying AFL and going through the tutorials.
You could also use a single line of code to count the number of up days in a row, resetting the count to 0 each time there’s a down day. The proof is left as an exercise to the reader, but the solution involves the BarsSince function.
Thanks very much for your reply & suggestions. You found my error in the “Pad & Align” feature. I had that box checked in settings. When I uncheck the box, the code runs fine. I understand now the problem…although I had initiated the array, it only applied to the first bar in my data series, so (as you pointed out) I had null values in some of the future values. Also, your suggestion on the Cum function does indeed capture what I wanted. I appreciate the help. Thanks!
Actually, when you set TrendUp=0, it initialized the entire array. But then your looping code reassigns all elements of the array starting at TrendUp. It’s the fact that DayTrend contains nulls that caused your problems.
You are aware that your loop can be replaced by simple:
TrendUp = Cum( DayTrend );
and it would run 20x faster than loop?