API Reference

Types

Sarimax.SARIMAModelType

The SARIMAModel struct represents a SARIMA model. It contains the following fields:

  • y: The time series data.
  • p: The autoregressive order for the non-seasonal part.
  • d: The degree of differencing.
  • q: The moving average order for the non-seasonal part.
  • seasonality: The seasonality period.
  • P: The autoregressive order for the seasonal part.
  • D: The degree of seasonal differencing.
  • Q: The moving average order for the seasonal part.
  • metadata: A dictionary containing model metadata.
  • exog: Optional exogenous variables.
  • c: The constant term.
  • trend: The trend term.
  • ϕ: The autoregressive coefficients for the non-seasonal part.
  • θ: The moving average coefficients for the non-seasonal part.
  • Φ: The autoregressive coefficients for the seasonal part.
  • Θ: The moving average coefficients for the seasonal part.
  • ϵ: The residuals.
  • exogCoefficients: The coefficients of the exogenous variables.
  • σ²: The variance of the residuals.
  • fitInSample: The in-sample fit.
  • forecast: The forecast.
  • silent: Whether to suppress output.
  • allowMean: Whether to include a mean term in the model.
  • allowDrift: Whether to include a drift term in the model.
  • keepProvidedCoefficients: Whether to keep the provided coefficients.
  • lambda: The regularization strength parameter for lasso, ridge, or elastic net regularization.
  • alpha: The mixing parameter for elastic net regularization (0 ≤ alpha ≤ 1). Alpha = 1 is lasso, alpha = 0 is ridge.
source
Sarimax.DatasetsType

The Datasets Enum is used to identify the dataset used in the load_dataset function.

The Datasets Enum is defined as follows:

  • AIR_PASSENGERS = 1
  • GDPC1 = 2
  • NROU = 3

The load_dataset function uses this Enum to determine the dataset to be loaded.

source

Exceptions

Sarimax.ModelNotFittedType
struct ModelNotFitted <: Exception

An exception type that indicates the model has not been fitted yet.

Usage

This exception can be thrown when an operation that requires a fitted model is attempted on an unfitted model.

source
Sarimax.MissingMethodImplementationType
MissingMethodImplementation <: Exception

Custom exception type for indicating that a required method is not implemented in the model.

Fields

  • method::String: The name of the method that is missing.
source
Sarimax.MissingExogenousDataType
MissingExogenousData <: Exception

An exception type that indicates the absence of exogenous data required for forecasting the requested horizon.

source
Sarimax.InvalidParametersCombinationType
InvalidParametersCombination <: Exception

A custom exception type to indicate that the combination of parameters provided to the model is invalid.

Fields

  • msg::String: A message describing why the parameters are invalid.
source

Model specification

Sarimax.SARIMAFunction
SARIMA constructor.

Parameters:
- y: TimeArray with the time series.
- p: Int with the autoregressive order for the non-seasonal part.
- d: Int with the degree of differencing.
- q: Int with the moving average order for the non-seasonal part.
- seasonality: Int with the seasonality period.
- P: Int with the autoregressive order for the seasonal part.
- D: Int with the degree of seasonal differencing.
- Q: Int with the moving average order for the seasonal part.
- silent: Bool to supress output.
- allowMean: Bool to include a mean term in the model.
- allowDrift: Bool to include a drift term in the model.
source

SARIMA constructor to initialize model with provided coefficients.

Parameters:

  • y: TimeArray with the time series.
  • exog: TimeArray with the exogenous variables.
  • arCoefficients: Vector with the autoregressive coefficients.
  • maCoefficients: Vector with the moving average coefficients.
  • seasonalARCoefficients: Vector with the autoregressive coefficients for the seasonal component.
  • seasonalMACoefficients: Vector with the moving average coefficients for the seasonal component.
  • mean: Float with the mean term.
  • trend: Float with the trend term.
  • exogCoefficients: Vector with the exogenous coefficients.
  • d: Int with the degree of differencing.
  • D: Int with the degree of seasonal differencing.
  • seasonality: Int with the seasonality period.
  • silent: Bool to supress output.
  • allowMean: Bool to include a mean term in the model.
  • allowDrift: Bool to include a drift term in the model.
source
SARIMA constructor.

Parameters:
- y: TimeArray with the time series.
- exog: TimeArray with the exogenous variables.
- p: Int with the order of the AR component.
- d: Int with the degree of differencing.
- q: Int with the order of the MA component.
- seasonality: Int with the seasonality period.
- P: Int with the order of the seasonal AR component.
- D: Int with the degree of seasonal differencing.
- Q: Int with the order of the seasonal MA component.
- silent: Bool to supress output.
- allowMean: Bool to include a mean term in the model.
- allowDrift: Bool to include a drift term in the model.
source

Estimation

Sarimax.fit!Function
fit!(
    model::SARIMAModel;
    silent::Bool=true,
    optimizer::DataType=Ipopt.Optimizer,
    objectiveFunction::String="mse"
    automaticExogDifferentiation::Bool=false
    invertible::Bool=false
    invertibilityMargin::AbstractFloat=0.0
)

