Search code examples
rxtsquantmod

Error invalid time series parameters specified - in backtesting R script


I have created this backtesting script and its executing but has a minor problem.

library(quantmod) 
library(PerformanceAnalytics)
tickers = 'AMZN'
symbol = getSymbols(tickers,from="2014-01-01",auto.assign=F)
head(symbol)
prices=Cl(symbol)
sma.fast=SMA(prices, 10)
sma.slow=SMA(prices, 20)
buy.signal = ifelse((sma.fast> sma.slow), 1, NA)
sell.signal=ifelse((sma.fast< sma.slow), -1, NA)
position=rowSums(cbind(buy.signal,sell.signal),na.rm=TRUE)
myReturn <- lag(position) * dailyReturn(symbol)

charts.PerformanceSummary(cbind(dailyReturn(symbol),myReturn))

Performance <- function(x) {

  cumRetx = Return.cumulative(x)
  annRetx = Return.annualized(x, scale=252)
  sharpex = SharpeRatio.annualized(x, scale=252) 
  winpctx = length(x[x > 0])/length(x[x != 0])
  annSDx = sd.annualized(x, scale=252)
  DDs <- findDrawdowns(x)
  maxDDx = min(DDs$return)
  maxLx = max(DDs$length)

  Perf = c(cumRetx, annRetx, sharpex, winpctx, annSDx, maxDDx, maxLx)
  names(Perf) = c("Cumulative Return", "Annual Return","Annualized Sharpe Ratio",
                  "Win %","Annualized Volatility", "Maximum Drawdown", "Max Length Drawdown")
  return(Perf)
}
cbind(STRAT=Performance(myReturn),BMK=Performance(dailyReturn(symbol)))

when executed this script is showing this error

Error in `[.xts`(x, x > 0) : invalid time series parameters specified

I am able to zero in the problem line and its is while calculating winpctx = length(x[x > 0])/length(x[x != 0]) this problem occurs.

How to solve this error.

P.S. Performance() is taken from a website


Solution

  • The problem is this line:

    myReturn <- lag(position) * dailyReturn(symbol)
    

    position is just a vector (not an xts object) so lag.default is dispatched and lag.default simply changes the tsp attribute (adding one if it doesn't exist). That makes myReturn a malformed xts object.

    > str(lag(position))
     atomic [1:422] 0 0 0 0 0 0 0 0 0 0 ...
     - attr(*, "tsp")= num [1:3] 0 421 1
    > str(myReturn)
    Error in `[.xts`(x, 1, ) : invalid time series parameters specified
    

    Fix that, and everything else works.

    signals <- merge(buy.signal, sell.signal)
    position <- xts(rowSums(signals, na.rm=TRUE), index(signals))
    myReturn <- lag(position) * dailyReturn(symbol)
    # set 1st obs to 0 (findDrawdowns complains if there are NA in the series)
    myReturn[1] <- 0