library(tidyverse)
library(tidyquant)
library(timetk)
# Create a quarterly series with 1 missing value
missing_data_tbl <- tibble(
date = tk_make_timeseries("2014-01-01", "2015-01-01", by = "quarter"),
value = 1:5
) %>%
slice(-4) # Lose the 4th quarter on purpose
missing_data_tbl
# Detects missing quarter, and pads the missing regularly spaced quarter with NA
missing_data_tbl %>% pad_by_time(date, .by = "quarter")
# Can specify a shorter period. This fills monthly.
missing_data_tbl %>% pad_by_time(date, .by = "month")
# Can let pad_by_time() auto-detect date and period
missing_data_tbl %>% pad_by_time()
# Can specify a .pad_value
missing_data_tbl %>% pad_by_time(date, .by = "quarter", .pad_value = 0)
# Can then impute missing values
missing_data_tbl %>%
pad_by_time(date, .by = "quarter") %>%
mutate(value = ts_impute_vec(value, period = 1))
# Can specify a custom .start_date and .end_date
missing_data_tbl %>%
pad_by_time(date, .by = "quarter", .start_date = "2013", .end_date = "2015-07-01")
# Can specify a tidyr::fill() direction
missing_data_tbl %>%
pad_by_time(date, .by = "quarter",
.fill_na_direction = "downup",
.start_date = "2013", .end_date = "2015-07-01")
# --- GROUPS ----
# Apply standard NA padding to groups
FANG %>%
group_by(symbol) %>%
pad_by_time(.by = "day")
# Apply constant pad value
FANG %>%
group_by(symbol) %>%
pad_by_time(.by = "day", .pad_value = 0)
# Apply filled padding to groups
FANG %>%
group_by(symbol) %>%
pad_by_time(.by = "day", .fill_na_direction = "down")
Run the code above in your browser using DataLab