【问题标题】:Custom indicator function for quantstratquantstrat 的自定义指标函数
【发布时间】:2016-10-28 19:34:29
【问题描述】:

我在编写用于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&lt;-function(lag=1,n=2,price,...) 我得到错误:

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

【问题讨论】:

  • add.indicator 函数在哪里?您显示代码的唯一函数是RSI.lagged(如果您希望它在其中使用price,那么您应该传入一个名为price的参数),但您不会显示任何调用它的代码。
  • 抱歉,library(quantstrat) 是必需的库。我已编辑我的代码以包含此内容。
  • 我还是一头雾水——我相信您回复了我评论的前 5 个字,但忽略了其他 40 个字。还是我错过了什么?
  • 我的印象是... 意味着add.indicator arguments 参数中提供的所有参数(如价格)将神奇地传递给函数 RSI.lagged。我是否误解了... 的含义?
  • 您根本没有使用 add.indicator... 参数。它既有arguments 参数(您正在使用)和... 参数,但您没有使用...尽管文档并没有很清楚地说明两者之间的区别。

标签: r quantstrat


【解决方案1】:

您试图访问不存在的列的名称。试试这个来让你的指标工作:

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

【讨论】:

  • 哇最后一行非常重要.....非常感谢您指出这一点!
猜你喜欢
  • 2018-07-13
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
相关资源
最近更新 更多