簡體   English   中英

如何在 Google 表格中計算過去 200 天的指數移動平均線 (EMA)?

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

我正在嘗試計算股票的指數移動平均線 (EMA)。 我找到了這個公式:

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

但它是一個 function 只是為了計算簡單移動平均線。 我進行了更多研究,並從該線程中找到了一個腳本,該腳本應該是解決方案:

/**
 * 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);
}

但是當我運行它時,它與實際值相差無幾。 請您指導我如何使用腳本或公式計算 200 天后的准確 EMA,而無需迭代前一天的值,或者作為下一個選項,我們可以從過去 200 天的簡單移動平均線計算 EMA 嗎?

這是示例數據的鏈接。 U 列中,我正在逐步計算 EMA,而B 列是“GOOG”股票的簡單移動平均線,我們可以通過創建一些公式或腳本使用B 列的數據獲得 EMA 嗎?

問題:

我認為引用的公式沒有正確處理系列中的第一個元素。 時間段 0 的 EMA 值與序列本身的值相匹配。 並且由於所有 rest 的值都取決於該值,因此最終結果是錯誤的( 參考):

在此處輸入圖像描述

解決方案:

因此, 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