Error in .xts(e, .index(e1) in quantstrat

admin

Administrator
Staff member
I get an error when running my quantmod code:
´Error in .xts(e, .index(e1), .indexCLASS = indexClass(e1), .indexFORMAT = indexFormat(e1), :
index length must match number of observations´

My code (partly from <a href="http://rbresearch.wordpress.com/2013/02/19/momentum-in-r-part-4-with-quantstrat/" rel="nofollow">http://rbresearch.wordpress.com/2013/02/19/momentum-in-r-part-4-with-quantstrat/</a>) is:

Code:
# qstratRank.R
qstratRank &lt;- function(symbols, init.equity=100000, top.N=1, 
                       max.size=1000, max.levels=1) {
  # The qstratRank function uses the quantstrat framework to backtest a
  # ranking or relative strength strategy
  #
  # args
  # symbols     : character vector of symbols
  # init.equity : initial equity
  # top.N       : trade the top N ranked assets
  # max.size    : maximum position size
  # max.levels  : maximum levels to scale in a trade
  # max.size and max.levels are passed to addPosLimit
  #
  # return value
  # returns a list: end.eq, returns, book, stats

  # remove variables
  suppressWarnings(rm("order_book.Rank", pos=.strategy))
  suppressWarnings(rm("account.Rank", "portfolio.Rank", pos=.blotter))
  suppressWarnings(rm("account.st", "port.st", "stock.str", "stratRank",
                      "initDate", "initEq", 'start_t', 'end_t'))


  # set initial variables
  initDate &lt;- "1900-01-01"
  initEq &lt;- init.equity
  port.st &lt;- "Rank"
  account.st &lt;- "Rank"

  # trade the top "N" ranked symbols
  N &lt;- top.N

  # initialize quantstrat objects
  initPortf(port.st, symbols=symbols, initDate=initDate)
  initAcct(account.st, portfolios=port.st, initDate=initDate,initEq=initEq)
  initOrders(portfolio=port.st, initDate=initDate)

  # initialize a strategy object
  stratRank &lt;- strategy("Rank")

  # there are two signals
  # the first signal is when Rank is less than or equal to N
  # (i.e. trades the #1 ranked symbol if N=1)

  stratRank &lt;- add.indicator(strategy=stratRank, name="SMA", 
                         arguments=list(x = quote(Cl(mktdata)), n=50), label="SMA50")

  stratRank &lt;- add.signal(stratRank, name="sigComparison", 
           arguments=list(columns=c("Close", "SMA50"), relationship="gt"), label="Cl.gt.SMA50")

  # the second signal is when Rank is greter than or equal to N
  # (i.e. trades the #1 ranked symbol if N=1)
  stratRank &lt;- add.signal(strategy=stratRank, name="sigThreshold", 
                          arguments=list(threshold=N, column="Rank", 
                                         relationship="gt", cross=FALSE), 
                          label="Rank.gt.N")



  # add buy rule
  stratRank &lt;- add.rule(strategy=stratRank, name='ruleSignal', 
                        arguments = list(sigcol="Cl.gt.SMA50", sigval=TRUE, 
                                         orderqty=max.size, ordertype='market', 
                                         orderside='long', pricemethod='market', 
                                         replace=FALSE, osFUN=osMaxPos), 
                        type='enter', path.dep=TRUE)



  stratRank &lt;- add.rule(strategy=stratRank, name='ruleSignal', 
                        arguments = list(sigcol="Rank.lte.N", sigval=TRUE, 
                                         orderqty=max.size, ordertype='market', 
                                         orderside='long', pricemethod='market', 
                                         replace=FALSE, osFUN=osMaxPos), 
                        type='enter', path.dep=TRUE)

  # add exit rule
  stratRank &lt;- add.rule(strategy = stratRank, name='ruleSignal', 
                        arguments = list(sigcol="Rank.gt.N", sigval=TRUE, 
                                         orderqty='all', ordertype='market', 
                                         orderside='long', pricemethod='market', 
                                         replace=FALSE), 
                        type='exit', path.dep=TRUE)

  #set max position size and levels
  for(symbol in symbols){ addPosLimit(port.st, symbol, initDate, max.size, max.levels) }

  print("setup completed")

  # apply the strategy to the portfolio
  start_t &lt;- Sys.time()
  out &lt;- try(applyStrategy(strategy=stratRank, portfolios=port.st))
  end_t &lt;- Sys.time()
  print(end_t-start_t)

  # update Portfolio
  start_t &lt;- Sys.time()
  updatePortf(Portfolio=port.st, Dates=paste('::', as.Date(Sys.time()), sep=''))
  end_t &lt;- Sys.time()
  print("trade blotter portfolio update:")
  print(end_t - start_t)

  # update account
  updateAcct(account.st)

  # update ending equity
  updateEndEq(account.st)

  # get ending equity
  eq &lt;- getEndEq(account.st, Sys.Date()) + initEq

  # view order book to confirm trades
  order.book &lt;- getOrderBook(port.st)

  # get trade statistics
  stats &lt;- tradeStats(port.st)

  # portfolio returns
  ret1 &lt;- PortfReturns(port.st)
  ret1$total &lt;- rowSums(ret1, na.rm=TRUE)

  return(list(end.eq=eq, returns=ret1, book=order.book, stats=stats))
}

I then run:

Code:
bt &lt;- qstratRank(symbols=symbols, init.equity=100000, top.N=2,
                  max.size=1000, max.levels=1)

The issue might be with my ´SMA50´ indicator, and signal and rule.
Any ideas?
Best Regards