【问题标题】:Trying to create a rolling period cummax试图创建一个滚动周期 cummax
【发布时间】:2019-04-15 17:31:01
【问题描述】:

我正在尝试创建一个购买 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

提前致谢

【问题讨论】:

    标签: r xts quantmod performanceanalytics


    【解决方案1】:

    你已经接近了。意识到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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多