# Libraries
library(timetk, exclude = "FANG")
library(dplyr)
# --- Basic Usage ----
CUMULATIVE_SUM(1:10)
PCT_CHANGE(c(21, 24, 22, 25), fill_na = 0)
# --- Usage with tidyverse ---
# Go from daily to monthly periodicity,
# then calculate returns and growth of $1 USD
FANG %>%
mutate(symbol = forcats::as_factor(symbol)) %>%
group_by(symbol) %>%
# Summarization - Collapse from daily to FIRST value by month
summarise_by_time(
.date_var = date,
.by = "month",
adjusted = FIRST(adjusted)
) %>%
# Mutation - Calculate monthly returns and cumulative growth of $1 USD
group_by(symbol) %>%
mutate(
returns = PCT_CHANGE(adjusted, fill_na = 0),
growth = CUMULATIVE_SUM(returns) + 1
)
Run the code above in your browser using DataLab