错误指定了无效的时间序列参数 - 在回测R脚本中

时间:2015-09-03 07:42:23

标签: r xts quantmod

我已经创建了这个回测试脚本及其执行但是有一个小问题。

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)))

执行此脚本时显示此错误

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

我能够在问题行中归零,并且在计算winpctx = length(x[x > 0])/length(x[x != 0])时会出现此问题。

如何解决此错误。

P.S。 效果()取自网站

1 个答案:

答案 0 :(得分:1)

问题在于这一行:

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

position只是一个向量(不是xts对象),因此调度lag.defaultlag.default只更改tsp属性(如果不存在则添加一个属性) )。这使myReturn格式错误的xts对象。

> 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

修复此问题,其他一切正常。

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