简体   繁体   中英

How to calculate Moving Average and plot the data?

Actually, I would like to use an R programme to calculate the n-days simple moving average (SMA) of the closing price with the example of Microsoft Corporation (NASDAQ: MSFT). With SMA, I could use the strategy that if SMA(20) > SMA(50), I would buy a stock of MSFT, otherwise, I sell it. Does it seem that I need to get the plot to compare? I find out I could only get the latest date's SMA:

library(quantmod)
# Get MSFT's data from its IPO date (March 13, 1986) till now.
msftData <- getSymbols("MCD",src = "yahoo", from = "1986-03-13", auto.assign = FALSE)

colnames(msftData)<-cbind("Open","High","Low","Close","Volume","Adjusted")
msftData<-as.data.frame(msftData)
attach(msftData)
fx<-function(n=1){
  cpt<-0
  for (i in 1:n){
    cpt<-cpt+(Close[length(Close)-i+1])
  }
  sma<-cpt/n
  return(sma)
}

I actually would try a function but it feels like it would not work.

smafn<-function(n=1){
cx <- c(0, cumsum(ifelse(is.na(Close), 0, Close)))
cn <- c(0, cumsum(ifelse(is.na(Close), 0, 1)))
rx <- cx[(n+1):length(cx)] - cx[1:(length(cx) - n)]
rn <- cn[(n+1):length(cx)] - cn[1:(length(cx) - n)]
rsum <- rx / rn
return(rsum)
}

The code in the question retrieves MacDonald's not Microsoft. Changing that and using chartSeries and addSMA (which adds the red moving average line) we get the chart below. Then we compute the moving average of the adjusted close. Use Cl instead of Ad if you want to use the close. (quantmod also has chart_Series with an underscore but note that the help file says that that one is experimental.)

library(quantmod)

getSymbols("MSFT", from = "1986-03-13")
chartSeries(MSFT)
addSMA(200)

ma <- SMA(Ad(MSFT), 200) # ma of adjusted close

截屏

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