I'm calculating EMA for some prices series using PHP.
Moving Averages in wikipedia
WHAT IS EMA?
Imagine that you have an array with 5000 elements, and you want to calculate EMA 10.
Compated with SMA, in SMA you only need to get the last 10 values and calculate the average, but in EMA you need the previous EMA value for new calculation. First EMA value is the SMA number of elements required.
My question is, do you need to process the 5000 previous values for EMA?
As i said it uses the previous value for next calculation, in theory you must but it can be a problem when you have for example 5 millions of registers.
Or is it just enough to get the items from $n-20 to $n-11, calculate the SMA, and then apply EMA for last 10 values?.
Additionally old values is EMA are deprecated faster, because it uses Alpha for that. I have created the next function to calculate EMA:
function EMA($v,$lastvalue,$num=200)
{
if($num>(count($v)-1))
return FALSE;
$MA=0;
$initMA=count($v)-2*$num;
if($initMA<0)
$initMA=0;
for($i=0,$j=$initMA;$i<$num;$i++,$j++)
$MA+=$v[$j];
$EMA=$MA/$num;
$a = 2/ ($num + 1);
for($i=$j;$i<count($v)-1;$i++)
$EMA = $a * $v[$i+1]+ (1-$a) * $EMA;
$EMA = $a * $lastvalue+ (1-$a) * $EMA;
return $EMA;
}
Thanks in advance.