简体   繁体   English

使用r中的循环创建移动平均线

[英]Create a moving average using a loop in r

Here's my current code: 这是我目前的代码:

n<-30
alpha<- 2/(1+n)
alpha
length(stocks$Close)
thirty <- colMeans(matrix(stocks$Close [1:30]))
x<-rep(0, length=6656)
for (i in 30:length(x)){
    x[i]<- ((alpha*thirty) + (Close[i-1]*(1-alpha)))
}

I need to substitute in the average for the first 30 days of closing values into the 30th member of the new vector. 我需要将关闭值的前30天的平均值替换为新向量的第30个成员。 Also, I'm supposed to start my new vector on day 30, beginning with that average value, and move forward with the formula: EMA[i]= ((P[i] alpha)+(EMA[i-1] (1-alpha)). P[i] is the closing price at the end of that time period. Given that we're starting the whole model on day thirty with the new value subbed in for i=30, I'm guessing that the whole thing will need to be adjusted. How do you insert that average on the 30th member and shift the model forward? 此外,我应该在第30天开始我的新矢量,从该平均值开始,然后继续使用公式:EMA [i] =((P [i] alpha)+(EMA [i-1] ( 1-alpha))。P [i]是该时间段结束时的收盘价。鉴于我们在第30天开始整个模型,新值为i = 30,我猜测整个事情需要调整。如何在第30个成员上插入平均值并将模型向前移动?

What you looking for is this: You need to access the curret price as P[i], so 30th, 31st etc. 你在寻找的是:你需要以P [i],30th,31st等方式获取当前价格。

   for (i in 30:length(x)){
        x[i]<- ((alpha*P[i]) + (x[i-1]*(1-alpha)))
    }

Then for the first 29 days you can add the original prices 然后在前29天您可以添加原始价格

x[1:29]=Close[1:29]

to make it complete 使它完整

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

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