-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRolling_Window_Time_Series_Regression.Rmd
161 lines (126 loc) · 7.08 KB
/
Rolling_Window_Time_Series_Regression.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
---
title: "Rolling Window Time Series Regression"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Rolling Window Time Series Regression}
%\VignetteEngine{knitr::knitr}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
use_saved_results <- TRUE
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
echo = TRUE,
eval = !use_saved_results,
message = FALSE,
warning = FALSE
)
if (use_saved_results) {
results <- readRDS("vignette_rwtsr.rds")
df_beta <- results$df_beta
}
```
In this short tutorial, I show how to calculate a rolling regression on grouped time series data using `tidyfit`. With very few lines of code, we will be able to estimate and analyze a large number of regressions. As usual, begin by loading necessary libraries:
```{r, eval=TRUE}
library(dplyr); library(tidyr); library(purrr) # Data wrangling
library(ggplot2); library(stringr) # Plotting
library(lubridate) # Date calculations
library(tidyfit) # Model fitting
```
The data set consists monthly industry returns for 10 industries, as well as monthly factor returns for 5 Fama-French factors (data set is available [here](https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html)). The factors are:
1. The market risk premium `Mkt-RF`
2. Size `SMB` (small minus big)
3. Value `HML` (high minus low)
4. Profitability `RMW` (robust minus weak)
5. Investment `CMA` (conservative minus aggressive)
Returns are provided for 10 industries, and excess returns are calculated by subtracting the risk free rate from the monthly industry returns:
```{r, eval=TRUE}
data <- Factor_Industry_Returns
data <- data %>%
mutate(Date = ym(Date)) %>% # Parse dates
mutate(Return = Return - RF) %>% # Excess return
select(-RF)
data
```
The aim of the analysis is to calculate rolling window factor betas using a regression for each industry. To fit a regression for each industry, we simply group the data:
```{r, eval=TRUE}
data <- data %>%
group_by(Industry)
```
Let's verify that this fits individual regressions:
```{r, eval=TRUE}
mod_frame <- data %>%
regress(Return ~ CMA + HML + `Mkt-RF` + RMW + SMB, m("lm"))
mod_frame
```
The model frame now contains 10 regressions estimated using `stats::lm`. We may want to fit the regression using a heteroscedasticity and autocorrelation consistent (HAC) estimate of the covariance matrix, since we are working with financial time series. This can be done by passing the additional argument to `m(...)`:^[Note that the `...` in `m()` passes arguments to the underlying method (i.e. `stats::lm`). However in some cases `tidyfit` adds convenience functions, such as the ability to pass a `vcov.` argument as used in `coeftest` for `lm`.]
```{r, eval=TRUE}
mod_frame_hac <- data %>%
regress(Return ~ CMA + HML + `Mkt-RF` + RMW + SMB, m("lm", vcov. = "HAC"))
mod_frame_hac
```
A rolling window regression can be estimated by specifying an appropriate cross validation method. `tidyfit` uses the `rsample` package from the `tidymodels` suite to create cross validation slices. Apart from the classic CV methods (vfold, loo, expanding window, train/test split), this also includes sliding functions (`sliding_window`, `sliding_index` and `sliding_period`), as well as `bootstraps`. The sliding functions do not generate a validation slice, but only create rolling window training slices. We will be using `sliding_index`, which works well with date indices. See `?rsample::sliding_index` for specifics.^[It is important to note that `sliding_index` can not be used to select hyperparameters since no test slices are produced. To perform time series CV, use the `rolling_origin` setting, which is similar, but produces train and test splits.]
Since the method `lm` has no hyperparameters, it is not passed to the cross validation loop by default, since this would create unnecessary computational overhead. To ensure that models are fitted on train slices, we need to add the additional argument `.force_cv = TRUE`. Furthermore, the CV slices are typically not returned but only used to select optimal hyperparameters. To return slices set `.return_slices = TRUE`:
```{r}
mod_frame_rolling <- data %>%
regress(Return ~ CMA + HML + `Mkt-RF` + RMW + SMB,
m("lm", vcov. = "HAC"),
.cv = "sliding_index", .cv_args = list(lookback = years(5), step = 6, index = "Date"),
.force_cv = TRUE, .return_slices = TRUE)
```
The `.cv_args` are arguments passed directly to `rsample::sliding_index`. We are using a 5 year window (`lookback = years(5)`), and skipping 6 months between each window to reduce the number of models fitted (`step = 6`).
The model frame now contains models for each slice for each industry. The `slice_id` provides the valid date for the respective slices. Betas can be extracted using the built-in `coef` function:
```{r}
df_beta <- coef(mod_frame_rolling)
```
```{r, eval=TRUE}
df_beta
```
In order to plot the betas, we will add confidence bands. HAC standard errors are nested in `model_info` in the coefficients frame:
```{r, eval=TRUE}
df_beta <- df_beta %>%
unnest(model_info) %>%
mutate(upper = estimate + 2 * std.error, lower = estimate - 2 * std.error)
```
```{r, eval=TRUE}
df_beta
```
Now, with all the pieces in place, we can plot the results. Let's begin by examining the market beta for each industry using `ggplot2`:
```{r, fig.width=7, fig.height=5, fig.align="center", eval=TRUE}
df_beta %>%
mutate(slice_id = as.Date(slice_id)) %>%
filter(term == "Mkt-RF") %>%
ggplot(aes(slice_id)) +
geom_hline(yintercept = 1) +
facet_wrap("Industry", scales = "free") +
geom_ribbon(aes(ymax = upper, ymin = lower), alpha = 0.25) +
geom_line(aes(y = estimate)) +
theme_bw(8)
```
Or plotting risk-adjusted return (alpha) given by the intercept:
```{r, fig.width=7, fig.height=5, fig.align="center", eval=TRUE}
df_beta %>%
mutate(slice_id = as.Date(slice_id)) %>%
filter(term == "(Intercept)") %>%
ggplot(aes(slice_id)) +
geom_hline(yintercept = 0) +
facet_wrap("Industry", scales = "free") +
geom_ribbon(aes(ymax = upper, ymin = lower), alpha = 0.25) +
geom_line(aes(y = estimate)) +
theme_bw(8)
```
Or plotting all parameters for the HiTec industry:
```{r, fig.width=6, fig.height=4.25, fig.align="center", eval=TRUE}
df_beta %>%
mutate(slice_id = as.Date(slice_id)) %>%
filter(Industry == "HiTec") %>%
ggplot(aes(slice_id)) +
geom_hline(yintercept = 0) +
facet_wrap("term", scales = "free") +
geom_ribbon(aes(ymax = upper, ymin = lower), alpha = 0.25) +
geom_line(aes(y = estimate)) +
theme_bw(8)
```
While there are certainly very interesting insights to be had here, the aim of this walk-through is not to interpret these results, but rather to demonstrate how a complex piece of analysis can be done very efficiently using the `tidyfit` package.
In a follow-up article found [here](https://tidyfit.unchartedml.com/articles/Time-varying_parameters_vs_rolling_windows.html), I compare the results in the plot above to a time-varying parameter regression to show how more robust methods can be used to avoid window effects in the rolling sample and to shrink some coefficients to constant values.