开始使用免费开始使用

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.

本练习是课程的一部分

Financial Trading in R

查看课程

练习说明

  • 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".

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Add a 200-day SMA indicator to strategy.st
add.indicator(strategy = ___, 
              
              # Add the SMA function
              name = ___, 
              
              # Create a lookback period
              arguments = list(___), 
              
              # Label your indicator SMA200
              label = ___)
编辑并运行代码