我正在尝试使用吸墨纸回溯测试交易策略。经过长时间的搜索后,我发现错误只有在没有交易并且没有开仓的情况下。在任何交易开始之前,Posn在RStudio的工作区中列为数字(0)。之后它总是0或位置。 如果(Posn!= 0),我的错误在哪里或者我可以添加到第一个if子句中?因为这会产生错误,并显示以下消息:
Error in if (Posn != 0) { : argument is of length zero
然后我尝试了这两个输入并得到了这些结果:
> Posn
numeric(0)
> Posn!=0
logical(0)
这是我的完整代码:
for(i in 84:200){
CurrentDate <- time(MergedXTS)[i]
ClosePrice <- as.numeric(MergedXTS[i,'Close'])
if(!(is.na(as.numeric(MergedXTS[i,'Close']))) && !(is.na(as.numeric(MergedXTS[i-1,'Close'])))){
RiskClose <- as.numeric(MergedXTS[i,'RiskIndicatorMA'])
RiskClose.PreviousDay <- as.numeric(MergedXTS[i-1,'RiskIndicatorMA'])
Posn <- getPosQty(StrategyName, Symbol=CrossCurrency, Date=CurrentDate)
print(Posn)
if(Posn != 0){
if(Posn>0){
#Long active, sell long
if(RiskClose <= ParamUp && RiskClose.PreviousDay > ParamUp){
addTxn(Risk.Strategy, Symbol=CrossCurrency, TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = -1000 , TxnFees=0)
}
} else {
#Short active sell short
if(RiskClose >= ParamDown && RiskClose.PreviousDay < ParamDown){
addTxn(StrategyName, Symbol=CrossCurrency, TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = 1000 , TxnFees=0)
}
}
} else {
if(RiskClose >= ParamUp && RiskClose.PreviousDay < ParamUp){
#Buy
addTxn(StrategyName, Symbol=CrossCurrency, TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = 1000 , TxnFees=0)
}
if(RiskClose <= ParamDown && RiskClose.PreviousDay > ParamDown){
#Short
addTxn(StrategyName, Symbol=CrossCurrency, TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = -1000 , TxnFees=0)
}
}
# Calculate P&L and resulting equity with blotter
updatePortf(StrategyName, Dates=CurrentDate)
updateAcct(StrategyName, Dates=CurrentDate)
updateEndEq(StrategyName, Dates=CurrentDate)
print(i)
}
}
答案 0 :(得分:1)
在致电length(Posn)==0
后,只需测试getPosQty
:
Posn <- numeric(0)
if(!length(Posn)) Posn <- 0