Exercise

Implementing an indicator - I

At this point, it's time to start getting into the mechanics of implementing an indicator within the scope of the quantstrat library. In this exercise you will learn how to add an indicator to your strategy. For this exercise you will use the strategy you created in earlier exercises, strategy.st. For your first indicator, you will add a 200-day simple moving average.

To add an indicator to your strategy, you will use the add.indicator(). Set strategy equal to the name of your strategy, name to the name of a function in quotes, and arguments to the arguments of the named function in the form of a list. For instance, if your function name was SMA, the arguments argument will contain the arguments to the SMA function:

add.indicator(strategy = strategy.st, 
              name = "SMA", 
              arguments = list(x = quote(Cl(mktdata)), n = 500), 
              label = "SMA500")

When referencing dynamic market data in your add.indicator() call, include mktdata inside the quote() function because it is created inside quantstrat and will change depending on whichever instrument the package is using at the time. quote() ensures that the data can dynamically change over the course of running your strategy.

In this exercise, you will add a 200-day SMA to your existing strategy strategy.st. The quantstrat and quantmod packages are also loaded for you.

Instructions

100 XP
  • Use add.indicator() on your existing strategy strategy.st. Follow the example code closely.
  • Provide the SMA function as the name argument.
  • Specify the desired arguments of SMA, using the closing price of mktdata and a lookback period n of 200 days.
  • Label your indicator "SMA200".