Estimate the SARIMA model parameters via conditional least squares (CSS) formulated as a JuMP optimization problem: the residuals are decision variables tied to the data by the model dynamics, and the first lb-1 pre-sample residuals are fixed at zero. No Kalman filter / exact likelihood is used; the "ml" objective is the concentrated conditional Gaussian likelihood (equivalent to least squares in the coefficients). The resulting optimal parameters as well as the residuals and the model's σ² are stored within the model. The default objective function used to estimate the parameters is the mean squared error (MSE), but it can be changed to the maximum likelihood (ML) by setting the objectiveFunction parameter to "ml".

Arguments

  • model::SARIMAModel: The SARIMA model to be fitted.
  • silent::Bool: Whether to suppress solver output. Default is true.
  • optimizer::DataType: The optimizer to be used for optimization. Default is Ipopt.Optimizer.
  • mipSolver::DataType: The MIP sub-solver used by the Alpine global optimizer for its lower-bounding step. Default is SCIP.Optimizer, which can solve the mixed-integer quadratic (MIQP) relaxations arising from quadratic objectives such as "mse". If HiGHS.Optimizer is supplied it only works with the linear "mae" objective; a warning is issued otherwise. Only relevant when optimizer = Alpine.Optimizer.
  • objectiveFunction::String: The objective function used for estimation. Default is "mse".
  • automaticExogDifferentiation::Bool: Whether to automatically differentiate the exogenous variables. Default is false.
  • invertible::Bool: When true, the (seasonal) moving-average coefficients are generated from bounded reflection coefficients κ via reflectionToMA, guaranteeing an invertible MA polynomial by construction instead of imposing only box bounds on θ/Θ. For q = Q = 1 this is equivalent to the default box bounds; for higher orders it restricts the estimate to the (non-box) invertibility region. Not compatible with the "bilevel" objective. Default is false.
  • invertibilityMargin::AbstractFloat: Margin ρ ∈ [0, 1) that bounds the reflection coefficients to [-(1-ρ), 1-ρ], keeping the solution ρ away from the unit circle. Only used when invertible=true. Default is 0.0.
  • seasonalForm::Symbol: :multiplicative (Box-Jenkins, default) or :additive.
  • stationary::Bool: When true, the (seasonal) AR coefficients are generated from bounded reflection coefficients (partial autocorrelations) via reflectionToAR, guaranteeing a stationary AR polynomial by construction (exact under :multiplicative; per-block only under :additive). Default is false.
  • stationarityMargin::AbstractFloat: Margin in [0, 1) bounding the AR reflection coefficients to [-(1-margin), 1-margin]. Only used when stationary = true.
  • Missing observations: NaN entries in the endogenous series are supported for stationary models (d = D = 0, mse/ml objectives, no exogenous regressors). Each gap becomes a free decision variable whose residual is retained in the objective, yielding the two-sided conditional smoother; σ², the log-likelihood, the effective sample size and the residual diagnostics all exclude the imputed indices. The imputed values are written back into model.y and recorded in model.metadata["nMissing"].
  • initialization::Symbol: CSS conditioning convention. :zeroed (default) fixes the pre-sample residuals at zero and drops the first max(p+sP, q+sQ) differenced observations; :warmup conditions only on the AR-side lags and warm-starts the MA recursion from the beginning of the differenced sample, matching R's arima(..., method = "CSS"). Exact-likelihood (Kalman) initialization is out of scope by design.

Example

julia> airPassengers = load_dataset(AIR_PASSENGERS)

julia> model = SARIMA(airPassengers,0,1,1;seasonality=12,P=0,D=1,Q=1)

julia> fit!(model)
source
Sarimax.autoFunction
auto(
    y::TimeArray;
    exog::Union{TimeArray,Nothing}=nothing,
    seasonality::Int=1,
    d::Int = -1,
    D::Int = -1,
    maxp::Int = 5,
    maxd::Int = 2,
    maxq::Int = 5,
    maxP::Int = 2,
    maxD::Int = 1,
    maxQ::Int = 2,
    maxOrder::Int = 5,
    informationCriteria::String = "aicc",
    allowMean:Union{Bool,Nothing} = nothing,
    allowDrift::Union{Bool,Nothing} = nothing,
    integrationTest::String = "kpss",
    seasonalIntegrationTest::String = "seas",
    objectiveFunction::String = "mse",
    assertStationarity::Bool = true,
    assertInvertibility::Bool = true,
    showLogs::Bool = false,
    outlierDetection::Bool = false
    searchMethod::String = "stepwise"
)

Automatically fits the best SARIMA model according to the specified parameters.

