Average SumSince over n periods

Hi all,

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)

Please kindly help. Thanks.

First of all this one will (almost) always be greater zero:

So your condition:

will be TRUE almost always except for cases when price and ema are equal (but that's very very seldom).


Why not using MA function?


I think you meant like this

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);

30

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);

30

2 Likes

Great thanks to the explanation and it works so perfect.

Yes should use MA concept instead of excel sumup concept. Thanks.

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