How to calculate Moving Average and plot the data?

0

Issue

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)
}

Solution

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

screenshot

Answered By – G. Grothendieck

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More