Get startedGet started for free

Adding a moving average to financial data

One of the most popular indicators to add to a trading strategy is the 200-day simple moving average (SMA). This is a technical indicator of the average closing price of a stock over the past 200 days. Other moving averages can be of varying length, such as 50-day, 100-day, etc.

Whenever the price is above the 200-day moving average, a whole assortment of good things usually happen, such as the asset appreciating in price, low volatility, and so on. Getting a long-lasting visual might shed light on why this indicator is mentioned so often.

The TTR package has a function that calculates moving averages, SMA(), which takes in a price series x and computes the arithmetic mean over n days. A call of SMA() with a lookback window of 50 days could look like the following:

SMA(Cl(GDX), n = 50)

In this exercise, you will use the SMA() function. The quantmod and TTR packages have been loaded into your workspace, as well as the SPY object.

This exercise is part of the course

Financial Trading in R

View Course

Exercise instructions

  • Create a plot of the closing prices of SPY.
  • Use the lines() function to add a 200-day SMA of the closing prices of SPY. Color the line red by setting the col argument to "red".

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Plot the closing prices of SPY
___(___(___))

# Add a 200-day SMA using lines()
lines(___(___(___), n = ___), col = ___)
Edit and Run Code