1

我正在计算 R 中 PnL 数据系列的平均回撤、平均长度、恢复长度等,而不是返回数据。这是这样的数据框

            PNL
2008-11-03  3941434
2008-11-04  4494446
2008-11-05  2829608
2008-11-06  2272070
2008-11-07 -2734941
2008-11-10 -2513580

我使用了 fTrading 包中的 maxDrawDown 函数,它起作用了。我怎样才能获得其他回撤功能?如果我直接运行AverageDrawdown(quantbook)函数,它会给出这样的错误消息

Error in if (thisSign == priorSign) { : missing value where TRUE/FALSE needed  

我检查了文档,AverageDrawdown如下所示:

findDrawdowns(R, geometric = TRUE, ...)

R    an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns

Myquantbook是一个数据框,但不适用于此功能。或者你有什么其他的包来获得同样的功能,请指教。

4

1 回答 1

1

我已经修改了包的功能。这是 PnL 情况下的一种解决方案(或您想要获得价值而不是回报的任何其他情况),希望您发现它有用。参数x是 adataframerow.namesforxdates这样你就不必费心在不同的数据类型之间进行转换(我实际上遭受了很多痛苦)。使用该函数findPnLDrawdown,您可以执行许多其他函数来计算averageDrawDownaverageLengthrecovery等。

PnLDrawdown <- function(x) {
  ts = as.vector(x[,1])
  cumsum = cumsum(c(0, ts))
  cmaxx = cumsum - cummax(cumsum)
  cmaxx = cmaxx[-1]
  cmaxx = as.matrix(cmaxx)
  row.names(cmaxx) = row.names(x)
  cmaxx = timeSeries(cmaxx)
  cmaxx
}


findPnLDrawdown <- function(R) {
  drawdowns = PnLDrawdown(R)
  draw = c()
  begin = c()
  end = c()
  length = c(0)
  trough = c(0)
  index = 1
  if (drawdowns[1] >= 0) {
    priorSign = 1
  } else {
    priorSign = 0
  }
  from = 1
  sofar = as.numeric(drawdowns[1])
  to = 1
  dmin = 1
  for (i in 1:length(drawdowns)) {
    thisSign =ifelse(drawdowns[i] < 0, 0, 1)
    if (thisSign == priorSign) {
      if (as.numeric(drawdowns[i]) < as.numeric(sofar)) {
        sofar = drawdowns[i]
        dmin = i
      }
      to = i+ 1
    }
    else {
      draw[index] = sofar
      begin[index] = from
      trough[index] = dmin
      end[index] = to
      from = i
      sofar = drawdowns[i]
      to = i + 1
      dmin = i
      index = index + 1
      priorSign = thisSign
    }
  }
  draw[index] = sofar
  begin[index] = from
  trough[index] = dmin
  end[index] = to
  list(pnl = draw, from = begin, trough = trough, to = end, 
       length = (end - begin + 1),
       peaktotrough = (trough - begin + 1),
       recovery = (end - trough))
}
于 2015-06-26T16:30:39.530 回答