rquantstrat

Error with using add.indicator() in Quantstrat


I am really despairing of this problem and I haven't found any solution. If i remove the last call to add.indicator applyIndicators and thus the backtest will function, but this way I always run in the runSum error message.

Someone with an idea?

# load necessary packages
library(quantstrat)
library(quantmod)

# initialize basic settings
initdate = "1999-01-01"
from = "2003-01-01"
to = "2015-12-31"
currency("USD")
stock("SPY", currency = "USD")
Sys.setenv(TZ = "UTC")

tradesize <- 100000
initeq <- 100000
strategy.st <- portfolio.st <- account.st <- "firststrat"

# load market data from yahoo finance
getSymbols ("SPY", from = from,
            to = to, src = "yahoo",
            adjust = TRUE,
            index.class=c("POSIXt","POSIXct"))

# initialize portfolio, account, orders and strategy
rm.strat(strategy.st)

initPortf(portfolio.st,
          symbols = "SPY",
          initDate = initdate,
          currency = "USD")

initAcct(account.st,
         portfolios = portfolio.st,
         initDate = initdate,
         currency = "USD",
         initEq = initeq)

initOrders(portfolio.st, initDate = initdate)

strategy(strategy.st, store = TRUE)

# add the strategy's backbone: indicators, signals and rule
add.indicator(strategy = strategy.st,
              name = "SMA",
              arguments = list(x = quote(Cl(mktdata)), n = 20),
              label = "SMAClose")
add.indicator(strategy = strategy.st,
              name = "SMA",
              arguments = list(x = quote(Op(mktdata)), n = 20),
              label = "SMAOpen")
add.indicator(strategy = strategy.st,
              name = "SMA",
              arguments = list(x = quote(Hi(mktdata)), n = 200),
              label = "SMA200")
add.indicator(strategy = strategy.st,
              name = "SMA",
              arguments = list(x = quote(Cl(mktdata)), n = 10),
              label = "SMA10")

applyIndicators(strategy.st, SPY)
Fehler in runSum(x, n) : ncol(x) > 1. runSum only supports univariate 'x'

Solution

  • The error indicates your x variable is multivariate. If you run head(x) you will see the series'

        Browse[1]> head(x)
                   SPY.Close SMA.SMAClose
        2003-01-02  70.37356           NA
        2003-01-03  70.58992           NA
        2003-01-06  71.83404           NA
        2003-01-07  71.65631           NA
        2003-01-08  70.62083           NA
        2003-01-09  71.71812           NA
    

    The problem stems from the label "SMAClose" in your first indicator. The Cl() function from quantmod uses grep and a pattern "Close" to identify Close prices. By the time you try to create your 4th indicator, you have 2 columns with the name "Close" in your mktdata object...so both are returned and SMA errors out. Simply naming the first indicator "SMACl20" or anything without the word "Close" will work fine for your above code. HTH.