View source: R/compute_rolling_value.R
| compute_rolling_value | R Documentation |
Applies an arbitrary summary function over rolling time-period windows.
Each window spans periods units of period (e.g., 12 months). All rows
that fall into the same period receive the value of that period's window.
Before calling .f, rows with any missing values are dropped from the
window; if fewer than min_obs rows remain, the result is NA_real_
instead.
compute_rolling_value(
data,
.f,
period = "month",
periods = 12,
min_obs = periods,
data_options = NULL
)
data |
A data frame with a date column of class |
.f |
A function applied to each window. Receives a data-frame slice (complete cases only) and must return a single scalar value. |
period |
A string specifying the period for rolling windows
(e.g., |
periods |
Number of periods to include in the rolling window. |
min_obs |
Minimum number of non-missing rows required per window.
Defaults to |
data_options |
A list of class |
A numeric vector aligned with the rows of data.
Other rolling and lagging functions:
add_lagged_columns(),
join_lagged_values()
library(dplyr)
# Rolling standard deviation
set.seed(42)
df <- tibble(
date = seq.Date(
from = as.Date("2020-01-01"),
by = "month",
length.out = 24
),
value = rnorm(24)
)
df |>
mutate(
rolling_sd = compute_rolling_value(
pick(everything()),
.f = ~ sd(.x$value, na.rm = TRUE),
period = "month",
periods = 4,
min_obs = 2
)
)
# Rolling last residual from a regression
set.seed(42)
df_reg <- tibble(
date = seq.Date(
from = as.Date("2020-01-01"),
by = "month",
length.out = 60
),
ret_excess = rnorm(60, 0, 0.05),
mkt_excess = rnorm(60, 0, 0.04),
smb = rnorm(60, 0, 0.03),
hml = rnorm(60, 0, 0.03)
)
df_reg |>
mutate(
residual = compute_rolling_value(
pick(everything()),
.f = \(x) {
last(lm(ret_excess ~ mkt_excess + smb + hml, data = x)$residuals)
},
period = "month",
periods = 24,
min_obs = 12
)
)
# Rolling cumulative-return-to-SD ratio
set.seed(42)
df_resid <- tibble(
date = seq.Date(
from = as.Date("2020-01-01"),
by = "month",
length.out = 24
),
int_roll_residual = rnorm(24, 0, 0.02)
)
df_resid |>
mutate(
return_to_sd = compute_rolling_value(
pick(everything()),
.f = ~ (prod(1 + .x$int_roll_residual) - 1) / sd(.x$int_roll_residual),
period = "month",
periods = 12,
min_obs = 12
)
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.