[英]Writing a sum from 0 to n in R for EWMA
I am trying to write the following sum in R but no success so far.我正在尝试在 R 中编写以下总和,但到目前为止没有成功。 The sum I am trying to write is the following:
我想写的总和如下:
from t=0 to t=260, Rt * Lambda^t * (1-Lambda)
从 t=0 到 t=260,Rt * Lambda^t * (1-Lambda)
Rt represents the returns at time t, Lambda is a decay coefficient (=0.97 but subject to change). Rt 代表时间 t 的回报,Lambda 是衰减系数(=0.97 但可能会发生变化)。
I have a time series data frame and want to apply the result of this sum for every row of the data frame.我有一个时间序列数据框,并希望将此总和的结果应用于数据框的每一行。 this means that for any row i, t=0 and for row i-1, t=1, row i-2, t=2 and so on.
这意味着对于任何行 i,t=0 和行 i-1,t=1,行 i-2,t=2 等等。
Thank you very much for the help非常感谢你的帮助
in R you do not need loops to calculate such sums.在 R 中,您不需要循环来计算这样的总和。 You can simply use
sum
:您可以简单地使用
sum
:
sum(as.numeric(rt) * lambda^(seq_along(rt) - 1) * (1-lambda))
Here is some toy data:以下是一些玩具数据:
set.seed(1)
rt <- ts(rnorm(261))
lambda <- 0.97
You can also check out the EMA
function from the TTR
package.您还可以从
TTR
包中查看EMA
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.