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.
Note: tibbletime has been retired. You should look into timetk.
Now timetk has the
slidify
instead ofrollify
function. But I couldn't get it to work correctly as it keeps complaining about the period. But going back tozoo::rollapply
does the trick. Also getting the whole table is for also an issue for some reason.The code below will work for the example given and return the beta's. I'm using the function
CAPM.beta
to return the beta's.You can ignore the warning messages. These come from
time_tk::tk_xts
For faster implementations of the function you can find several examples in this SO post.