Skip to content
Advertisement

Do you need all the historic previous values to calculate EMA?

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.

Advertisement

Answer

I have tested with EMA20 in long series of numbers with known ema20 results, and comparing values with my algoritm, and yes, you need all the values since the begining.

In EMA with a lot of numbers like EMA200 it is not important, since old values weight is really small, but in small EMAs when high volatility it is important to calculate the ema using all the values in the historic.

So an efficient algorithm would need to store all those previous emas in a file or a database, since calculate the current ema would generate a lot of calculations, and if you have them already calculated it is just one simple operation.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement