# NOT RUN {
library(tidyverse)
library(tidyquant)
library(timetk)
# Training Data
FB_tbl <- FANG %>%
filter(symbol == "FB") %>%
select(symbol, date, adjusted)
# ---- FUNCTION FORMAT ----
# - The `.f = mean` function is used. Argument `na.rm = TRUE` is passed as ...
FB_tbl %>%
mutate(adjusted_30_ma = slidify_vec(
.x = adjusted,
.period = 30,
.f = mean,
na.rm = TRUE,
.align = "center")) %>%
ggplot(aes(date, adjusted)) +
geom_line() +
geom_line(aes(y = adjusted_30_ma), color = "blue")
# ---- FORMULA FORMAT ----
# - Anonymous function `.f = ~ mean(., na.rm = TRUE)` is used
FB_tbl %>%
mutate(adjusted_30_ma = slidify_vec(
.x = adjusted,
.period = 30,
.f = ~ mean(., na.rm = TRUE),
.align = "center")) %>%
ggplot(aes(date, adjusted)) +
geom_line() +
geom_line(aes(y = adjusted_30_ma), color = "blue")
# ---- PARTIAL VALUES ----
# - set `.partial = TRUE`
FB_tbl %>%
mutate(adjusted_30_ma = slidify_vec(
.x = adjusted,
.f = ~ mean(., na.rm = TRUE),
.period = 30,
.align = "center",
.partial = TRUE)) %>%
ggplot(aes(date, adjusted)) +
geom_line() +
geom_line(aes(y = adjusted_30_ma), color = "blue")
# ---- Loess vs Moving Average ----
# - Loess: Using `.degree = 0` to make less flexible. Comperable to a moving average.
FB_tbl %>%
mutate(
adjusted_loess_30 = smooth_vec(adjusted, period = 30, degree = 0),
adjusted_ma_30 = slidify_vec(adjusted, .f = AVERAGE,
.period = 30, .partial = TRUE)
) %>%
ggplot(aes(date, adjusted)) +
geom_line() +
geom_line(aes(y = adjusted_loess_30), color = "red") +
geom_line(aes(y = adjusted_ma_30), color = "blue") +
labs(title = "Loess vs Moving Average")
# }
Run the code above in your browser using DataLab