Skip to content

Instantly share code, notes, and snippets.

@AdamSpannbauer
Created March 19, 2023 15:20
Show Gist options
  • Save AdamSpannbauer/9989301ea95e7e23192d005a6b0479cb to your computer and use it in GitHub Desktop.
Save AdamSpannbauer/9989301ea95e7e23192d005a6b0479cb to your computer and use it in GitHub Desktop.
Small helper function for suggesting number of lags in Ljung-Box test per Rob Hyndman advice in fpp3
# From: https://otexts.com/fpp3/diagnostics.html#portmanteau-tests-for-autocorrelation
#
# We suggest using l = 10 for non-seasonal data and l = 2 * m for seasonal data, where m is the period of
# seasonality. However, the test is not good when l is large, so
# if these values are larger than T / 5 then use l = T / 5.
# Translating into R function:
# * n_obs - number of observations in the series (referred to as T in the text)
# * n_seasonal_periods - NA if non-seasonal; 4 if quarterly; 12 if monthly; etc.
suggest_ljung_box_lags <- function(n_obs, n_seasonal_periods = 4) {
if (is.na(n_seasonal_periods)) {
# We suggest using l = 10 for non-seasonal data
suggested_n_lags <- 10
} else {
# We suggest using ... l = 2*m for seasonal data,
# where m is the period of seasonality
suggested_n_lags <- 2 * n_seasonal_periods
}
# However, the test is not good when l is large, so
# if these values are larger than T / 5 then use l = T / 5
max_lags <- floor(n_obs / 5)
if (suggested_n_lags > max_lags) {
suggested_n_lags <- max_lags
}
return(suggested_n_lags)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment