gpt4 book ai didi

r - data.table 的最大回撤

转载 作者:行者123 更新时间:2023-12-02 08:34:00 29 4
gpt4 key购买 nike

我对 data.table 有点生疏,我想找到意甲 X_t 的最大回撤(任何时间 t 的最大回撤可以定义为argmin{X_T-X_t} 其中 T>t,英文,对于时间系列的每个元素,我需要找到带有 T>t 的系列元素,这样最小化 X_T-X-t,如果系列在增加,则没有减少)。

library(data.table) 
set.seed(1)
DT = data.table(x=rnorm(10))
DT[,cumsumX:=cumsum(x)]

#I am interested in the drawdown for cumsumX

DT
x cumsumX
1: -0.6264538107 -0.6264538107 => max drawdown is -1.27.. index 3 (-1.27+0.62 is mini)
2: 0.1836433242 -0.4428104865 => max drawdown is -1.27.. index 3 (-1.27+0.62 is mini)
3: -0.8356286124 -1.2784390989 => max drawdown is NA (-1.27 is global minima)
4: 1.5952808021 0.3168417032 => max drawdown is -0.17.. index 6
5: 0.3295077718 0.6463494750 ...
6: -0.8204683841 -0.1741189091
7: 0.4874290524 0.3133101433
8: 0.7383247051 1.0516348485
9: 0.5757813517 1.6274162001
10: -0.3053883872 1.3220278130

如何使用 data.table 找到 maxdrawdow

这是我的解决方案

DT[,`:=`(dd=min(0,min(DT$cumsumX[.I:nrow(DT)])-cumsumX),ddIDX=.I-1L+which.min(DT$cumsumX[.I:nrow(DT)])),by=IDX]
DT
x cumsumX IDX dd ddIDX
1: -0.6264538 -0.6264538 1 -0.6519853 3
2: 0.1836433 -0.4428105 2 -0.8356286 3
3: -0.8356286 -1.2784391 3 0.0000000 3
4: 1.5952808 0.3168417 4 -0.4909606 6
5: 0.3295078 0.6463495 5 -0.8204684 6
6: -0.8204684 -0.1741189 6 0.0000000 6
7: 0.4874291 0.3133101 7 0.0000000 7
8: 0.7383247 1.0516348 8 0.0000000 8
9: 0.5757814 1.6274162 9 -0.3053884 10
10: -0.3053884 1.3220278 10 0.0000000 10

最佳答案

看起来你想要:

DT[, maxdrawdown := rev(cummin(rev(cumsumX)))]
DT[, index := .I[.N], by = maxdrawdown]
DT[cumsumX == min(cumsumX), `:=`(index = NA, maxdrawdown = NA)]
# x cumsumX maxdrawdown index
# 1: -0.6264538 -0.6264538 -1.2784391 3
# 2: 0.1836433 -0.4428105 -1.2784391 3
# 3: -0.8356286 -1.2784391 NA NA
# 4: 1.5952808 0.3168417 -0.1741189 6
# 5: 0.3295078 0.6463495 -0.1741189 6
# 6: -0.8204684 -0.1741189 -0.1741189 6
# 7: 0.4874291 0.3133101 0.3133101 7
# 8: 0.7383247 1.0516348 1.0516348 8
# 9: 0.5757814 1.6274162 1.3220278 10
#10: -0.3053884 1.3220278 1.3220278 10

关于r - data.table 的最大回撤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23639875/

29 4 0