滚动应用时间序列 [英] Rollapply for time series

查看:30
本文介绍了滚动应用时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算滚动的 20 周期历史波动率.我接受每日回报:

I am trying to calculate the rolling 20 period historical volatility. I take the daily returns:

ret<-ROC(data1)

然后我使用 rollapply 获取每列的 20 天 HV:

And then I use rollapply to get the 20 day HV for each column:

vol<-rollapply(ret,20,sd,by.column=T,fill=NA)

问题是 vol 中的观察结果在 10 天后开始出现,这与我指定的 20 天是错误的.

The problem is that observations in vol starts appearing after ten days which is wrong as I specified 20.

为了演示,这里是数据示例:

For demonstration here is sample of the data:

0.000000000, 0.005277045, 0.023622047, 0.002564103,-0.002557545, -0.020512821,
0.007853403,-0.012987013,  0.007894737,  0.015665796,  0.000000000, -0.002570694,
0.002577320, -0.015424165, 0.002610966,  0.010416667,  0.002577320,  0.015424165, 
0.000000000, -0.002531646, -0.002538071, 0.030534351,  0.014814815, -0.007299270,
-0.009803922, -0.012376238,  0.002506266, -0.015000000,-0.002538071,  0.002544529

假设上面的数据存储在x中,那么:

Assume the data above is stored in x, then:

rollapply(x,20,sd,fill=NA)

将在第 10 行而不是第 20 行产生第一个观察结果.sd 也是错误的.

will yield a first observation at 10th row instead of 20. Also the sd is wrong too.

我应该在这里遗漏了一些东西......

I should be missing something here...

推荐答案

你需要使用 align='right' 而不是使用默认的 align='center'code>,或者不使用 rollapply,而是使用 rollapplyr 包装器,该包装器将 align='right' 作为默认值.

You need to use align='right' instead of using the default which is align='center', or instead of using rollapply, use the rollapplyr wrapper which has align='right' as the default.

来自?rollapply:

对齐指定与观察的滚动窗口相比,结果的索引是左对齐还是右对齐还是居中(默认).仅当宽度表示宽度时才使用此参数.

align specifyies whether the index of the result should be left- or right-aligned or centered (default) compared to the rolling window of observations. This argument is only used if width represents widths.

尽管如此,就个人而言,我会使用 TTR 中的 runSD 打包,因为它使用编译代码并且速度会更快.

Although, for this, personally, I'd use runSD from the TTR package because it uses compiled code and will be faster.

其中任何一个都应该符合您的预期,但第二个会更快.

Either of these should do what you expect, but the second one will be faster.

library(zoo)
rollapply(x, 20, sd, fill=NA, align='right')

library(TTR)
runSD(x, 20)

这篇关于滚动应用时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