简体   繁体   中英

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. When done like this, I get strange and discontinuous lines in red for the 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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