# A function that calculates the rolling correlation between a sector ETF and the SPY SP500 ETF. 

sector_index_correlation <- function(x, window) {
    # Make one xts object to hold the sector returns and the SPY returns  
    merged_xts <- merge(x, etf_returns$'Index')

    # Use rollapply() to calculate the rolling correlations. 
    # See what happens if you remove the 'pairwise.complete.obs' argument - the NAs will cause problems.
    merged_xts$rolling_cor <- rollapply(merged_xts, window, 
                                         function(x) cor(x[,1], x[,2], use = "pairwise.complete.obs"), 
                                         by.column = FALSE)
    names(merged_xts) <- c("Sector Returns", "SPY Returns", "Sector/SPY Correlation")