I would like to calculate a column --720-period mean of spread. Below is the code after research on some sumsince posts.

periods_ema = 50;
spread= abs(( Close - EMA( Close, periods_ema ) )/EMA( Close, periods_ema ));
prevbars = 720; // bars range to sum up 720 trading days
condition = spread>0;
Avg_spread = SumSince(Ref(condition, -prevbars), condition)/prevbars;
Filter = 1;
AddColumn(Avg_spread, "720-period MEAN of SPREAD",1.3);

The result show in "Explore" window is completely incorrect. ( I have do the manual calculation in excel where spread data is correct and it is easy to use average() in excel...I dont know how to average an array over n periods in amibroker)

prevbars = 720; // bars range to sum up 720 trading days
greater_zero = spread>0;
// if spread greater zero then use spread else set to zero
filtered_spread = IIf(greater_zero, spread, 0);
// average if spread greater zero
Avg_spread = MA(filtered_spread,prevbars);

So entire code:

periods_ema = 50;
e_ma = EMA( Close, periods_ema );
spread= /*abs*/((Close - e_ma)/e_ma);
prevbars = 720; // bars range to sum up 720 trading days
greater_zero = spread>0;
// if spread greater zero then use spread else set to zero
filtered_spread = IIf(greater_zero, spread, 0);
// average if spread greater zero
Avg_spread = MA(filtered_spread,prevbars);
Plot( spread, "spread", colorGold );
Plot( Avg_spread, "Avg_spread", colorRed);
PlotGrid(0, colorRed);
Filter = 1;
AddColumn(Avg_spread, "720-period MEAN of SPREAD",1.3);

Or only output filtered spread

periods_ema = 50;
e_ma = EMA( Close, periods_ema );
spread= /*abs*/((Close - e_ma)/e_ma);
prevbars = 720; // bars range to sum up 720 trading days
greater_zero = spread>0;
// if spread greater zero then use spread else set to zero
filtered_spread = IIf(greater_zero, spread, 0);
// average if spread greater zero
Avg_spread = MA(filtered_spread,prevbars);
//Plot( spread, "spread", colorGold );
Plot( filtered_spread, "filtered_spread", colorBrightGreen );
Plot( Avg_spread, "Avg_spread", colorRed);
PlotGrid(0, colorRed);
Filter = 1;
AddColumn(Avg_spread, "720-period MEAN of SPREAD",1.3);