71046

Error with applyStrategy

Question:

I am new to R and have recently encountered the following error after running applyStrategy function from quantstrat package:

Error in eval(expr, envir, enclos) : object 'signal' not found Error in `colnames<-`(`*tmp*`, value = integer(0)) : attempt to set 'colnames' on an object with less than two dimensions

Could anyone please explain to me how I can debug this error and advise if I had used sigFormula correctly to combine both MACD and RSI indicators?

Thank you for your help and please refer to the code below:

# 1. Load R Packages library(quantstrat) # 2. Stock Instrument Initialisation # 2.1 Stock Instrument Initialisation inital.portfolio.date <- '2013-12-31' start.date <- '2014-01-01' end.date <- '2017-05-31' initial.equity <- 10000 Sys.setenv(TZ="UTC") # 2.2 Download data getSymbols(Symbols = "SPY", src = "google", from = start.date, to = end.date, adjust = T, index.class="POSIXct") # 2.3 Initialise currency currency(primary_id = "USD") # 2.4 Initialise Stock Instrument stock(primary_id = "SPY", currency = "USD", multiplier = 1) # 3. Strategy Visualisation and Details # MACD & RSI Strategy lineChart(SPY, theme = "white") addMACD(fast = 12, slow = 26, signal =9, type = "EMA") addRSI(n = 14, maType = "EMA") # 4. Strategy Initialisation # 4.1 Strategy Name WT.Strat1 <- "Wen Ting's MACD & RSI Strategy" # 4.2 Clear Strategy Data rm.strat(WT.Strat1) # 4.3 Strategy Object strategy(name = WT.Strat1, store = TRUE) # 4.4 Summary of Completed Strategy Object summary(getStrategy(WT.Strat1)) # 5. Strategy Definition # 5.1 Add Indicators add.indicator(strategy = WT.Strat1, name = "MACD", arguments = list(x = quote(Cl(SPY)), nFast = 12, nSlow = 26, nSig = 9), label = "MACD") add.indicator(strategy = WT.Strat1, name = "RSI", arguments = list(price = quote(Cl(SPY)), n = 14), label = "RSI") # 5.2 Add Strategy Signals add.signal(strategy = WT.Strat1, name = "sigFormula", arguments = list(columns = c("macd","signal","RSI"), formula ="(signal > macd) & (RSI < 30)", cross = FALSE, label = "trigger"), label = "BuySignal") add.signal(strategy = WT.Strat1, name = "sigFormula", arguments = list(columns = c("macd","signal","RSI"), formula ="(signal < macd) & (RSI > 70)", cross = FALSE, label = "trigger"), label = "SellSignal") # 5.3 Add Buy Rule add.rule(strategy = WT.Strat1, name = "ruleSignal", arguments = list(sigcol = "BuySignal", sigval = TRUE, orderqty = 10, ordertype = "market", orderside = "long"), type = "enter", label = "BuyRule", enabled = TRUE) # 5.4 Add Sell Rule add.rule(strategy = WT.Strat1, name = "ruleSignal", arguments = list(sicol = "SellSignal", sigval = TRUE, orderqty = all, ordertype = "market", orderside = "long", TxnFees = -6), type = "exit", label = "SellRule", enabled = TRUE) # 5.5 Completed Strategy Object summary(getStrategy(WT.Strat1)) # 6. Portfolio Initialisation # 6.1 Portfolio Name WT.Portfolio1 <- "Wen Ting's Portfolio 1" # 6.2 Clear Portfolio Data rm.strat(WT.Portfolio1) # 6.3 Initialise Portfolio Object initPortf(name = WT.Portfolio1, symbols = "SPY", initDate = inital.portfolio.date) # 6.4 Initialise Account Object initAcct(name = WT.Strat1, portfolios = WT.Portfolio1, initDate = inital.portfolio.date, initEq = initial.equity) # 6.5 Initialise Orders Object initOrders(portfolio = WT.Portfolio1, initDate = inital.portfolio.date) # 7. Strategy Application # 7.1 Strategy Application to Market Data applyStrategy(strategy = WT.Strat1, portfolios = WT.Portfolio1)

Answer1:

Try these corrections to your code block:

