Calculating Exponential Moving Average (EMA) using javascript

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.


I like recursion, so here's an example of an EMA function that uses it. No need to maintain arrays.

function weightMultiplier(N) { return 2 / (N + 1) }

function ema(tIndex, N, array) {
    if (!array[tIndex-1] || (tIndex) - (N) < 0) return undefined;
    const k = weightMultiplier(N);
    const price = array[tIndex];
    const yEMA = ema(tIndex-1, N, array) || array[tIndex-1]
    return (price - yEMA) * k + yEMA
}

The following can be another way of implementing the EMA.

var getEMA = (a,r) => a.reduce((p,n,i) => i ? p.concat(2*n/(r+1) + p[p.length-1]*(r-1)/(r+1)) : p, [a[0]]),
      data = [15,18,12,14,16,11,6,18,15,16],
     range = 3;

console.log(getEMA(data,range));