多滚动相关

时间:2018-02-08 19:55:13

标签: r tidyquant

我想解决的问题是计算数据框中所选列的滚动相关性。我想使用列名来驱动滚动函数:

我的功能

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)

}

功能测试

aapl <- tq_get("aapl")

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

关于如何进行此项工作或任何其他想法的任何想法?

提前致谢。

1 个答案:

答案 0 :(得分:0)

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)

}
data("FB")
corr_df <- rolling_correlation(FB, c("open", "high", "low"), c("close", "low", "open"), 5)

帮助unquoting !! quo(!! sym(.x))来自这里 - 看看lionel-评论于2017年5月4日 https://github.com/r-lib/rlang/issues/116