Arguments

  • y::TimeArray: The time series data.
  • exog::Union{TimeArray,Nothing}: Optional exogenous variables. If Nothing, no exogenous variables are used.
  • seasonality::Int: The seasonality period. Default is 1 (non-seasonal).
  • d::Int: The degree of differencing for the non-seasonal part. Default is -1 (auto-select).
  • D::Int: The degree of differencing for the seasonal part. Default is -1 (auto-select).
  • maxp::Int: The maximum autoregressive order for the non-seasonal part. Default is 5.
  • maxd::Int: The maximum integration order for the non-seasonal part. Default is 2.
  • maxq::Int: The maximum moving average order for the non-seasonal part. Default is 5.
  • maxP::Int: The maximum autoregressive order for the seasonal part. Default is 2.
  • maxD::Int: The maximum integration order for the seasonal part. Default is 1.
  • maxQ::Int: The maximum moving average order for the seasonal part. Default is 2.
  • maxOrder::Int: The maximum order for the non-seasonal part. Default is 5.
  • informationCriteria::String: The information criteria to be used for model selection. Options are "aic", "aicc", or "bic". Default is "aicc".
  • allowMean::Union{Bool,Nothing}: Whether to include a mean term in the model. Default is nothing.
  • allowDrift::Union{Bool,Nothing}: Whether to include a drift term in the model. Default is nothing.
  • integrationTest::String: The integration test to be used for determining the non-seasonal integration order. Default is "kpss".
  • seasonalIntegrationTest::String: The integration test to be used for determining the seasonal integration order. Default is "seas".
  • objectiveFunction::String: The objective function to be used for model selection.
  • parallel::Bool: Fit candidate models across Julia threads (experimental; applies to the "grid" and "stepwiseNaive" searches; requires starting Julia with multiple threads). Default is false. Options are "mse", "ml", or "bilevel". Default is "mse".
  • assertStationarity::Bool: Whether to assert stationarity of the fitted model. Default is true.
  • assertInvertibility::Bool: Whether to assert invertibility of the fitted model. Default is true.
  • showLogs::Bool: Whether to suppress output. Default is false.
  • outlierDetection::Bool: Whether to perform outlier detection. Default is false.
  • searchMethod::String: The search strategy: "stepwise" (Hyndman-Khandakar style, default), "stepwiseNaive", "grid" (exhaustive), or "sarimax" (no search: fits a single dense specification at the maximum orders, intended for regularized estimation).

References

  • Hyndman, RJ and Khandakar. "Automatic time series forecasting: The forecast package for R." Journal of Statistical Software, 26(3), 2008.
source

Forecasting and simulation

Sarimax.predict!Function
predict!(
    model::SARIMAModel;
    stepsAhead::Int = 1
    seed::Int = 1234,
    isSimulation::Bool = false,
    displayConfidenceIntervals::Bool = false,
    confidenceLevel::Fl = 0.95
    automaticExogDifferentiation::Bool=false
) where Fl<:AbstractFloat

Predicts the SARIMA model for the next stepsAhead periods. The resulting forecast is stored within the model in the forecast field.

Arguments

  • model::SARIMAModel: The SARIMA model to make predictions.
  • stepsAhead::Int: The number of periods ahead to forecast (default: 1).
  • seed::Int: Seed for random number generation when simulating forecasts (default: 1234).
  • isSimulation::Bool: Whether to perform a simulation-based forecast (default: false).
  • displayConfidenceIntervals::Bool: Whether to display confidence intervals (default: false).
  • confidenceLevel::Fl: The confidence level for the confidence intervals (default: 0.95).
  • automaticExogDifferentiation::Bool: Whether to automatically differentiate the exogenous variables. Default is false.

Example

