我正在尝试创建一个使用包中的drawdown
函数的自定义函数tseries
。我想将此函数应用于函数中正确的值范围,但即使这是一个相当新手的问题,我也看不到可能的解决方案。
这是我的数据框的样子:
> subSetTrades
Instrument EntryTime ExitTime AccountValue
1 JPM 2007-03-01 2007-04-10 6997
2 JPM 2007-04-10 2007-05-29 7261
3 JPM 2007-05-29 2007-07-18 7545
4 JPM 2007-07-18 2007-07-19 7614
5 JPM 2007-07-19 2007-08-22 7897
6 JPM 2007-08-22 2007-08-28 7678
7 JPM 2007-08-28 2007-09-17 7587
8 JPM 2007-09-17 2007-10-17 7752
9 JPM 2007-10-17 2007-10-29 7717
10 JPM 2007-10-29 2007-11-02 7423
11 KFT 2007-04-13 2007-05-14 6992
12 KFT 2007-05-14 2007-05-21 6944
13 KFT 2007-05-21 2007-07-09 7069
14 KFT 2007-07-09 2007-07-16 6919
15 KFT 2007-07-16 2007-07-27 6713
16 KFT 2007-07-27 2007-09-07 6820
17 KFT 2007-09-07 2007-10-12 6927
18 KFT 2007-10-12 2007-11-28 6983
19 KFT 2007-11-28 2007-12-18 6957
20 KFT 2007-12-18 2008-02-20 7146
如果我手动计算我希望我的函数输出的值,结果是正确的:
# Apply the function to the dataframe
with(subSetTrades, tapply(AccountValue, Instrument, MDD_Duration))
JPM KFT
106 85
> # Check the function for JPM
> maxdrawdown(subSetTrades[1:10,4])$from
[1] 5
> maxdrawdown(subSetTrades[1:10,4])$to
[1] 10
> # Get the entry time for JPM on row 5
> # Get the exit time for JPM on row 10
> # Calculate the time difference
> difftime(subSetTrades[10,3], subSetTrades[5,2], units='days')
Time difference of 106 days
# Check the calculations for the other Instrument
> maxdrawdown(subSetTrades[11:20,4])$from
[1] 3
> maxdrawdown(subSetTrades[11:20,4])$to
[1] 5
> # Get the exittime on row 5 for KFT, get the entrytime for KFT on row 3,
# and calculate the time difference
> difftime(subSetTrades[15,3], subSetTrades[13,2])
Time difference of 67 days
正如您在上面的示例中看到的,我的自定义函数 ( MDD_Duration
) 为 JPM 提供了正确的值,但为 KFT 提供了错误的值:结果应该是 67,而不是 85。函数 MDD_Duration 如下:
MDD_Duration <- function(x){
require(tseries)
# Get starting point
mdd_Start <- maxdrawdown(x)$from
mdd_StartDate <- subSetTrades$EntryTime[mdd_Start]
# Get the endpoint
mdd_End <- maxdrawdown(x)$to
mdd_EndDate <- subSetTrades$ExitTime[mdd_End]
return(difftime(mdd_EndDate, mdd_StartDate, units='days'))
}
手动回溯此自定义函数的步骤显示“<code>from”和“<code>to”行号的计算存在问题(即 R 需要根据仪器的长度调整 KFT 的值在它之前,在这种情况下是 JPM)。对于可能的解决方案,R 需要执行以下操作:
maxdrawdown
如果该工具是第一个(即在列表顶部),则获取函数的“来自”值。但是,如果当前乐器是第二个(或第三个等),则考虑前一个乐器的长度。因此,如果工具 JPM 的长度为 10,则搜索 KFT 的值应从 +10 开始。from
并且仪器 3 的和值的搜索to
应该从仪器 1 的长度 + 仪器 2 的长度开始。
我尝试nrow
在函数中使用(这似乎是这个答案的明显解决方案),这导致了关于“长度为 0 的参数”的错误,即使 nrow 使用正确(即函数外部的相同语句确实有效)。我还尝试对函数内的数据进行子集化,但也没有成功。任何想法都非常受欢迎。:)