2016-03-28 28 views
0

感謝Simon Otziger,我將跨越一個策略的累積回報和回報高峯的功能作爲一個很好的結合閃亮和量化的例子。源代碼是here。該代碼大部分時間都能正常工作,但對於某些數據,它不會正確繪製峯值。volemont/insights:chart.EquityCurve.R:繪製累計回報高峯的錯誤?

代碼被簡化了,但關鍵邏輯沒有改變。我從三個示例策略中複製了三組數據(cumPNL1,cumPNL2,cumPNL3)來運行代碼,其中第一個數據將導致代碼無法正確繪製峯值。

我分別用cumPNL1,cumPNL2,cumPNL3運行了以下代碼。通過cumPNL2和cumPNL3,代碼可以成功地生成累積回報線和峯值點。然而,對於cumPNL1,代碼只能產生直線,但峯值不在正確位置。

我注意到,基於cumPNL2和cumPNL3的peakIndex都將其第一個值設置爲TRUE,所以當我通過添加一行peakIndex[1] <- TRUE來更改代碼時,cumPNL1將與修改的代碼一起正常工作。

雖然現在它可以與修改後的代碼一起工作,但我不知道爲什麼它的行爲如此。任何人都可以看看嗎?感謝

cumPNL1 <- c(-193,-345,-406,-472,-562,-543,-450,-460,-544,-659,-581,-342,-384,276,-858,-257.99) 
cumPNL2 <- c(35.64,4.95,-2.97,-6.93,11.88,-19.8,-26.73,-39.6,-49.5,-50.49,-51.48,-48.51,-50.49,-55.44,143.55,770.22,745.47,691.02,847.44,1141.47,1007.82,1392.93,1855.26,1863.18,2536.38,2778.93,2811.6,2859.12,2417.58) 
cumPNL3 <- c(35.64,4.95,-2.97,-6.93,11.88,-19.8,-26.73,-39.6,-49.5,-50.49,-51.48,-48.51,-50.49,-55.44,143.55,770.22,745.47,691.02,847.44,1141.47,1007.82,1392.93,1855.26,1863.18,2536.38,2778.93,2811.6,2859.12,2417.58) 


peakIndex <- c(cumPNL3[1] > 0, diff(cummax(cumPNL3)) > 0) 
# peakIndex[1] <- TRUE 

dev.new() 

plot(cumPNL3, type='n', xlab="index of trades", ylab="returns in cash", main="cumulative returns and peaks") 
grid() 
lines(cumPNL3)  
points(cbind(1 : length(cumPNL3), cumPNL3)[peakIndex, ], 
     pch=19, col='green', cex=0.6) 

legend(
    x='bottomright', inset=0.1, 
    legend=c('Net Profit','Peaks'), 
    lty=c(1, NA), pch=c(NA, 19), 
    col=c('black','green') 
) 

回答

1

cumPNL1具有單峯和R減少了從一個數值矩陣的維數,以長度爲2的數值矢量的points函數繪製在y軸使用x軸指數兩個數值矢量值1和2:

peakIndex1 <- c(cumPNL1[1] > 0, diff(cummax(cumPNL1)) > 0) 
peakIndex3 <- c(cumPNL3[1] > 0, diff(cummax(cumPNL3)) > 0) 

str(cbind(1 : length(cumPNL1), cumPNL1)[peakIndex1,]) 
str(cbind(1 : length(cumPNL3), cumPNL3)[peakIndex3,]) 

輸出:

> str(cbind(1 : length(cumPNL1), cumPNL1)[peakIndex1,]) 
num [1:12, 1:2] 1 15 16 19 20 22 23 24 25 26 ... 
- attr(*, "dimnames")=List of 2 
    ..$ : NULL 
    ..$ : chr [1:2] "" "cumPNL1" 
> str(cbind(1 : length(cumPNL3), cumPNL3)[peakIndex3,]) 
Named num [1:2] 14 276 
- attr(*, "names")= chr [1:2] "" "cumPNL3" 

一般設置plot = FALSE保留了對象,例如,str(cbind(1 : length(cumPNL3), cumPNL3)[peakIndex3, drop = FALSE]),這在某些情況下不起作用。然而,改變points線以下的解決了這個問題:

points(seq_along(cumPNL3)[peakIndex], cumPNL3[peakIndex], pch = 19, 
    col = 'green', cex = 0.6) 

由於報告了該問題。我會在明天推出修補程序到GitHub。