运行quantstrat分析时出错

时间:2013-06-28 20:14:43

标签: r quantstrat

我坚持以下分析:

library(quantstrat)

stock_size = 200
tickers = c("XOM", "MCD")
init.date = as.Date("2008-01-01")

usd = "USD"
currency(usd)
for(ticker in tickers){ 
  stock(ticker, currency=usd, multiplier = 1)
}

options("getSymbols.warning4.0"=FALSE)
getSymbols(tickers,from=init.date,to.assign=TRUE)

suppressWarnings(rm(strat, port, acct, ords))

port.name <- "MyPort"
port <- initPortf(port.name,tickers,initDate=init.date)
acct.name <- "MyAcct"
acct <- initAcct(acct.name,portfolios=port.name, initDate=init.date, initEq=35000)
ords <- initOrders(portfolio=port.name,initDate=init.date)

strat.name <- "MyStrat"
strat<- strategy(strat.name)
strat<- add.indicator(strategy = strat, name = "SMA", arguments = list(x=quote(Ad(mktdata)), n=20),label= "ma20" )
strat<- add.indicator(strategy = strat, name = "SMA", arguments = list(x=quote(Ad(mktdata)), n=50),label= "ma50")

strat<- add.signal(strat, name="sigCrossover", arguments = list(columns=c("ma20","ma50"), relationship="gte"), label="ma20.gt.ma50")
strat<- add.signal(strat, name="sigCrossover", arguments = list(column=c("ma20","ma50"), relationship="lt"), label="ma20.lt.ma50")

strat<- add.rule(strategy = strat,name='ruleSignal', arguments = list(sigcol="ma20.gt.ma50", sigval=TRUE, orderqty=stock_size, ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE)
strat<- add.rule(strategy = strat,name='ruleSignal', arguments = list(sigcol="ma20.lt.ma50", sigval=TRUE, orderqty='all', 
ordertype='market', orderside='long', pricemethod='market'), type='exit', path.dep=TRUE)

out<-try(applyStrategy(strategy=strat, portfolios=port.name))
charts.PerformanceSummary()

因为我遇到了这两个错误:

Error in `colnames<-`(`*tmp*`, value = c("XOM.Adjusted.SMA.50", "XOM.Adjusted.SMA.20.ma20.SMA.50" : 
  length of 'dimnames' [2] not equal to array extent
Error in inherits(x, "xts") : argument "R" is missing, with no default

任何人都可以帮我找到错误吗?

1 个答案:

答案 0 :(得分:5)

在当前版本的TTR中,MA指示符返回的列的名称以输入列的名称为前缀。例如。 SMA(MCD.Adjusted,n = 20)返回名为 MCD.Adjusted.SMA.20 的列。

Ad()将返回与字符串调整匹配的所有列名。

当您的第二个SMA指标被调用时, Ad()将匹配2个列名称(原始 MCD.Adjusted 列加上第一个的输出列)指标 MCD.Adjusted.SMA.20 )。这会导致尺寸错误,因为在当前实现中,SMA()当时只能处理一个输入列。

解决方案是在参数列表中使用 quote(Ad(mktdata)[,1])仅传递第一个匹配项。