Search code examples
rxtszoo

unable to add moving average line to stock price time series plot


I need to plot stock price chart and add moving average line on top of that. I tried the code below to generate the plot. But for some reason, the ma line do not show on the plot. I'm very confused. Does anyone know what I did wrong in thecode? why ma line does not show up?

library(quantmod)
library(forecast)
library(xts)
library(zoo)
start <- as.Date('2018-01-01')
end <- as.Date('2018-02-13')
getSymbols('APPL', src='yahoo', from=start, to=end)
appl <- APPL[, 'APPL.Adjusted']

plot(appl)
sma = ma(appl, order=20)
lines(sma, col='red')

Solution

  • Use the following to convert the ts (obtained from applying the ma() function) to an xts object:

    sma = xts(ma(aapl, order=20), order.by=index(appl))
    lines(sma, col='red')
    

    The plot() object will now be able to add the moving average (MA) to the plot.

    Bear in mind that ma() does some adjustment to center an even-order MA such as yours. It does this by applying two non-centered MA's to the data, one of order 20 and the second of order 2. So the following is equivalent to the MA that you calculated:

    ma( ma(appl, 20, centre=F), 2, centre=F)