user25172554
user25172554

Reputation: 1

Rolling-window beta estimation using monthly returns in R-code

I am trying to estimate market betas for each mutual fund (grsp_id) for each month by using 36-months of past data. I used this tutorial https://www.tidy-finance.org/r/beta-estimation.html#rolling-window-estimation

By code looks the same as in the tutorial:

estimate_capm <- function(data, min_obs = 1) {
  if(nrow(data) < min_obs) {
    beta <- as.numeric(NA)
  } else {
    fit <- lm(excess_return ~ excess_market, data = data)
    beta <- as.numeric(coefficients(fit)[2])
  }
  return(beta)
}

roll_capm_estimation <- function(data, months, min_obs) {
  data <- data %>% arrange(month)
  
  betas <- slide_period_vec(
    .x = data,
    .i = data$month,
    .period = "month",
    .f = ~ estimate_capm(., min_obs),
    .before = months - 1,
    .complete = FALSE
  )
  return(tibble(
    month = unique(data$month),
    beta = betas
  ))
}

final_data <- final_data %>%
  group_by(grsp_id) %>%
  mutate(roll_capm_estimation(pick(everything()), months = 36, min_obs = 24)) %>%
  drop_na() %>%
  ungroup()`

The code runs fine for some funds (by grsp_id) but for some it gives the same error: must be size of X (in this example 233) or 1, not X-1 (in this example 232):

Error in mutate(): ℹ In argument: roll_capm_estimation(pick(everything()), months = 36, min_obs = 24). ℹ In group 234: grsp_id = 2005702. Caused by error: ! roll_capm_estimation(pick(everything()), months = 36, min_obs = 24) must be size 233 or 1, not 232. Run rlang::last_trace() to see where the error occurred.

Does anyone have idea what that error means or what it could be related to?

Thanks in advance!

Upvotes: 0

Views: 44

Answers (0)

Related Questions