Conditional Moving Average

Hi,

We know that a simple Moving Average function (MA) just calculates the average of the array of the periods given. Particular data points should be considered for average calculation only if a certain condition matches. Is it possible to achieve this? Here is the code I wrote, Is there a better way of achieving it. I am even getting endless loop error for the below code. Please help.

SetBarsRequired(sbrAll);

function CustomSimpleMovingAverage(arr, per)
{
	local result, z;
	result = Null;
	
	for(z = (BarCount - 1); z > per; z--)
	{
		
		local completed_period, running_total, idx;
		completed_period = 0; running_total = 0;
		
		do
		{
			idx = (z - completed_period);

			if( NOT (H[idx] == L[idx]) ) {
				running_total += arr[idx];
				completed_period++;
			}
			
			if(completed_period >= per) break;
			
		} while(z > per OR completed_period >= per);
		
		result[idx] = (running_total/completed_period);
	}
	return result;
	
}

Thanks and Regards,
Vinay

1 Like

To do that you just need SparseCompress/SparseExpand
https://www.amibroker.com/guide/afl/sparsecompress.html
https://www.amibroker.com/guide/afl/sparseexpand.html

Example from upper link

/// @link https://www.amibroker.com/guide/afl/sparsecompress.html
only_when = ( Month() % 2 ) == 0; // even months only
x = SparseCompress( only_when, Close ); // compact sparse data
y = MA( x, 10 ); // regular calculation
y = SparseExpand( only_when, y ); // expand sparse data

Plot( C, "Price", colorDefault, styleBar );
Plot( y, "Sparse MA from even months", colorRed ); 

modify

only_when = ( Month() % 2 ) == 0; // even months only

to your condition

only_when = H != L;
3 Likes

Thank you very much. There are lot of stuffs to learn for me.