Search code examples
javascriptarraysmoving-average

Calculating Exponential Moving Average (EMA) using javascript


Hi Is possible to calculate EMA in javascript?

The formula for EMA that I'm trying to apply is this

EMA = array[i] * K + EMA(previous) * (1 – K)

Where K is the smooth factor:

K = 2/(N + 1)

And N is the Range of value that I wanna consider

So if I've an array of value like this, and this value grow during the times:

var data = [15,18,12,14,16,11,6,18,15,16];

the goal is to have a function, that return the array of the EMA, because any of this value, expect the very fist "Range" value, have this EMA, for each item on data, I've the related EMA value. In that way I can use all or use only the last one to "predict" the next one.

function EMACalc(Array,Range) {
var k = 2/(Range + 1);
...
}

I can't figure out how to achieve this, any help would be apreciated


Solution

  • I don't know if I completely understood what you need, but I will give you the code for a function that returns an array with the EMA computed for each index > 0 (the first index doesn't have any previous EMA computed, and will return the first value of the input).

    function EMACalc(mArray,mRange) {
      var k = 2/(mRange + 1);
      // first item is just the same as the first item in the input
      emaArray = [mArray[0]];
      // for the rest of the items, they are computed with the previous one
      for (var i = 1; i < mArray.length; i++) {
        emaArray.push(mArray[i] * k + emaArray[i - 1] * (1 - k));
      }
      return emaArray;
    }
    

    This should do it.