Calculate rolling correlation using rollapply

我的未来我决定 提交于 2019-11-30 08:57:40

For your simple case, you could use TTR::runCor.

set.seed(21)
x <- rnorm(30)
y <- rnorm(30)
z <- zoo(cbind(x,y),Sys.Date()-1:30)
tail(rollapplyr(z, 21, function(x) cor(x[,1],x[,2]), by.column=FALSE))
tail(runCor(z[,1],z[,2],21))

Try something like this:

x<-rnorm(100)
y<-rnorm(100)
rollapply(data.frame(x,y), 21 ,function(x) cor(x[,1],x[,2]), by.column=FALSE)

In other words, I think you may just need the by.column=FALSE argument. Works with a zoo object too

rollapply(zoo(cbind(x,y),Sys.Date()-1:100), 21 ,function(x) cor(x[,1],x[,2]), by.column=FALSE)

Edit to address a question from the comment about adding another column.

You can specify the columns you want to use in the cor function.

z<-rnorm(100)
rollapply(zoo(cbind(x,y,z),Sys.Date()-1:100), 21 ,function(x) cor(x[,1],x[,3]), by.column=FALSE)
rollapply(zoo(cbind(x,y,z),Sys.Date()-1:100), 21 ,function(x) cor(x[,2],x[,3]), by.column=FALSE)

by.column=FALSE indicates that the function should not be applied to each column separately. If by.column=TRUE, then the function will be applied to each column separately, and this is the default behavior.

6 month running correlation

`library(tidyquant)`

`x<-rnorm(100)
y<-rnorm(100)`

`zoo(cbind(x,y),Sys.Date()-1:100)`

`tq_transmute_xy(x          = x, 
                    y          = y,
                    mutate_fun = runCor,
                    n          = 6,
                    col_rename = "rolling.corr.6")`
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!