R 转印器:在任何仓位开仓之前 posn 都会产生错误



我正在尝试使用吸墨器回测交易策略。经过长时间的搜索,我发现错误只发生在没有交易发生并且没有开仓的情况下。在任何交易开仓之前,Posn 在 RStudio 的工作区中以 numeric(0) 的形式列出。之后,它始终为 0 或仓位。我的错误在哪里,或者我可以在第一个 if 子句中添加什么 if(Posn!=0)?因为这如果生成错误并显示以下消息:

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)
  }
}

只需测试调用getPosQty后是否length(Posn)==0

Posn <- numeric(0)
if(!length(Posn)) Posn <- 0

相关内容

  • 没有找到相关文章

最新更新