library(dplyr)
library(ggplot2)
# 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", na.rm = TRUE)
# ---- 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", na.rm = TRUE)
# ---- 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. Comparable to a moving average.
FB_tbl %>%
mutate(
adjusted_loess_30 = smooth_vec(adjusted, period = 30, degree = 0),
adjusted_ma_30 = slidify_vec(adjusted, .f = mean,
.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