rtidyquanttibbletime

tibbletime with tq_transmute producing strange error, column obviously exists but says it doesn't


I could have sworn this code worked a week ago, but I guess that I am mistaken. I keep getting the error: Error: Can't subset columns that don't exist. x Column asset doesn't exist. Run rlang::last_error() to see where the error occurred. In addition: Warning message: ... must not be empty for ungrouped data frames. Did you want data = everything()?

I've taken it step by step to try and see where it is in my code and I can tell that it is after I group the assets, and occurs when I start to add on the tq_transmute. If someone could please help that would be greatly appreciated. I will have code that you should be able to just run automatically and see what I am talking about. It doesn't make any sense because "asset" does exist after gathering the data and grouping it.

library(tidyverse)
library(lubridate) 
library(readxl)
library(highcharter) 
library(tidyquant) 
library(timetk) 
library(tibbletime) 
library(quantmod) 
library(PerformanceAnalytics)
library(scales)
library(magrittr)
library(broom)
library(purrr)

symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")

prices <- getSymbols(symbols,
                     src = 'yahoo',
                     from = "2012-12-31",
                     to = "2017-12-31",
                     auto.assign = TRUE,
                     warnings = FALSE) %>%
  map(~Ad(get(.)))%>% #the period here in get(.) refers to our intial object
  reduce(merge) %>%
  `colnames<-`(symbols)


# WHERE MY PROBLEM OCCURS 
asset_returns_tbltime <-
  prices %>% 
  tk_tbl(preserve_index = TRUE,
                    rename_index = "date")%>%
  # this is the the tibbletime function
  as_tbl_time(index = date) %>% 
  as_period(period = "month",
            side = "end") %>%
  gather(asset, returns, -date) %>%
  group_by(asset) %>% 
  tq_transmute(mutate_fun = periodReturn, #GETTING THE ERROR SOMEWHERE IN HERE
                                   type = "log") %>%
  spread(asset, monthly.returns) %>%
  select(date, symbols) %>%
  slice(-1)

Solution

  • gather has been replaced with pivot_longer and spread with pivot_wider. If you change gather code to pivot_longer it works. I am not exactly sure why it fails with gather though.

    prices %>% 
      tk_tbl(preserve_index = TRUE,
             rename_index = "date")%>%
      as_tbl_time(index = date) %>% 
      as_period(period = "month",
                side = "end") %>%
      pivot_longer(cols = -date, names_to = 'asset', values_to = 'returns') %>%
      group_by(asset) %>%
      tq_transmute(mutate_fun = periodReturn, type = "log")  %>%
      pivot_wider(names_from = asset, values_from = monthly.returns) %>%
      select(date, symbols) %>%
      slice(-1)