R/get_stl_score.R

Defines functions get_stl_score

Documented in get_stl_score

#' Get remainder of time-series decomposition
#' @param dates vector of dates
#' @param dates vector of values corresponding to dates
#' @param granularity character indicating granularity of data, must be one of "daily", "weekly", "monthly"
#' @return vector with residuals of auto.arima fit
#' @export
get_stl_score <- function(dates, values, granularity){

  library(tidyverse)
  library(anomalize)
  library(lubridate)

  df <- tibble(Date = dates, Value = values)
  assertthat::assert_that(is.data.frame(df), msg = "df must be a data.frame")
  assertthat::assert_that(all(granularity %in% c("daily", "weekly", "monthly")), msg = "granularity must be one of daily, monthly, weekly")

  granularity <- granularity %>% unique

  if(granularity == "daily"){
    fit <- time_decompose(df, target = Value, method = "stl", frequency = 7, message = F)
  }

  if(granularity %in% c("weekly", "monthly")){
    fit <- time_decompose(df, target = Value, method = "stl", frequency = 2, message = F)
  }

  return(fit$remainder)
}
td-berlin/anomalizer documentation built on Feb. 21, 2020, 2:03 a.m.