Moving Averages Strategy Indicators with R

Last Update: February 6, 2020

Strategy indicators consist of identifying trend-following or mean-reversion asset price patterns. Main indicators include single or multiple, lagging or leading technical indicators.

This topic is part of Quantitative Trading Analysis with R course. Feel free to take a look at Course Curriculum.

This tutorial has an educational and informational purpose and doesn’t constitute any type of trading or investment advice. All content, including code and data, is presented for personal educational use exclusively and with no guarantee of exactness of completeness. Past performance doesn’t guarantee future results. Please read full Disclaimer.

An example of trend-following lagging strategy indicators is simple moving average which consists of asset prices overlay for identifying uptrends and downtrends.

1. Strategy indicator calculation.

sma_{k}\left ( c \right )_{t}=\frac{1}{k}\sum_{i=0}^{k-1}\left ( c_{t-i} \right )

Where c_{t} = current period asset close prices, sma_{k}\left ( c \right )_{t} = current period close prices k periods simple moving average.

2. R script code example.

2.1. Load R packages [1].


2.2. Moving averages strategy indicators data reading.

  • Data: S&P 500® index replicating ETF (ticker symbol: SPY) daily open, high, low, close, adjusted close prices and volume (2016).
SPY <- read.csv('Moving-Averages-Strategy-Indicators-Data.txt',header=T)
SPY <- xts(SPY[,2:7],[,1]))

2.3. Moving averages strategy indicators calculation and chart.

  • Moving averages strategy indicators number of periods not fixed and only included for educational purposes.
sma <- cbind(SPY$SPY.Close,SMA(SPY$SPY.Close,5),SMA(SPY$SPY.Close,20))
colnames(sma) <- c('SPY.Close','SMA(5)','SMA(20)')
3. References.

[1] Joshua Ulrich. “TTR: Technical Trading Rules”. R package version 0.23-5. 2019.

Jeffrey A. Ryan and Joshua M. Ulrich. “quantmod: Quantitative Financial Modelling Framework”. R package version 0.4-15. 2019.