1

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")
Hakki
  • 1,440
  • 12
  • 26

1 Answers1

1

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.

Cameron Giles
  • 72
  • 1
  • 8
  • #camerongiles doesn’t your solution still rely on the SPY prices? Like #Viitama, we have external data data and are struggling to use it in quantstrat. – W Barker Jul 12 '19 at 01:37
  • See also: https://stackoverflow.com/questions/41287566/r-loading-external-indicators-into-quantstrat# – W Barker Jul 14 '19 at 11:44