View source: R/estimate_betas.R
| estimate_betas | R Documentation |
Estimates rolling betas for a given linear model using a fast, vectorized
approach. Instead of fitting one regression per stock and estimation window,
the function collapses the data to additive cumulants (the entries of the
moment matrices X'X and X'y) per stock and period, aggregates
these cumulants over rolling calendar windows in a single pass with
slider::slide_index_sum(), and recovers the coefficients via the
closed-form OLS solution \hat\beta = (X'X)^{-1} X'y. This produces
estimates that are numerically identical to a per-window regression, but
fast enough that no per-stock nesting or parallelization is required.
estimate_betas(data, model, lookback, min_obs = NULL, data_options = NULL)
data |
A data frame containing the data with a date identifier
(defaults to |
model |
A character string describing the model to be estimated (e.g.,
|
lookback |
A Period object specifying the number of months, days, hours, minutes, or seconds to look back when estimating the rolling model. |
min_obs |
An integer specifying the minimum number of observations
required to estimate the model. Defaults to 80% of |
data_options |
A list of class |
A data frame with the estimated betas for each entity and period.
It contains the entity and date identifiers, an intercept column (if the
model includes one), and one beta_<variable> column per regressor.
Other estimation functions:
estimate_fama_macbeth(),
estimate_model()
# Estimate monthly betas using monthly return data
set.seed(1234)
data_monthly <- tibble::tibble(
date = rep(seq.Date(from = as.Date("2020-01-01"),
to = as.Date("2020-12-01"), by = "month"), each = 50),
permno = rep(1:50, times = 12),
ret_excess = rnorm(600, 0, 0.1),
mkt_excess = rnorm(600, 0, 0.1),
smb = rnorm(600, 0, 0.1),
hml = rnorm(600, 0, 0.1),
)
estimate_betas(data_monthly, "ret_excess ~ mkt_excess", months(3))
estimate_betas(
data_monthly,
"ret_excess ~ mkt_excess + smb + hml",
months(6)
)
data_monthly |>
dplyr::rename(id = permno) |>
estimate_betas("ret_excess ~ mkt_excess", months(3),
data_options = data_options(id = "id"))
# Estimate monthly betas using daily return data
data_daily <- tibble::tibble(
date = rep(seq.Date(from = as.Date("2020-01-01"),
to = as.Date("2020-12-31"), by = "day"), each = 50),
permno = rep(1:50, times = 366),
ret_excess = rnorm(18300, 0, 0.02),
mkt_excess = rnorm(18300, 0, 0.02),
smb = rnorm(18300, 0, 0.02),
hml = rnorm(18300, 0, 0.02),
)
data_daily <- data_daily |>
dplyr::mutate(date = lubridate::floor_date(date, "month"))
estimate_betas(
data_daily,
"ret_excess ~ mkt_excess",
lubridate::days(90)
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.