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.
Cet exercice fait partie du cours
Financial Trading in R
Instructions
- Use
add.indicator()on your existing strategystrategy.st. Follow the example code closely. - Provide the SMA function as the
nameargument. - Specify the desired arguments of SMA, using the closing price of
mktdataand a lookback periodnof 200 days. - Label your indicator
"SMA200".
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# 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 = ___)