量子定制的自定义指示器功能

时间:2016-06-26 20:32:28

标签: r quantstrat

我在编写用于quanstrat::add.indicator

的自定义指标功能时遇到问题

错误:

Error in inherits(x, "xts") : object 'price' not found 

我的代码:

library(quantstrat)
symbols<-getSymbols("USD/EUR",src="oanda")
strat<-acct<-portfolio<-"tempTest"
initEq<-1000

initDate <- '2009-12-31'
currency("USD")
exchange_rate(symbols, currency="USD")
rm.strat(strat) # remove portfolio, account, orderbook if re-run
initPortf(name=portfolio, symbols, initDate=Sys.Date())
initAcct(name=acct, portfolios=portfolio,initDate=Sys.Date(), initEq=initEq)
initOrders(portfolio=portfolio, initDate=Sys.Date())
strategy(strat, store=TRUE)

colnames(USDEUR)<-"Close"
#################################################################################################

RSI.lagged<-function(lag=1,n=2,...){
  RSI <- RSI(price)
  RSI <- lag(RSI, lag)
  out <- RSI$rsi
  colnames(out) <- "rsi"
  return(out)
}

########RSI indicator
####THIS IS LAGGED TO PREVENT FOREKNOWLEDGE
add.indicator(strat, name="RSI.lagged", arguments=list(price = quote(Cl(mktdata)), n=2), label="rsiIndLagged")
test <- applyIndicators(strat, mktdata=USDEUR)

将参数price添加到RSI.lagged函数后,例如RSI.lagged<-function(lag=1,n=2,price,...),我收到错误:

Error in `colnames<-`(`*tmp*`, value = "rsi") : attempt to set 'colnames' on an object with less than two dimensions 

1 个答案:

答案 0 :(得分:2)

您试图访问不存在的列的名称。试着这样做,让你的指标工作:

RSI.lagged<-function(price, lag=1,n=2,...){
  # Stick in a browser to see your problem more clearly:
  # browser()
  rsi <- RSI(price)
  rsi <- lag(rsi, lag)
  # This column name does not exist: "rsi".  The name of the column gets the default "EMA"
  # tail(rsi)
  #                 EMA
  # 2017-11-04 63.48806
  # 2017-11-05 66.43532
  # 2017-11-06 64.41188
  # 2017-11-07 66.02659
  # 2017-11-08 67.96394
  # 2017-11-09 66.08134
  colnames(rsi) <- "rsi"
  return(out)
}

(除此之外,还强烈建议您不要尝试使用Oanda数据进行回溯测试,因为价格不是“真实的”;它们是每天的加权平均价格。请参阅:Exact time stamp on quantmod currency (FX) data