尝试创建滚动期cummax

时间:2018-11-12 23:26:37

标签: r xts quantmod performanceanalytics

我正在尝试创建一个购买N期高位的函数。因此,如果我有一个向量:

  x = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

我想把滚动期提高到3个周期。这就是我想要的功能外观

 x =  c(1, 2, 3, 4, 5, 5, 5, 3, 4, 5)

我正在尝试在xts对象上执行此操作。 这是我尝试过的:

    rollapplyr(SPY$SPY.Adjusted, width = 40, FUN = cummax)
    rollapply(SPY$SPY.Adjusted, width = 40, FUN = "cummax")
    rapply(SPY$SPY.Adjusted, width  = 40, FUN = cummax)

我收到的错误是:

      Error in `dimnames<-.xts`(`*tmp*`, value = dn) : 
      length of 'dimnames' [2] not equal to array extent

预先感谢

1 个答案:

答案 0 :(得分:5)

您已经关闭。意识到rollapply(等)在这种情况下期望返回单个数字,但是cummax返回一个向量。让我们追溯一下:

  1. 使用rollapply(..., partial=TRUE)时,第一遍就是第一个数字:1
  2. 第二个电话,前两个数字。您期望使用2(以便将其附加到上一步的1中),但请注意cummax(1:2):它的长度为2。结论cum函数之所以幼稚,是因为它们相对单调:在执行逻辑/转换时,它们始终考虑直到当前值的所有事物,包括当前数字。
  3. 第三次呼叫,我们第一次访问一个全窗口(在这种情况下):考虑1 2 3,我们想要3max有效。

所以我想你想要这个:

zoo::rollapplyr(x, width = 3, FUN = max, partial = TRUE)
#  [1] 1 2 3 4 5 5 5 3 4 5

partial使我们在进入第一个完整窗口1-3之前先看一下1和1-2。在帮助页面中:

partial: logical or numeric. If 'FALSE' (default) then 'FUN' is only
         applied when all indexes of the rolling window are within the
         observed time range.  If 'TRUE', then the subset of indexes
         that are in range are passed to 'FUN'.  A numeric argument to
         'partial' can be used to determin the minimal window size for
         partial computations. See below for more details.

cummax视为等同于

rollapplyr(x, width = length(x), FUN = max, partial = TRUE)
#  [1] 1 2 3 4 5 5 5 5 5 5
cummax(x)
#  [1] 1 2 3 4 5 5 5 5 5 5