2015-06-25 32 views
1

我正在計算平均壓降,平均長度,恢復長度等,其中R爲PnL數據序列而不是返回數據。這是這樣的數據幀如何修改PerformanceAnalytics包中的壓縮函數值

  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 

quantbook是數據幀,但沒有按」 t爲這個功能工作。 或者你還有其他什麼包可以獲得同樣的功能,請告知。

+0

什麼包'AverageDrawdown'屬於? – SabDeM

+0

該包稱爲PerformanceAnalytics包,用於返回數據(以百分比表示) – iamchrisa

+0

我在標題中提到了包名。 – iamchrisa

回答

1

我修改了包的函數。以下是PnL案例中的一個解決方案(或者您希望獲得價值而不是返回的其他任何案例),並希望您發現它很有用。參數xdataframe,而row.names對於xdates,所以你不用費力地在不同的數據類型之間進行轉換(我實際上遭受了很多)。隨着功能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)) 
}