I'm trying to calculate a rolling Beta regression for multiple stocks with a width of 12 past months.
I have the following dataset
Looks like:
I was searching a lot of posts, but somehow I didn't get it to work for my data frame.
func1 <- . %>% {
roll_regres.fit(x = cbind(1, .$MKT_ex),
y = .$r_rf, width = 12L)$coefs }
out <- dt %>%
group_by(Stkcd) %>%
# make it explicit that data needs to be sorted
arrange(Date, .by_group = TRUE) %>%
do(cbind(reg_col = select(., MKT_ex, r_rf) %>% func1,
date_col = select(., Date))) %>%
ungroup
I get the error message:
Error in roll_cpp(Y = y, X = x, window = width, do_compute_R_sqs =
do_compute_R_sqs, : 'dchdd' failed with code -1
My goal is to get an output, which contains the Date, Stkcd (Stocknumber) and the calculatet Beta (r_rf regressed on MKT_ex). What did I miss in my code?
I found also this code in the forum from
G. Grothendieck
, sadly it doesn't work for my dataset and I can't find out why.
rolli <- function(ix) {
data.frame(coef = rollapplyr(ix, width = 12, function(ix) {
coef(lm(y ~ x, data = dat, subset = ix))[2]
}, by = 1), Date = dt$Date[ix][1], Stkcd = dt$Stkcd[ix][1])
}
do.call("rbind", by(1:nrow(dt), dat[c("Date", "Stkcd")], rolli)