business-science / tidyquant

Bringing financial analysis to the tidyverse
https://business-science.github.io/tidyquant/
Other
852 stars 175 forks source link

Allowing tq_transmute to programmatically set aggregation functions #198

Open kaybenleroll opened 3 years ago

kaybenleroll commented 3 years ago

I am trying to create a function that takes a list of aggregation functions and applies them in sequence.

Here is a short reprex:

library(tidyquant)
library(glue)

calculate_period_volume <- function(label, data) {
  apply_func <- glue("apply.{labe}") %>% get()

  agg_tbl <- data %>%
    tq_transmute(
      mutate_fun = apply_func,
      FUN        = sum,
      na.rm      = TRUE,
      col_rename = "amount"
      )

  return(agg_tbl)
}

agg_vol_tbl <- c("daily", "weekly", "monthly") %>%
  enframe(name = NULL, value = "period") %>%
  mutate(
    data = map(label, calculate_period_volume, data = FANG)
  )

The error message for this is

Error: Problem with `mutate()` input `data`.
x fun = apply_func not a valid option.
i Input `data` is `map(label, calculate_period_volume, data = FANG)`.

I think the issue is that tq_transmute/tq_mutate is expecting the name of the function, but would it be possible to change this so that if mutate_fun is a string it just uses the function named in the string? I guess for validity you would also need to ensure that the value of the string is on the approved list if you want to preserve that feature?

Happy to help out in fixing this if I can as I think it will be useful.