Search code examples
rtidyquant

Multiple rolling correlation


The problem I am trying to solve is to calculate rolling correlation over selected columns in a data frame. I want to use column names to drive the rolling functions:

my function

library(tidyquant)

rolling_cor <- function(df, col1, col2, window.length){

  col1 <- as.name(col1)
  col2 <- as.name(col2)

    xx <- df %>%
    tq_mutate_xy(x          = col1, 
                 y          = col2,
                 mutate_fun = runCor,
                 n          = window.length,
                 col_rename = glue(str_sub(col1,1,3), "_",str_sub(col2,1,3), "_", str_sub(col1,4,6)))
  return(xx)

}

test of the function

aapl <- tq_get("aapl")

aapl_roll_cor <- rolling_cor(aapl, col1 = "open" , col2 = "high", 15)

Any ideas on how to make this work or any alternative ideas?

Thanks in advance.


Solution

  • rolling_correlation <- function(df, vector.1, vector.2, window.length = 15){
    
    
      require(rlang)
      require(tidyquant)
      require(tibbletime)
    
      #build the correlation formula
      cor_roll <- rollify(~cor(.x, .y), window = window.length)
    
    
      x <- map2(vector.1, vector.2, ~mutate(df, 
                                            running_cor = cor_roll(!!quo(!! sym(.x)), 
                                                                   !!quo(!! sym(.y))))) %>%
        stats::setNames(., paste(vector.1, vector.2, sep = "_")) %>%                            # name the dfs in the list
        bind_rows(.id = "groups") %>% spread(groups, running_cor)                               # add the list name as a column in the DF and then spread it
    
      return(x)
    
    }
    
    Example
    data("FB")
    corr_df <- rolling_correlation(FB, c("open", "high", "low"), c("close", "low", "open"), 5)
    

    help for unquoting !!quo(!! sym(.x)) was from here - look at lionel- commented on May 4, 2017 https://github.com/r-lib/rlang/issues/116