I'm trying to generate rolling betas for stocks and my rolling function is not working. What I have tried so far:
library(tidyquant)
library(tidyverse)
library(tibbletime)
ticker_data <- tq_get(c("AAPL", "SPY"))
daily_returns <- ticker_data %>%
group_by(symbol) %>%
tq_transmute(select = close,
mutate_fun = periodReturn,
period = "daily",
col_rename = "daily_return") %>%
ungroup
all_returns_df <- left_join(daily_returns %>% filter(symbol == "AAPL"),
daily_returns %>% filter(symbol == "SPY") %>%
select(-symbol) %>%
rename(mkt_daily_return = daily_return))
# Can generate one Beta for all dates
all_returns_df %>%
tq_performance(Ra = daily_return,
Rb = mkt_daily_return,
scale = 252,
performance_fun = table.CAPM)
# Rolling Beta is not working
#Function that is not working
roll_beta <- rollify(.f = function(xy){ tq_performance(data = xy,
Ra = daily_return,
Rb = mkt_daily_return,
scale = 252,
performance_fun = table.CAPM)},
window = 40)
# This fails
all_returns_df %>% roll_beta()
Any ideas on how to make this work for me?
My main aim is to do this in a "tidy" way.