Skip to content

Add sign to level shifts? #142

@raneameya

Description

@raneameya

Thank you for the amazing package. It's makes so much sense to have a *verse of time series packages that talk well with each other.

I'm trying to correct for level shifts in a tsibble, but noticed that the level shift was not signed. In the example below, would it make sense for the two outputs to have different signs?

library(tsibble)
library(feasts)
tsbl <- data.frame(
  Date    = seq(as.Date('2020-01-01'), length.out = 100L, by = '1 day'), 
  Value1 = c(rep(0, times = 50L), rep(10, times = 50L)), 
  Value2 = c(rep(0, times = 50L), rep(-10, times = 50L))
) %>% 
  as_tsibble(index = Date)

tsbl %>%
  features(Value1, shift_level_max) # Expect shift_level_max = 10
tsbl %>%
  features(Value2, shift_level_max) # Expect shift_level_max  = -10

A slight modification to the existing function can allow for this possibility.

shift_level_max <- function (x, .size = NULL, .period = 1) 
{
  if (is.null(.size)) {
    .size <- ifelse(.period == 1, 10, .period)
  }
  rollmean <- slider::slide_dbl(x, mean, .before = .size - 
                                  1, na.rm = TRUE)
  means <- diff(rollmean, .size) # get rid of abs(.)
  if (length(means) == 0L) {
    maxmeans <- 0
    maxidx <- NA_real_
  }
  else if (all(is.na(means))) {
    maxmeans <- NA_real_
    maxidx <- NA_real_
  }
  else {
    maxidx <- which.max(abs(means)) + 1L # include abs(.) in here
    maxmeans <- means[maxidx]
  }
  return(c(shift_level_max = maxmeans, shift_level_index = maxidx))
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions