Learn R Programming

tidyfinance (version 0.4.3)

estimate_betas: Estimate Rolling Betas

Description

This function estimates rolling betas for a given model using the provided data. It supports parallel processing for faster computation using the furrr package.

Usage

estimate_betas(
  data,
  model,
  lookback,
  min_obs = NULL,
  use_furrr = FALSE,
  data_options = NULL
)

Value

A tibble with the estimated betas for each time period.

Arguments

data

A tibble containing the data with a date identifier (defaults to date), a stock identifier (defaults to permno), and other variables used in the model.

model

A formula representing the model to be estimated (e.g., ret_excess ~ mkt_excess + smb + hml).

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 lookback.

use_furrr

A logical indicating whether to use the furrr package and its paralellization capabilities. Defaults to FALSE.

data_options

A named list of data_options with characters, indicating the column names required to run this function. The required column names identify dates and the stocks. Defaults to date = date and id = permno.

Examples

Run this code
# 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 and parallelization
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"))

# Change settings via future::plan(strategy = "multisession", workers = 4)
estimate_betas(data_daily, "ret_excess ~ mkt_excess", lubridate::days(90), use_furrr = TRUE)

Run the code above in your browser using DataLab