Search code examples
rdplyrtime-seriesttr

apply dplyr function to time series failed


There is time series ttrc_total , when applying the dplyr function group_by mutate ..., there are failures. Is there way to solve it? Thanks!

library(TTR)
library(tidyverse)
data(ttrc)
ttrc_total <- rbind(ttrc %>% mutate(category='A'),
      ttrc %>% mutate(category='B'),
      ttrc %>% mutate(category='C'))

Below code show error message : no applicable method for 'group_by' applied to an object of class "c('xts', 'zoo')"

ttrc_total %>% xts::xts(., order.by=.$Date) %>% 
  group_by(category) %>% 
  mutate(ATR_10 = ATR(.[,c("High","Low","Close")], n=10))

Solution

  • I might try to split the data by category and shape it back to long format.

    library(TTR)
    library(tidyverse)
    data(ttrc)
    ttrc_total <- rbind(ttrc %>% mutate(category='A'),
                        ttrc %>% mutate(category='B'),
                        ttrc %>% mutate(category='C'))
    
    nested_data <- ttrc_total %>%
      as_tibble() %>%
      group_nest(category)
    
    nested_data <- nested_data %>%
      mutate(atr = map(data, \(x) as.data.frame(ATR(select(x, High, Low, Close), n = 10))))
    
    nested_data
    #> # A tibble: 3 × 3
    #>   category               data atr             
    #>   <chr>    <list<tibble[,6]>> <list>          
    #> 1 A               [5,550 × 6] <df [5,550 × 4]>
    #> 2 B               [5,550 × 6] <df [5,550 × 4]>
    #> 3 C               [5,550 × 6] <df [5,550 × 4]>
    
    atr_df <- bind_rows(nested_data$atr) %>%
      mutate(category = rep(nested_data$category, map_int(nested_data$atr, nrow)))
    
    head(atr_df)
    #>     tr atr trueHigh trueLow category
    #> 1   NA  NA       NA      NA        A
    #> 2 0.07  NA     3.15    3.08        A
    #> 3 0.04  NA     3.12    3.08        A
    #> 4 0.05  NA     3.12    3.07        A
    #> 5 0.04  NA     3.12    3.08        A
    #> 6 0.07  NA     3.17    3.10        A
    

    Created on 2023-09-01 with reprex v2.0.2