尝试创建滚动期cummax

Jor*_*ong 3 r xts quantmod performanceanalytics

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

  x = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
Run Code Online (Sandbox Code Playgroud)

我想把滚动期提高到3个周期。这就是我希望功能看起来的样子

 x =  c(1, 2, 3, 4, 5, 5, 5, 3, 4, 5)
Run Code Online (Sandbox Code Playgroud)

我试图在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)
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

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

提前致谢

r2e*_*ans 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
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

认为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
Run Code Online (Sandbox Code Playgroud)