Skip to content

Instantly share code, notes, and snippets.

@DavisVaughan
Created September 14, 2017 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavisVaughan/fddb90442625f71a78cfe6e5805f4954 to your computer and use it in GitHub Desktop.
Save DavisVaughan/fddb90442625f71a78cfe6e5805f4954 to your computer and use it in GitHub Desktop.
# devtools::install_github("business-science/tibbletime")
library(tibbletime)
#>
#> Attaching package: 'tibbletime'
#> The following object is masked from 'package:stats':
#>
#> filter
library(tidyverse)
#> Loading tidyverse: ggplot2
#> Loading tidyverse: tibble
#> Loading tidyverse: tidyr
#> Loading tidyverse: readr
#> Loading tidyverse: purrr
#> Loading tidyverse: dplyr
#> Conflicts with tidy packages ----------------------------------------------
#> filter(): dplyr, tibbletime, stats
#> lag(): dplyr, stats
# Create a rolling version of any function
mean_roll_5 <- rollify(~mean(.x), window = 5)
mean_roll_8 <- rollify(~mean(.x), window = 8)
cor_roll_5 <- rollify(~cor(.x, .y), window = 5)
# Load up Facebook stock prices
data(FB)
# Just a common call to `mutate`, but using rolling functions!
FB %>%
mutate(rolling_mean_5 = mean_roll_5(adjusted),
rolling_mean_8 = mean_roll_8(adjusted),
rolling_cor_5 = cor_roll_5(adjusted, high))
#> # A tibble: 1,008 x 11
#> symbol date open high low close volume adjusted
#> <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 FB 2013-01-02 27.44 28.18 27.42 28.00 69846400 28.00
#> 2 FB 2013-01-03 27.88 28.47 27.59 27.77 63140600 27.77
#> 3 FB 2013-01-04 28.01 28.93 27.83 28.76 72715400 28.76
#> 4 FB 2013-01-07 28.69 29.79 28.65 29.42 83781800 29.42
#> 5 FB 2013-01-08 29.51 29.60 28.86 29.06 45871300 29.06
#> 6 FB 2013-01-09 29.67 30.60 29.49 30.59 104787700 30.59
#> 7 FB 2013-01-10 30.60 31.45 30.28 31.30 95316400 31.30
#> 8 FB 2013-01-11 31.28 31.96 31.10 31.72 89598000 31.72
#> 9 FB 2013-01-14 32.08 32.21 30.62 30.95 98892800 30.95
#> 10 FB 2013-01-15 30.64 31.71 29.88 30.10 173242600 30.10
#> # ... with 998 more rows, and 3 more variables: rolling_mean_5 <dbl>,
#> # rolling_mean_8 <dbl>, rolling_cor_5 <dbl>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment