简体   繁体   English

如何在 Google 表格中计算过去 200 天的指数移动平均线 (EMA)?

[英]How to Calculate Exponential Moving Average (EMA) of last 200 days in Google sheets?

I am trying to calculate the Exponential Moving Average (EMA) of stock.我正在尝试计算股票的指数移动平均线 (EMA)。 I found this formula:我找到了这个公式:

=AVERAGE(INDEX(GoogleFinance("GOOG","all",WORKDAY(TODAY(),-200),TODAY()),,3))

But it is a function just to calculate Simple Moving Average.但它是一个 function 只是为了计算简单移动平均线。 I researched more and found a script from this thread that was supposed to be the solution:我进行了更多研究,并从该线程中找到了一个脚本,该脚本应该是解决方案:

/**
 * Calculates the EMA of the range.
 *
 * @param {range} range The range of cells to calculate.
 * @param {number} n The number of trailing samples to give higer weight to, e.g. 30.
 * @return The EMA of the range.
 * @customfunction
 */
function EMA(range, n) {
  if (!range.reduce) {
    return range;
  }

  n = Math.min(n, range.length);
  var a = 2 / (n + 1);

  return range.reduce(function(accumulator, currentValue, index, array) {
    return currentValue != "" ? (currentValue * a + accumulator * (1-a)) : accumulator;
  }, 0);
}

But when I run it, it is no way near the actual value.但是当我运行它时,它与实际值相差无几。 Kindly can you guide me on how to calculate accurate EMA of stock after 200 days with a script or formula without iterating each previous day's value or as a next option can we calculate EMA from the Simple Moving Average of the last 200 days?请您指导我如何使用脚本或公式计算 200 天后的准确 EMA,而无需迭代前一天的值,或者作为下一个选项,我们可以从过去 200 天的简单移动平均线计算 EMA 吗?

Here is the link to Sample Data .这是示例数据的链接。 In Column U , I am calculating EMA step by step, while Column B is the Simple Moving Average of 'GOOG' stock, can we get EMA using the data of Column B by creating some formula or script?U 列中,我正在逐步计算 EMA,而B 列是“GOOG”股票的简单移动平均线,我们可以通过创建一些公式或脚本使用B 列的数据获得 EMA 吗?

Issue:问题:

I think the referenced formula is not handling the first element in the series properly.我认为引用的公式没有正确处理系列中的第一个元素。 The value of the EMA at time period 0 matches the value of the series itself.时间段 0 的 EMA 值与序列本身的值相匹配。 And since all the rest of the values depend on that one, the end result is wrong ( ref ):并且由于所有 rest 的值都取决于该值,因此最终结果是错误的( 参考):

在此处输入图像描述

Solution:解决方案:

Therefore, the reduce function should take the first value in the series as the initial value:因此, reduce function 应该取系列中的第一个值作为初始值:

function EMA(range, n) {
  if (!range.reduce) {
    return range;
  }
  n = Math.min(n, range.length);
  const a = 2 / (n + 1);
  const first = range.shift();
  return range.reduce((accumulator, currentValue) => {
    return currentValue != "" ? (currentValue * a + accumulator * (1-a)) : accumulator;
  }, first);
}

在此处输入图像描述

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

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