Search code examples
rrolling-computationquantile

Estimating quantile correlations with rolling window


I would like to estimate the quantile correlations between two variables, say Y and X, using the rolling window. I am using the R package QCSIS for this purpose. I tried to do the following

library(QCSIS)

#Generate some random variables
n   <- 4000
x   <- rnorm(n)
y   <- 2 * x + rt(n,df = 1)
tau <- 9 / 10
#calculate the static quantile correlation
fit<-qc(x = x, y = y, tau = tau)
fit$rho 
#calculate the rolling window quantile correlations
s<-260 #The window size

Rho.mat <- matrix(0,1,(n-s+1)) #create empty matrix to store the correlation coefficients
#running the loop
for(i in 1:(n-s+1)) {  
fit <- qc(x = x, y = y, tau = tau) 
Rho.mat[,i] <- fit$rho  

}  

However, this code does not give the quantile correlation for each window and only repeats the static quantile correlation! Most of the other solutions I found online are related to linear regression and do not fit with the function I am using. That is why I am using a loop.


Solution

  • Use rollapplyr as follows to avoid loops:

    library(zoo)
    rollapplyr(cbind(x, y), s, function(z) qc(z[, 1], z[, 2], tau)$rho, 
      fill = NA, by.column = FALSE)
    

    or over the indexes:

    rollapplyr(seq_along(x), s, function(ix) qc(x[ix], y[ix], tau)$rho, fill = NA)
    

    We can check the result like this:

    library(zoo)
    r.roll <- rollapplyr(cbind(x, y), s, function(z) qc(z[, 1], z[, 2], tau)$rho, 
      fill = NA, by.column = FALSE)
    
    r.for <- x
    for(i in seq_along(r.for)) {  
      r.for[i] <- if (i < s) NA else {
        ix <- seq(to = i, length = s)
        qc(x[ix], y[ix], tau = tau)$rho
      }
    }
    
    identical(r.roll, r.for)
    ## [1] TRUE