我试图计算股票的指数移动平均(EMA)。我找到了这个公式:
=AVERAGE(INDEX(GoogleFinance("GOOG","all",WORKDAY(TODAY(),-200),TODAY()),,3))
但它是一个函数,仅仅是计算简单的移动平均。我做了更多的研究,并从这个线程中找到了一个应该是解决方案的脚本:
/**
* 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天后股票的准确均线,而不迭代前一天的值,或者作为下一个选项,我们能从过去200天的简单移动平均值中计算EMA吗?
这是指向样本数据的链接。在列U中,我正在逐步计算EMA,而列B是'GOOG‘股票的简单移动平均,我们可以通过创建一些公式或脚本来利用列B的数据来获得EMA吗?
发布于 2022-08-25 08:47:54
问题:
我认为引用的公式不是正确处理系列中的第一个元素。时间段0的EMA值与序列本身的值相匹配。由于所有其余的值都依赖于该值,所以最终结果是错误的(参考):
解决方案:
因此,reduce
函数应该将系列中的第一个值作为初始值:
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);
}
https://stackoverflow.com/questions/73469913
复制相似问题