add.signal(strategy = WT.Strat1, name = "sigFormula", arguments = list(columns = c("macd.MACD","signal.MACD","EMA.RSI"), formula ="(signal.MACD > macd.MACD) & (EMA.RSI < 30)", cross = FALSE, label = "trigger"), label = "BuySignal") add.signal(strategy = WT.Strat1, name = "sigFormula", arguments = list(columns = c("macd.MACD","signal.MACD","EMA.RSI"), formula ="(signal.MACD < macd.MACD) & (EMA.RSI > 70)", cross = FALSE, label = "trigger"), label = "SellSignal")

How to debug this error you ask? Here is a quick way:

First try calling traceback()

> traceback() 8: stop("attempt to set 'colnames' on an object with less than two dimensions") 7: `colnames<-`(`*tmp*`, value = seq(ncol(tmp_val))) 6: applySignals(strategy = strategy, mktdata = mktdata, parameters = parameters, ...) 5: applyStrategy(strategy = WT.Strat1, portfolios = WT.Portfolio1) at .active-rstudio-document#86 4: eval(ei, envir) 3: eval(ei, envir) 2: withVisible(eval(ei, envir)) 1: source("~/.active-rstudio-document", echo = TRUE)

You can see that there is something wrong in applySignals inside your call to applyStrategy (which runs the backtest) so you know it has something to do with your signal related data. (If it were applyIndicators it would be something to do with your indicator logic, if it were applyRules you know it's probably to do with your rule logic)

applyStrategy adds to the global environment a mktdata object which you can inspect, even if the full simulation is not successful.

try head(mktdata):

> head(mktdata) SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume macd.MACD signal.MACD EMA.RSI 2014-01-02 183.98 184.07 182.48 182.92 119636836 NA NA NA 2014-01-03 183.21 183.60 182.63 182.88 81390502 NA NA NA 2014-01-06 183.47 183.56 182.08 182.36 108028139 NA NA NA 2014-01-07 183.09 183.79 182.95 183.48 86144169 NA NA NA 2014-01-08 183.45 183.83 182.89 183.52 96582234 NA NA NA 2014-01-09 184.10 184.13 182.80 183.64 90683302 NA NA NA

Ah, you can see your column names are not actually signal, macd, but rather signal.MACD and macd.MACD. You need to specify the column names correctly in the sigFormula logic.

And that is one quick way to debug quantstrat. Inserting browser() in the code is the next level of detail you could use if you can't figure out the problem ....

If you try running the backtest with the correct column names, things will then work.

Recommend

  • Forward declaration being ignored?
  • itext 7.1 how to check if image is rotated
  • Continuous colorbar with contour levels
  • VBA: Choosing Specific Tab on Internet Explorer
  • Add click to imagebutton inside gridview dynamically
  • When casting an int64 to uint64, is the sign retained?
  • Semi-circle donut pie chart with labels (data names) and %-ages on the pie … and data numbers on mou
  • Core Data Optimize Fetch Request
  • WPF Prism RegisterTypeForNavigation with viewmodel type
  • What does {0} stands for in Console.WriteLine?
  • Codeigniter sending email to multiple email ids, file attachment is not going with emails
  • How to access images in UIATablecell
  • Python ImportError- what is wrong here?
  • Bluetooth on Raspberry Pi Zero W, using buildroot
  • Why does GetAttr not work on cloudformation template parameters?
  • The initialization of non-local non-inline variables: does it take place strictly before the `main()
  • Getting this “org.xhtmlrenderer.render.BlockBox cannot be cast to org.xhtmlrenderer.newtable.TableBo
  • Where to store larger data for Outlook Web App?
  • disable EJS caching in production
  • How do I use Promise.all() with chrome.storage()?
  • How to retrieve data from Firebase Database with join if key only return true?
  • How to override C# DateTime serialization with class auto-generated from wsdl?
  • Deleting/“Rebasing” rails migrations
  • Web API Routing - Overloaded GET method causes 405 Method Not Allowed for other verbs
  • How to render a react component on any other page other than index.html
  • Get an image from the video
  • Wrap array elements in divs based on same value
  • using vtkTimerCallback with QVTKRenderWindowInteractor not working
  • Background beacon detection and Notification (Both iOS and Android) for Eddystone beacon?
  • Avoiding duplicated data in same table with jquery
  • Azure NodeJS Error: ENOENT, open 'D:\\home\\site\\wwwroot\\bin\\views\\'
  • How to organize this layout with overflows?
  • separate tokens in batch file
  • Building JavaFX 2.0 App on Mac, deploying on Windows
  • How to use Streams api peek() function and make it work?
  • How to decleare char *const argv[] in swift [duplicate]
  • How to get rgb from transparent pixel in js
  • WPF custom control and direct content support