Pastor Soto
Pastor Soto

Reputation: 386

How to add a simple moving average from all data on quantmod and subset the chart?

I have data from SPY I want to add a 200 simple moving average, the thing is that I want to plot only a specific timeframe but I want that the moving average took all data into consideration so I can see it. Like a regular chart on tradingview when you plot the data and you see the moving average from all data but you can see how it looks on a specific length of time. This code doesn't work since I subset the data and I don't have all the range of values to calculate the indicator.

library(quantmod)
getSymbols("SPY", from="2016-01-01", to="2020-01-01")
chartSeries(SPY, subset = "2017-11-18::2017-12-16")
addSMA(n=200, on=1, col = "blue")

I want to plot the data from 2017-11-18 to 201712-16 but I want the moving average takes the values of all the available data.

Upvotes: 2

Views: 642

Answers (1)

phiver
phiver

Reputation: 23608

You can add the SMA without an issue, but the reason you are not seeing it is because it falls out of the shown y-range of the the SPY data.

If you set the y-range manually you would see it.

chartSeries(SPY, subset = "2017-11-18::2017-12-16", yrange = c(240, 280))
addSMA(n=200, on=1, col = "blue")

But better would be to use the chart_Series functions. Adding the SMA then will automatically shift the y-range to include the SMA.

chart_Series(SPY, subset = "2017-11-18::2017-12-16")
add_SMA(n=200, on=1, col = "blue")

The only disadvantage of the chart_Series functions is that they are not really well documented. But there is a lot of info on SO about them.

Upvotes: 2

Related Questions