R 尝试创建滚动周期cummax
我正在尝试创建一个函数来购买N周期高点。如果我有一个向量:R 尝试创建滚动周期cummax,r,xts,quantmod,performanceanalytics,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
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
`dimnames中的
错误,您很接近了。意识到rollappy
(等)在这种情况下需要返回一个数字,但是cummax
返回一个向量。让我们追溯一下:
使用rollappy(…,partial=TRUE)
时,第一次通过仅是第一个数字:1
第二个电话,前两个号码。您期望的是2
(这样它将附加到上一步的1
),但请看cummax(1:2)
:它的长度为2<强> >从这个步骤得出:<代码> CUM/代码>函数是天真的,因为它们是相对单调的:它们总是在执行逻辑/变换时考虑到所有的,包括当前的数目。
第三次调用,我们第一次访问完整的窗口(在本例中):考虑到13
,我们想要3
<代码>最大值
有效
所以我想你想要这个:
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