Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 382
Jorman Franzini Avatar asked Oct 15 '16 08:10

Jorman Franzini


3 Answers

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.

like image 97
Daniel Reina Avatar answered Oct 20 '22 01:10

Daniel Reina


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
}
like image 39
4UmNinja Avatar answered Oct 19 '22 23:10

4UmNinja


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));
like image 32
Redu Avatar answered Oct 19 '22 23:10

Redu