library(recipes)
library(dplyr)
library(ggplot2)
# Training Data
FB_tbl <- FANG %>%
filter(symbol == "FB") %>%
select(symbol, date, adjusted)
# New Data - Make some fake new data next 90 time stamps
new_data <- FB_tbl %>%
tail(90) %>%
mutate(date = date %>% tk_make_future_timeseries(length_out = 90))
# OVERWRITE EXISTING COLUMNS -----
# Create a recipe object with a step_slidify
rec_ma_50 <- recipe(adjusted ~ ., data = FB_tbl) %>%
step_slidify(adjusted, period = 50, .f = ~ mean(.x))
# Bake the recipe object - Applies the Moving Average Transformation
training_data_baked <- bake(prep(rec_ma_50), FB_tbl)
# Apply to New Data
new_data_baked <- bake(prep(rec_ma_50), new_data)
# Visualize effect
training_data_baked %>%
ggplot(aes(date, adjusted)) +
geom_line() +
geom_line(color = "red", data = new_data_baked)
# ---- NEW COLUMNS ----
# Use the `names` argument to create new columns instead of overwriting existing
rec_ma_30_names <- recipe(adjusted ~ ., data = FB_tbl) %>%
step_slidify(adjusted, period = 30, .f = mean, names = "adjusted_ma_30")
bake(prep(rec_ma_30_names), FB_tbl) %>%
ggplot(aes(date, adjusted)) +
geom_line(alpha = 0.5) +
geom_line(aes(y = adjusted_ma_30), color = "red", size = 1)
Run the code above in your browser using DataLab