简体   繁体   English

使用 javascript 计算指数移动平均线 (EMA)

[英]Calculating Exponential Moving Average (EMA) using javascript

Hi Is possible to calculate EMA in javascript?嗨 可以在javascript中计算EMA吗?

The formula for EMA that I'm trying to apply is this我试图应用的 EMA 公式是这样的

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

Where K is the smooth factor:其中 K 是平滑因子:

K = 2/(N + 1) K = 2/(N + 1)

And N is the Range of value that I wanna consider N 是我要考虑的值范围

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.目标是有一个函数,返回 EMA 的数组,因为这个值中的任何一个,期望第一个“范围”值,有这个 EMA,对于数据上的每个项目,我有相关的 EMA 值。 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我不知道如何实现这一点,任何帮助都会受到赞赏

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). 我不知道我是否完全理解你需要什么,但我会给你一个函数的代码,该函数返回一个数组,其中每个索引计算的EMA> 0(第一个索引没有任何先前的EMA计算,并且将返回输入的第一个值)。

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. 这应该做到这一点。

The following can be another way of implementing the EMA. 以下可以是实现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)); 

I like recursion, so here's an example of an EMA function that uses it.我喜欢递归,所以这里有一个使用它的 EMA 函数的例子。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM