R中的循环更快

时间:2015-04-21 19:07:39

标签: r

我正在努力减少程序运行所需的时间。我从其他语言的编程中得知的一点是,某些循环比其他循环运行得慢。现在我正在使用重复循环,我想知道是否有更快的选项。

FindPnL <- function(StockData, MA1, MA2, SL, LS, Day, Buy, Sell){

PnL <- 0
  MA1Value <- moving_avg(StockData, MA1, Day)
  MA2Value <- moving_avg(StockData, MA2, Day)
  repeat{
    MA1Prev <- MA1Value
    MA2Prev <- MA2Value
    Day <- Day + 1
    if(Day>7890){ #Pending length technique
      break
    }
    MA1Value <- moving_avg(StockData, MA1, Day)
    MA2Value <- moving_avg(StockData, MA2, Day)
    results <- CheckCross(MA1Prev, MA2Prev, MA1Value, MA2Value)
    Buy <- CheckCross(MA1Prev, MA2Prev, MA1Value, MA2Value)[["a"]]
    Sell <- CheckCross(MA1Prev, MA2Prev, MA1Value, MA2Value)[["b"]]
    PnL <- Transaction(Buy, Sell, PnL, Day, SL, LS, StockData)[["a"]]
    Day <- Transaction(Buy, Sell, PnL, Day, SL, LS, StockData)[["b"]]
    Buy <- FALSE
    Sell <- FALSE
  }
  return(PnL)
}

1 个答案:

答案 0 :(得分:3)

使用样本函数

CheckCross <- function(...){
 Buy <- TRUE
 Sell <- FALSE
 results <- list(a = Buy, b = Sell)
 return(results)
}

您可以替换

Buy <- CheckCross(MA1Prev, MA2Prev, MA1Value, MA2Value)[["a"]]
Sell <- CheckCross(MA1Prev, MA2Prev, MA1Value, MA2Value)[["b"]]

cc <- CheckCross(MA1Prev, MA2Prev, MA1Value, MA2Value)
Buy <- cc$a
Sell <- cc$b