```julia julia> airPassengers = loaddataset(AIRPASSENGERS)

julia> model = SARIMA(airPassengers, 0, 1, 1; seasonality=12, P=0, D=1, Q=1)

julia> fit!(model)

julia> predict!(model; stepsAhead=12)

source
Sarimax.simulateFunction
simulate(
    model::SARIMAModel,
    stepsAhead::Int = 1,
    numScenarios::Int = 200,
    seed::Int = 1234
)

Simulates the SARIMA model for the next stepsAhead periods assuming that the model's estimated σ². Returns a vector of numScenarios scenarios of the forecasted values.

Arguments

  • model::SARIMAModel: The SARIMA model to simulate.
  • stepsAhead::Int: The number of periods ahead to simulate. Default is 1.
  • numScenarios::Int: The number of simulation scenarios. Default is 200.
  • seed::Int: The seed of the simulation. Default is 1234.

Returns

  • Vector{Vector{AbstractFloat}}: A vector of scenarios, each containing the forecasted values for the next stepsAhead periods.

Example

julia> airPassengers = load_dataset(AIR_PASSENGERS)

julia> model = SARIMA(airPassengers, 0, 1, 1; seasonality=12, P=0, D=1, Q=1)

julia> fit!(model)

julia> scenarios = simulate(model, stepsAhead=12, numScenarios=1000)
source
Sarimax.forecastErrorsFunction
forecastErrors(model::SARIMAModel, maxLags::Int=12)

Computes the h-step-ahead forecast VARIANCES on the original (integrated) scale: the ψ-weights are derived from the AR polynomial composed with the differencing operator (1-B)^d (1-B^s)^D, so the uncertainty accumulated by re-integration is propagated (e.g. ARIMA(0,1,0) yields σ²·h).

References

  • Brockwell, P. J., & Davis, R. A. Time Series: Theory and Methods (page 92). Springer(2009)
source

Coefficients, residuals and inference (StatsAPI)

StatsAPI.coefMethod
coef(model::SARIMAModel)

Estimated coefficients in the order: mean c (if allowMean), drift (if allowDrift), ϕ (AR), θ (MA), Φ (seasonal AR), Θ (seasonal MA), exogenous β. σ² is not included.

source
StatsAPI.coefnamesMethod
coefnames(model::SARIMAModel)

Names matching coef: "c", "drift", "ar_i", "ma_j", "sar_k", "sma_w", and one name per exogenous column.

source
StatsAPI.fittedMethod
fitted(model::SARIMAModel)

In-sample one-step-ahead fitted values on the original (integrated) scale.

source
StatsAPI.nobsMethod
nobs(model::SARIMAModel)

Number of effective observations (residuals) used by the CSS fit.

source
StatsAPI.vcovMethod
vcov(model::SARIMAModel)

Asymptotic covariance of the CSS coefficient estimates, Var(θ̂) ≈ 2σ̂² H⁻¹, where H is the numerical Hessian of the residual sum of squares at the estimate (for least squares H ≈ 2J'J, so this equals the classical σ²(J'J)⁻¹).

source
StatsAPI.stderrorMethod
stderror(model::SARIMAModel)

Asymptotic standard errors of the CSS coefficient estimates (square root of the diagonal of vcov). Entries whose variance estimate is not positive (e.g. estimates on a bound, or flat RSS directions) are returned as NaN with a warning.

source
Sarimax.cssResidualsFunction
cssResiduals(model::SARIMAModel, coefficients::Vector)

Pure-Julia replica of the CSS recursion used by fit!: given a coefficient vector in the coef order, returns the residuals over the effective sample. Used to differentiate the RSS numerically for vcov; cssResiduals(model, coef(model)) ≈ residuals(model).

Assumes the exogenous variables enter as provided (the default automaticExogDifferentiation = false path of fit!).

source

Likelihood and information criteria

Sarimax.loglikeFunction
loglike(model::SarimaxModel)

Conditional (CSS) Gaussian log-likelihood of a fitted model, evaluated at the maximum-likelihood variance σ̂² = RSS / n, with full Gaussian constants:

ℓ = -n/2 * (log(2π) + 1 + log(RSS / n))

where n is the number of effective residuals (the observations used after differencing and conditioning on the pre-sample values). This is the likelihood convention of conditional least squares — comparable to R's arima(..., method = "CSS"), NOT to the exact (Kalman-filter) likelihood reported by default by R and statsmodels.

Arguments

  • model::SarimaxModel: A fitted SARIMAModel object.

Returns

  • The conditional Gaussian log-likelihood.

Errors

  • MissingMethodImplementation("fit!"): Thrown if the fit! method is not implemented for the given model type.
  • ModelNotFitted(): Thrown if the model has not been fitted.
source
Sarimax.aicFunction
aic(K::Int, loglikeVal::Fl) where Fl<:AbstractFloat -> Fl

Calculate the Akaike Information Criterion (AIC) for a given number of parameters and log-likelihood value.

Arguments

  • K::Int: Number of parameters in the model.
  • loglikeVal::Fl: Log-likelihood value of the model.

Returns

The AIC value calculated using the formula: AIC = 2K - 2loglikeVal.

source
aic(model::SarimaxModel; offset::Fl) -> Fl where Fl<:AbstractFloat

Calculate the Akaike Information Criterion (AIC) for a Sarimax model: AIC = 2K - 2ℓ, where is the conditional (CSS) Gaussian log-likelihood (loglike) and K the number of estimated parameters. Comparable to R's arima(..., method = "CSS") convention, not to exact-likelihood AICs.

Arguments

  • model::SarimaxModel: The Sarimax model for which AIC is calculated.
  • offset::Fl: Optional value added to the AIC (kept for call compatibility).
  • K::Int: Optional parameter-count override.

Returns

The AIC value calculated using the number of parameters and log-likelihood value of the model.

Errors

  • Throws a MissingMethodImplementation if the get_hyperparameters_number method is not implemented for the given model type.
source
Sarimax.aiccFunction
aicc(T::Int, K::Int, loglikeVal::Fl) where Fl<:AbstractFloat -> Fl

Calculate the corrected Akaike Information Criterion (AICc) for a given number of observations, number of parameters, and log-likelihood value.

Arguments

  • T::Int: Number of observations in the data.
  • K::Int: Number of parameters in the model.
  • loglikeVal::Fl: Log-likelihood value of the model.

Returns

The AICc value calculated using the formula: AICc = AIC(K, loglikeVal) + ((2KK + 2*K) / (T - K - 1)).

source
aicc(model::SarimaxModel; offset::Fl) -> Fl where Fl<:AbstractFloat

Calculate the Corrected Akaike Information Criterion (AICc) for a Sarimax model.

Arguments

  • model::SarimaxModel: The Sarimax model for which AICc is calculated.
  • offset::Fl=0.0: Offset value to be added to the AICc value.

Returns

The AICc value calculated using the number of parameters, sample size, and log-likelihood value of the model.

Errors

  • Throws a MissingMethodImplementation if the get_hyperparameters_number method is not implemented for the given model type.
source
Sarimax.bicFunction
bic(T::Int, K::Int, loglikeVal::Fl) -> Fl

Calculate the Bayesian Information Criterion (BIC) for a given number of observations, number of parameters, and log-likelihood value.

Arguments

  • T::Int: Number of observations in the data.
  • K::Int: Number of parameters in the model.
  • loglikeVal::Fl: Log-likelihood value of the model.

Returns

The BIC value calculated using the formula: BIC = log(T) * K - 2 * loglikeVal.

source
bic(model::SarimaxModel; offset::Fl) -> Fl where Fl<:AbstractFloat

Calculate the Bayesian Information Criterion (BIC) for a Sarimax model.

Arguments

  • model::SarimaxModel: The Sarimax model for which BIC is calculated.
  • offset::Fl=0.0: Offset value to be added to the BIC value.

Returns

The BIC value calculated using the number of parameters, sample size, and log-likelihood value of the model.

Errors

  • Throws a MissingMethodImplementation if the get_hyperparameters_number method is not implemented for the given model type.
source

Residual diagnostics

Sarimax.ljung_box_testFunction
ljung_box_test(residuals::Vector; lags, fitdf = 0)
ljung_box_test(model::SARIMAModel; lags, fitdf = p + q + P + Q)

Ljung-Box portmanteau test for residual autocorrelation.

Q = n(n+2) Σₖ ρ̂ₖ²/(n−k) over k = 1:lags; under the null of no autocorrelation Q ~ χ²(lags − fitdf). For a fitted model, fitdf defaults to the number of estimated ARMA coefficients (R's checkresiduals convention) and lags to min(2s, n÷5) for seasonal models (min(10, n÷5) otherwise).

Returns

Dict with "test_statistic", "p_value", "lags", "dof".

References

  • Ljung, G. M. & Box, G. E. P. (1978). On a measure of lack of fit in time series models. Biometrika 65(2), 297-303.
source
Sarimax.jarque_bera_testFunction
jarque_bera_test(residuals::Vector)
jarque_bera_test(model::SARIMAModel)

Jarque-Bera test for normality: JB = n/6 · (S² + (K−3)²/4), where S and K are the sample skewness and kurtosis; under the null of normality JB ~ χ²(2).

Returns

Dict with "test_statistic", "p_value", "skewness", "kurtosis".

source

Transformations

Sarimax.boxcox_transformFunction
boxcox_transform(y, λ)

Box-Cox transform: (y^λ − 1)/λ for λ ≠ 0, log(y) for λ = 0. Requires strictly positive data. Accepts a vector or a TimeArray.

source
Sarimax.boxcox_lambdaFunction
boxcox_lambda(y; seasonality = 2, lower = -1.0, upper = 2.0)

Select the Box-Cox λ by Guerrero's (1993) method: split the series into non-overlapping groups of seasonality observations (at least 2) and choose the λ that minimizes the coefficient of variation of σᵢ / μᵢ^(1−λ) across groups — the λ that best stabilizes the variance. This is the method used by forecast::BoxCox.lambda in R.

Returns

The selected λ (grid search on lower:0.01:upper).

References

  • Guerrero, V. M. (1993). Time-series analysis supported by power transformations. Journal of Forecasting 12, 37-48.
source

Model evaluation

Sarimax.cross_validationFunction
cross_validation(y::TimeArray; initialTrainSize, stepsAhead = 1, step = 1,
                 fitFunction = train -> auto(train), showLogs = false)

Rolling-origin evaluation with an expanding window (Hyndman's tsCV scheme): for each origin o = initialTrainSize, initialTrainSize+step, … a model is fitted on y[1:o] by fitFunction and forecast stepsAhead periods; the out-of-sample errors y[o+h] − ŷ[o+h] are collected.

fitFunction receives the training TimeArray and must return a fitted model supporting predict! (e.g. train -> auto(train; seasonality = 12), or a closure that fits a fixed specification). Exogenous variables can be handled by closing over them and slicing inside fitFunction.

Returns

A named tuple:

  • errors::Matrix(origin, horizon) forecast errors (NaN where a fit failed);
  • origins::Vector — the training sizes used;
  • mae, rmse — per-horizon aggregates over origins (skipping NaNs).

Example

cv = cross_validation(y; initialTrainSize = 100, stepsAhead = 12,
                      fitFunction = train -> auto(train; seasonality = 12))
cv.rmse   # 12-vector: RMSE by horizon
source

Stationarity and seasonality tests

Sarimax.kpss_testFunction
kpss_test(y::Vector{T}; regression::Symbol=:c, nlags::Union{Symbol,Int}=:legacy) where T <: AbstractFloat

Kwiatkowski-Phillips-Schmidt-Shin test for stationarity.

Arguments

  • y::Vector{T}: Time series data where T is a floating point type
  • regression::Symbol=:c: The null hypothesis for the KPSS test
    • :c: The data is stationary around a constant (default)
    • :ct: The data is stationary around a trend
  • nlags::Union{Symbol,Int}=:auto: Number of lags to use
    • :auto (default): data-dependent selection of Hobijn et al. (1998)
    • :legacy: int(12 * (n/100)^(1/4)) as in Schwert (1989)
    • Integer value: uses the specified number of lags

Returns

  • Dict: Dictionary containing test results including:
    • test_statistic: KPSS test statistic
    • p_value: p-value of the test
    • critical_values: Dictionary of critical values at different significance levels
    • lags: Number of lags used

Notes

To estimate σ² the Newey-West estimator is used. The p-values are interpolated from Table 1 of Kwiatkowski et al. (1992).

References

  • Kwiatkowski et al. (1992). Testing the null hypothesis of stationarity against the alternative of a unit root. Journal of Econometrics, 54: 159-178.
  • Newey & West (1994). Automatic lag selection in covariance matrix estimation. Review of Economic Studies, 61: 631-653.
  • Schwert (1989). Tests for unit roots: A Monte Carlo investigation. Journal of Business and Economic Statistics, 7(2): 147-159.
source
Sarimax.ocsb_testFunction
ocsb_test(y::Vector{T}; m::Int=12, lag_method::Symbol=:aic, max_lag::Int=3) where T <: AbstractFloat

Perform an OCSB test of seasonality (Osborn, Chui, Smith, and Birchenhall test).

Arguments

  • y::Vector{T}: Time series data
  • m::Int=12: The seasonal differencing term (e.g., 12 for monthly, 4 for quarterly)
  • lag_method::Symbol=:aic: Method for lag selection, one of [:fixed, :aic, :bic, :aicc]
  • max_lag::Int=3: Maximum lag order to consider

Returns

  • Dict: Dictionary containing test results including:
    • test_statistic: OCSB test statistic
    • critical_value: Critical value for the test
    • seasonal_difference: Recommended seasonal differencing (0 or 1)

References

  • Osborn DR, Chui APL, Smith J, and Birchenhall CR (1988). Seasonality and the order of integration for consumption. Oxford Bulletin of Economics and Statistics 50(4):361-377.
source
Sarimax.automatic_differentiationFunction
automatic_differentiation(series; seasonalPeriod=1, seasonalIntegrationTest="seas", integrationTest="kpss", maxd=2)

Automatically applies differentiation to each series in a TimeArray.

Arguments

  • series::TimeArray: The input TimeArray containing the time series data.
  • seasonalPeriod::Int=1: The seasonal period of the time series.
  • seasonalIntegrationTest::String="ocsb": The test used to select the seasonal integration order.
  • integrationTest::String="kpss": The test used to select the integration order.
  • maxd::Int=2: The maximum order of differencing to consider.

Returns

A tuple (diffSeries, diffSeriesMetadata) containing:

  • diffSeries::Vector{TimeArray}: The differentiated time series.
  • diffSeriesMetadata::Vector{Dict{Symbol, Any}}: Metadata containing the integration orders used for differentiation.

Errors

Throws an AssertionError if invalid test options or seasonal period are provided.

source

Differencing utilities

Sarimax.differentiateFunction
differentiate(
    series::TimeArray,
    d::Int=0,
    D::Int=0,
    s::Int=1
)

Differentiates a TimeArray series d times and D times with a seasonal difference of s periods.

Arguments

  • series::TimeArray: The time series data to differentiate.
  • d::Int=0: The number of non-seasonal differences to take.
  • D::Int=0: The number of seasonal differences to take.
  • s::Int=1: The seasonal period for the differences.

Returns

A differentiated TimeArray.

Example

julia> airPassengers = load_dataset(AIR_PASSENGERS)

julia> stationaryAirPassengers = differentiate(airPassengers, d=1, D=1, s=12)
source
differentiate(series::Vector{Fl}, d::Int = 0, D::Int = 0, s::Int = 1) where Fl <: AbstractFloat

Differentiates a vector of values with d non-seasonal differences and D seasonal differences of period s.

Arguments

  • series::Vector{Fl}: The time series data to differentiate.
  • d::Int=0: The number of non-seasonal differences to take.
  • D::Int=0: The number of seasonal differences to take.
  • s::Int=1: The seasonal period for the differences.

Returns

A differentiated vector of values.

Example

# Differentiate a time series with first-order difference and seasonal difference
diff_values = differentiate(values, 1, 1, 12)
source
Sarimax.integrateFunction
integrate(initialValues::Vector{Fl}, diffSeries::Vector{Fl}, d::Int, D::Int, s::Int) where Fl<:AbstractFloat

Converts a differentiated time series back to its original scale.

Arguments

  • initialValues::Vector{Fl}: Initial values of the original time series.
  • diffSeries::Vector{Fl}: Differentiated time series.
  • d::Int: Order of non-seasonal differencing.
  • D::Int: Order of seasonal differencing.
  • s::Int: Seasonal period.

Returns

  • origSeries::Vector{Fl}: Time series in the original scale.
source
Sarimax.differentiated_coefficientsFunction
differentiated_coefficients(d::Int, D::Int, s::Int, Fl::DataType=Float64)

Compute the coefficients for differentiating a time series.

Arguments

  • d::Int: Order of non-seasonal differencing.
  • D::Int: Order of seasonal differencing.
  • s::Int: Seasonal period.
  • Fl: The type of the coefficients. Default is Float64.

Returns

  • coeffs::Vector{AbstractFloat}: Coefficients for differentiation.
source
Sarimax.to_maFunction
to_ma(model::SARIMAModel, maxLags::Int=12)

Convert a SARIMA model to a Moving Average (MA) model.

# Arguments
- `model::SARIMAModel`: The SARIMA model to convert.
- `maxLags::Int=12`: The maximum number of lags to include in the MA model.

# Returns
- `MAmodel::MAModel`: The coefficients of the lagged errors in the MA model.

# References
- Brockwell, P. J., & Davis, R. A. Time Series: Theory and Methods (page 92). Springer(2009)
source

Parameterizations

Sarimax.reflectionToMAFunction
reflectionToMA(κ)

Maps a vector of reflection coefficients κ = (κ₁,…,κ_q) to moving-average coefficients θ = (θ₁,…,θ_q) through the recursion

θ₁⁽¹⁾ = κ₁
θ_m⁽ᵐ⁾ = κ_m,                                  m = 2,…,q
θ_i⁽ᵐ⁾ = θ_i⁽ᵐ⁻¹⁾ + κ_m · θ_{m−i}⁽ᵐ⁻¹⁾,        i = 1,…,m−1
θ_j    = θ_j⁽q⁾,                                j = 1,…,q

When the reflection coefficients satisfy |κ_m| < 1 the resulting MA polynomial is invertible. The entries of κ may be numbers or JuMP variables/expressions; the returned vector then contains the corresponding (possibly nonlinear) expressions.

source
Sarimax.reflectionToARFunction
reflectionToAR(κ)

Maps reflection coefficients (partial autocorrelations) κ to AR coefficients via the Levinson-Durbin recursion (the AR analogue of reflectionToMA, with the opposite sign):

φ_m⁽ᵐ⁾ = κ_m
φ_i⁽ᵐ⁾ = φ_i⁽ᵐ⁻¹⁾ − κ_m · φ_{m−i}⁽ᵐ⁻¹⁾

When |κ_m| < 1 the resulting AR polynomial is stationary. Entries may be numbers or JuMP variables/expressions.

source

Data handling

Sarimax.load_datasetFunction
load_dataset(
    dataset::Datasets
)

Loads a dataset from the Datasets enum.

Example

julia> airPassengers = load_dataset(AIR_PASSENGERS)
204×1 TimeArray{Float64, 1, Date, Vector{Float64}} 1991-07-01 to 2008-06-01
│            │ value   │
├────────────┼─────────┤
│ 1991-07-01 │ 3.5266  │
│ 1991-08-01 │ 3.1809  │
│ ⋮          │ ⋮       │
│ 2008-06-01 │ 19.4317 │
source
load_dataset(
    df::DataFrame,
    showLogs::Bool=false
)

Loads a dataset from a Dataframe. If the DataFrame does not have a column named date a new column will be created with the index of the DataFrame.

Arguments

  • df::DataFrame: The DataFrame to be converted to a TimeArray.
  • showLogs::Bool=false: If true, logs will be shown.

Example

julia> airPassengersDf = CSV.File("datasets/airpassengers.csv") |> DataFrame
julia> airPassengers = load_dataset(airPassengersDf)
204×1 TimeArray{Float64, 1, Date, Vector{Float64}} 1991-07-01 to 2008-06-01
│            │ value   │
├────────────┼─────────┤
│ 1991-07-01 │ 3.5266  │
│ 1991-08-01 │ 3.1809  │
│ ⋮          │ ⋮       │
│ 2008-06-01 │ 19.4317 │
source
load_dataset(table; timestampColumn = :date, showLogs = false)

Load any Tables.jl-compatible source (named tuple of vectors, CSV.File, Arrow table, …) as a TimeArray. If timestampColumn is present it is used as the time index; otherwise a synthetic index is created (see the DataFrame method).

source
Sarimax.split_train_testFunction
split_train_test(
    data::TimeArray;
    trainSize::Fl=0.8
) where Fl<:AbstractFloat

Splits the time series in training and testing sets.

source
Sarimax.build_datetimesFunction
build_datetimes(startDatetime, granularity, weekDaysOnly, datetimesLength)

Builds an array of DateTime objects based on a given starting DateTime, granularity, and length.

Arguments

  • startDatetime::T: The DateTime from which the dateTime array will be computed. It won't be included in the final array
  • granularity::Dates.Period: The granularity by which to increment the timestamps.
  • weekDaysOnly::Bool: Whether to include only weekdays (Monday to Friday) in the timestamps.
  • datetimesLength::Int: The length of the array of DateTime objects to build.

Returns

An array of DateTime objects.

source
Sarimax.identify_granularityFunction
identify_granularity(datetimes::Vector{T})

Identifies the granularity of an array of timestamps.

Arguments

  • datetimes::Vector{T}: An array of TimeType objects.

Returns

A tuple (granularity, frequency, weekdays) where:

  • granularity: The identified granularity, which could be one of [:Second, :Minute, :Hour, :Day, :Week, :Month, :Year].
  • frequency: The frequency of the identified granularity.
  • weekdays: A boolean indicating whether the series uses weekdays only.

Errors

Throws an error if the timestamps do not follow a consistent pattern.

source
Sarimax.copy_time_arrayFunction
copy_time_array(y::TimeSeries.TimeArray)

Create a shallow copy of a TimeArray object.

This function creates a new TimeArray with copies of the timestamp and values from the original TimeArray. The new TimeArray is independent of the original, but the elements themselves are not deeply copied.

Arguments

  • y::TimeSeries.TimeArray: The TimeArray to copy.

Returns

  • TimeSeries.TimeArray: A new TimeArray with copies of the timestamp and values.

Examples

original = TimeArray(Date.(2021:2023), [1, 2, 3])
copied = copy_time_array(original)
source
Sarimax.deepcopy_time_arrayFunction
deepcopy_time_array(y::TimeSeries.TimeArray)

Create a deep copy of a TimeArray object.

This function creates a new TimeArray with deep copies of the timestamp and values from the original TimeArray. The new TimeArray and all its elements are completely independent of the original.

Arguments

  • y::TimeSeries.TimeArray: The TimeArray to deep copy.

Returns

  • TimeSeries.TimeArray: A new TimeArray with deep copies of the timestamp and values.

Examples

original = TimeArray(Date.(2021:2023), [1, 2, 3])
deepCopied = deepcopy_time_array(original)
source

MLJ integration

Sarimax.SARIMAForecasterType
SARIMAForecaster(; p = 0, d = 0, q = 0, P = 0, D = 0, Q = 0, seasonality = 1,
                 allowMean = true, allowDrift = false,
                 objectiveFunction = "mse", seasonalForm = :multiplicative,
                 initialization = :zeroed)

MLJ-compatible deterministic forecaster wrapping SARIMA/fit!. The target y is a real vector sampled at equal intervals; features X are ignored at present (exogenous variables via MLJ are not yet supported — use the native SARIMA/auto API for SARIMAX). predict(mach, Xnew) returns the nrows(Xnew)-step-ahead forecast.

source

Display

Base.printFunction
print(model::SARIMAModel)

Prints the full fitted-model summary (alias for show(stdout, MIME"text/plain"(), model)).

source

Introspection

Sarimax.has_fit_methodsFunction
has_fit_methods(modelType::Type{<:SarimaxModel}) -> Bool

Check if a given SarimaxModel type has the fit! method implemented.

Arguments

  • modelType::Type{<:SarimaxModel}: Type of the Sarimax model to check.

Returns

A boolean indicating whether the fit! method is implemented for the specified model type.

source
Sarimax.has_hyperparameters_methodsFunction
has_hyperparameters_methods(modelType::Type{<:SarimaxModel}) -> Bool

Checks if a given SarimaxModel type has methods related to hyperparameters.

Arguments

  • modelType::Type{<:SarimaxModel}: Type of the Sarimax model to check.

Returns

A boolean indicating whether the hyperparameter-related methods are implemented for the specified model type.

source
Sarimax.get_hyperparameters_numberFunction
get_hyperparameters_number(model::SARIMAModel)

Returns the number of estimated parameters K of a SARIMA model (including σ²), as used by the information criteria.

For regular objectives every declared parameter counts, regardless of the magnitude of its estimate — a coefficient estimated near zero was still estimated. For elastic-net fits (lambda/alpha set) the count is instead the number of ACTIVE coefficients (|coef| > 1e-5), the standard effective-degrees- of-freedom estimate for L1-type regularization (Zou, Hastie & Tibshirani, 2007).

Arguments

  • model::SARIMAModel: The SARIMA model.

Returns

  • Int: The number of parameters K.
source