Hakki
Hakki

Reputation: 1472

Adding Indicator Quantstrat R

I would like to add custom indicator in quantstrat, but this indicator isn't calculated from price series. For example:

# Get SPY from Yahoo Finance
getSymbols("SPY", from = "2016-01-01", to = "2016-01-31", src =  "yahoo", adjust =  TRUE)
SPY <- SPY[,1:4]

#Create Indicator
set.seed(123)
indicator <- sample(seq(from = 0, to = 100, by = 5), size = nrow(SPY), replace = TRUE)

How can I add that indicator to my strategy and produce signals from it? All I have found is this basic notation of adding indicators, but is there away to add already calculated indicators?

# Add a 5-day simple moving average indicator to your strategy
add.indicator(strategy = strategy.st,
              # Add the SMA function
              name = "SMA",
              # Create a lookback period
              arguments = list(x = quote(Cl(mktdata)), n = 5),
              # Label your indicator SMA5
              label = "SMA5")

Upvotes: 1

Views: 744

Answers (1)

Cameron Giles
Cameron Giles

Reputation: 82

I like to use the "ifelse" function

   Rule1<-function(price,SMA,...)
  {ifelse(price>SMA,1,-1)}
add.indicator(strategy=strategyname,name="SMA",
          arguments=list(x=quote(mktdata$Close),n=5),label="SMA40")
add.indicator(strategyname, name="Rule1", arguments=list(price = quote(mktdata$Close), SMA=quote(mktdata$SMA.SMA5)), label="Rule1Signal")

This will give you the SMA and a column with either a 1 which you could use as a buy singal or a -1 which could be used as your sell signal.

Upvotes: 1

Related Questions