-
-
Save perlatex/d87a29bf96d9abfa39ab7a5e79c7e25e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
library(slider) | |
library(lubridate) | |
library(tsibbledata) | |
# Google, Apple, Facebook, Amazon stock | |
gafa_stock <- as_tibble(gafa_stock) | |
gafa_stock <- select(gafa_stock, Symbol, Date, Close, Volume) | |
head(gafa_stock, 2) | |
#> # A tibble: 2 x 4 | |
#> Symbol Date Close Volume | |
#> <chr> <date> <dbl> <dbl> | |
#> 1 AAPL 2014-01-02 79.0 58671200 | |
#> 2 AAPL 2014-01-03 77.3 98116900 | |
# Insert complex model here... | |
model <- function(df) { | |
lm(Close ~ Volume, df) | |
} | |
# Arrange and group by `Symbol` (i.e. stock) | |
gafa_stock <- gafa_stock %>% | |
arrange(Symbol, Date) %>% | |
group_by(Symbol) | |
# - `cur_data()` to get the current group's data frame | |
# - 10 day rolling regression per group (current day + 9 days before) | |
gafa_stock %>% | |
mutate( | |
regression = slide_index( | |
.x = cur_data(), | |
.i = Date, | |
.f = model, | |
.before = days(9), | |
.complete = TRUE | |
) | |
) | |
#> # A tibble: 5,032 x 5 | |
#> # Groups: Symbol [4] | |
#> Symbol Date Close Volume regression | |
#> <chr> <date> <dbl> <dbl> <list> | |
#> 1 AAPL 2014-01-02 79.0 58671200 <NULL> | |
#> 2 AAPL 2014-01-03 77.3 98116900 <NULL> | |
#> 3 AAPL 2014-01-06 77.7 103152700 <NULL> | |
#> 4 AAPL 2014-01-07 77.1 79302300 <NULL> | |
#> 5 AAPL 2014-01-08 77.6 64632400 <NULL> | |
#> 6 AAPL 2014-01-09 76.6 69787200 <NULL> | |
#> 7 AAPL 2014-01-10 76.1 76244000 <NULL> | |
#> 8 AAPL 2014-01-13 76.5 94623200 <lm> | |
#> 9 AAPL 2014-01-14 78.1 83140400 <lm> | |
#> 10 AAPL 2014-01-15 79.6 97909700 <lm> | |
#> # … with 5,022 more rows |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment