我正在尝试在R中使用quantstrat来回测简单移动平均RSI策略,但出现错误:
Error in if ((orderqty + pos) > PosLimit[, "MaxPos"]) { :
argument is of length zero
问题似乎出在我的订单数量加上现有头寸大于最大头寸。如何控制我的排名限制以消除此错误?
下面是代码。
library(quantstrat)
library(quantmod)
getSymbols("SPY")
Sys.setenv(TZ = "UTC")
currency("USD")
ticker = "SPY"
stock(ticker, currency = "USD", multiplier = 1)
strat.3 = "SMA/RSI.3"
strat=NULL
initPortf(strat.3, ticker)
initOrders(strat.3, ticker)
initAcct(strat.3, strat.3, initEq = 100000000)
addPosLimit(portfolio=strat.3,symbol='SPY',timestamp=startDate,maxpos=1000)
strategy(strat.3, store = T)
add.indicator(strategy = strat.3, name = "RSI", arguments = list(price = quote(getPrice(mktdata))), label="RSI")
add.indicator(strategy = strat.3, name = "SMA", arguments = list(x=quote(Cl(mktdata)[,1]), n=200),label= "ma200")
add.signal(strat.3, "sigCrossover", arguments = list(columns = c("Close", "SMA200"),
relationship = "gte"),
label= "Cross.FB")
add.signal(strat.3, "sigCrossover", arguments = list(columns = c("Close", "SMA200"),
relationship = "lt"),
label = "Cross.FA")
add.signal(strategy = strat.3, name="sigThreshold",arguments = list(threshold=70, column="RSI",relationship="gt", cross=TRUE),label="RSI.gt.70")
# The second is when RSI is less than 10
add.signal(strategy = strat.3, name="sigThreshold",arguments = list(threshold=30, column="RSI",relationship="lt",cross=TRUE),label="RSI.lt.30")
add.rule(strat.3, "ruleSignal", arguments = list(sigcol = "Cross.FB",
sigval = T,
ordertype = "market",
orderqty = 1,
orderside = "long"),
type = "enter",
label = "Enter2Long")
add.rule(strat.3, "ruleSignal", arguments = list(sigcol = "Cross.FA",
sigval = T,
orderqty = 1,
ordertype = "market",
orderside = "long"),
type = 'exit',
label = "Exit2Close")
add.rule(strategy = strat.3, name='ruleSignal', arguments = list(sigcol="RSI.lt.30", sigval=TRUE, orderqty= 1, ordertype='market', orderside='long', pricemethod='market', replace=FALSE, osFUN=osMaxPos), type='enter', path.dep=TRUE)
add.rule(strategy = strat.3, name='ruleSignal', arguments = list(sigcol="RSI.gt.70", sigval=TRUE, orderqty=1, ordertype='market', orderside='long', pricemethod='market', replace=FALSE), type='exit', path.dep=TRUE)
out = applyStrategy(strat.3, strat.3)
您的帮助将不胜感激,因为这对我来说是一个非常重要的项目。谢谢