Как рассчитать корреляцию со скользящим окном? - PullRequest
2 голосов
/ 02 ноября 2011

У меня есть объект зоопарка с именем aux с годовыми данными за 1961–2009 гг .:

     x$nao x[, 2]
1961 -0.03   63.3
1962  0.20  155.9
1963 -2.98  211.0

Я хочу рассчитать корреляцию между двумя столбцами, используя скользящее окно на 20 лет.Я пытаюсь использовать rollapply, но я не могу заставить его работать.Я пробовал несколько разных способов сделать это, но всегда безуспешно ...

> rollapply(aux,20, cor(aux[,1],aux[,2],method="pearson"))
Error in match.fun(FUN) : 'cor(aux[, 1], aux[, 2], method = "pearson")' is not a function, character or symbol

> rollapply(aux,20, cor,method="pearson")
Error in FUN(coredata(data)[posns], ...) : supply both 'x' and 'y' or a matrix-like 'x'

> rollapply(aux,20, cor)
Error in FUN(coredata(data)[posns], ...) : supply both 'x' and 'y' or a matrix-like 'x'

Может кто-нибудь сказать мне, как заставить rollapply работать?

Спасибо за помощь!

1 Ответ

1 голос
/ 08 июня 2012

Попробуйте это.

library(quantmod)   
library(TTR)   

#Set the seed so results can be duplicated   
set.seed(123)   

#Build a zoo object with typical price data   
var1 <- zoo(cumprod(1+rnorm(50, 0.01, 0.05)), seq(1961, 2001, 1))   
var2 <- zoo(cumprod(1+rnorm(50, 0.015, 0.1)), seq(1961, 2001, 1))   
dat <- merge(var1=var1, var2=var2)   
plot(dat)   
grid()   

#Calculate the percent returns for the two prices   
del1 <- Delt(dat$var1)   
del2 <- Delt(dat$var2)   
dat <- merge(dat, del1=del1, del2=del2)   
dimnames(dat)[[2]][3] <- "del1"   
dimnames(dat)[[2]][4] <- "del2"   
head(dat)   
plot(dat)   

#Calculate the correlation between the two returns using a 5 year sliding window   
delcor <- runCor(dat$del1, dat$del2, n=5, use="all.obs", sample=TRUE, cumulative=FALSE)   
dat <- merge(dat, delcor)   
plot(dat$delcor, type="l", main="Sliding Window Correlation of Two Return Series", xlab="", col="red")   
grid()   

enter image description here

...