简体   繁体   English

R语言前循环简单矢量算法不适用于时间序列

[英]R-Language For-Loop Simple Vector Arithmetic Not Working for a Time Series

I am trying to make a simple moving average (SMA) of GOOG stocks. 我正在尝试对GOOG股票进行简单的移动平均线(SMA)。 When done like this, I get strange and discontinuous lines in red for the SMA: 像这样完成后,对于SMA,我会得到奇怪且不连续的红色线条:

frame()
rm(list=ls())

#Value of securities in GOOG
GOOG=read.csv(file="GOOG.csv", head=TRUE, sep=",")
plot(x=GOOG$Close, type="l", ylab="GOOG Closing Prices",xlab="Time")
SMA=GOOG$Close

#5 Day SMA in RED
for(i in 1:84)
{
  segments(x0=i,y0=mean(SMA[i:i+4]),
       x1=i+1, y1=mean(SMA[i+1:i+5]),
       col="red")
}

However, when I replace mean(SMA[i:i+4]) with (SMA[i]+...+SMA[i+4])/5 (and same with replacing mean(SMA[i+1:i+5])), the values work out fine and the SMA graph is smooth and continuous, as it should be. 但是,当我用(SMA [i] + ... + SMA [i + 4])/ 5代替均值(SMA [i:i + 4])/ 5(与替换均值(SMA [i + 1:i]相同+5])),这些值可以很好地工作,并且SMA图是应该平滑且连续的。

But arent these two values the same thing? 但是,这两个值是否相同? How can I correct this issue while still keeping the shorthand way of writing the average? 我如何纠正这个问题,同时又保持写平均值的捷径?

Try: 尝试:

#5 Day SMA in RED
for(i in 1:84)
{
  segments(x0=i,y0=mean(SMA[i:(i+4)]),
       x1=i+1, y1=mean(SMA[(i+1):(i+5)]),
       col="red")
}

*(Added parentheses) *(加括号)

Careful with your indices. 小心您的索引。

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

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