API Reference
Types
Sarimax.SARIMAModel — Type
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.
Sarimax.Datasets — Type
The Datasets Enum is used to identify the dataset used in the load_dataset function.
The Datasets Enum is defined as follows:
AIR_PASSENGERS = 1GDPC1 = 2NROU = 3
The load_dataset function uses this Enum to determine the dataset to be loaded.
Exceptions
Sarimax.ModelNotFitted — Type
struct ModelNotFitted <: ExceptionAn 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.
Sarimax.MissingMethodImplementation — Type
MissingMethodImplementation <: ExceptionCustom 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.
Sarimax.MissingExogenousData — Type
MissingExogenousData <: ExceptionAn exception type that indicates the absence of exogenous data required for forecasting the requested horizon.
Sarimax.InconsistentDatePattern — Type
struct InconsistentDatePattern <: ExceptionAn exception type to indicate that the timestamps do not follow a consistent pattern.
Sarimax.InvalidParametersCombination — Type
InvalidParametersCombination <: ExceptionA 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.
Model specification
Sarimax.SARIMA — Function
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.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.
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.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 istrue.optimizer::DataType: The optimizer to be used for optimization. Default isIpopt.Optimizer.mipSolver::DataType: The MIP sub-solver used by the Alpine global optimizer for its lower-bounding step. Default isSCIP.Optimizer, which can solve the mixed-integer quadratic (MIQP) relaxations arising from quadratic objectives such as"mse". IfHiGHS.Optimizeris supplied it only works with the linear"mae"objective; a warning is issued otherwise. Only relevant whenoptimizer = Alpine.Optimizer.objectiveFunction::String: The objective function used for estimation. Default is "mse".automaticExogDifferentiation::Bool: Whether to automatically differentiate the exogenous variables. Default isfalse.invertible::Bool: Whentrue, the (seasonal) moving-average coefficients are generated from bounded reflection coefficientsκviareflectionToMA, guaranteeing an invertible MA polynomial by construction instead of imposing only box bounds onθ/Θ. Forq = Q = 1this 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 isfalse.invertibilityMargin::AbstractFloat: Marginρ ∈ [0, 1)that bounds the reflection coefficients to[-(1-ρ), 1-ρ], keeping the solutionρaway from the unit circle. Only used wheninvertible=true. Default is0.0.seasonalForm::Symbol::multiplicative(Box-Jenkins, default) or:additive.stationary::Bool: Whentrue, the (seasonal) AR coefficients are generated from bounded reflection coefficients (partial autocorrelations) viareflectionToAR, guaranteeing a stationary AR polynomial by construction (exact under:multiplicative; per-block only under:additive). Default isfalse.stationarityMargin::AbstractFloat: Margin in[0, 1)bounding the AR reflection coefficients to[-(1-margin), 1-margin]. Only used whenstationary = true.- Missing observations:
NaNentries in the endogenous series are supported for stationary models (d = D = 0,mse/mlobjectives, 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 intomodel.yand recorded inmodel.metadata["nMissing"]. initialization::Symbol: CSS conditioning convention.:zeroed(default) fixes the pre-sample residuals at zero and drops the firstmax(p+sP, q+sQ)differenced observations;:warmupconditions only on the AR-side lags and warm-starts the MA recursion from the beginning of the differenced sample, matching R'sarima(..., 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)Sarimax.auto — Function
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. IfNothing, 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 isfalse. 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.
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<:AbstractFloatPredicts 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 isfalse.
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)
Sarimax.simulate — Function
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 nextstepsAheadperiods.
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)Sarimax.forecastErrors — Function
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)
Coefficients, residuals and inference (StatsAPI)
StatsAPI.coef — Method
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.
StatsAPI.coefnames — Method
coefnames(model::SARIMAModel)Names matching coef: "c", "drift", "ar_i", "ma_j", "sar_k", "sma_w", and one name per exogenous column.
StatsAPI.residuals — Method
residuals(model::SARIMAModel)The CSS residuals over the effective sample (t = lb:T).
StatsAPI.fitted — Method
fitted(model::SARIMAModel)In-sample one-step-ahead fitted values on the original (integrated) scale.
StatsAPI.nobs — Method
nobs(model::SARIMAModel)Number of effective observations (residuals) used by the CSS fit.
StatsAPI.vcov — Method
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)⁻¹).
StatsAPI.stderror — Method
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.
Sarimax.cssResiduals — Function
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!).
Likelihood and information criteria
Sarimax.loglike — Function
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 thefit!method is not implemented for the given model type.ModelNotFitted(): Thrown if the model has not been fitted.
Sarimax.aic — Function
aic(K::Int, loglikeVal::Fl) where Fl<:AbstractFloat -> FlCalculate 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.
aic(model::SarimaxModel; offset::Fl) -> Fl where Fl<:AbstractFloatCalculate 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
MissingMethodImplementationif theget_hyperparameters_numbermethod is not implemented for the given model type.
Sarimax.aicc — Function
aicc(T::Int, K::Int, loglikeVal::Fl) where Fl<:AbstractFloat -> FlCalculate 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)).
aicc(model::SarimaxModel; offset::Fl) -> Fl where Fl<:AbstractFloatCalculate 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
MissingMethodImplementationif theget_hyperparameters_numbermethod is not implemented for the given model type.
Sarimax.bic — Function
bic(T::Int, K::Int, loglikeVal::Fl) -> FlCalculate 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.
bic(model::SarimaxModel; offset::Fl) -> Fl where Fl<:AbstractFloatCalculate 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
MissingMethodImplementationif theget_hyperparameters_numbermethod is not implemented for the given model type.
Residual diagnostics
Sarimax.ljung_box_test — Function
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.
Sarimax.jarque_bera_test — Function
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".
Transformations
Sarimax.boxcox_transform — Function
boxcox_transform(y, λ)Box-Cox transform: (y^λ − 1)/λ for λ ≠ 0, log(y) for λ = 0. Requires strictly positive data. Accepts a vector or a TimeArray.
Sarimax.inverse_boxcox — Function
inverse_boxcox(z, λ)Inverse of boxcox_transform: (λz + 1)^(1/λ) for λ ≠ 0, exp(z) for λ = 0. Accepts a vector or a TimeArray.
Sarimax.boxcox_lambda — Function
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.
Model evaluation
Sarimax.cross_validation — Function
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 (NaNwhere a fit failed);origins::Vector— the training sizes used;mae,rmse— per-horizon aggregates over origins (skippingNaNs).
Example
cv = cross_validation(y; initialTrainSize = 100, stepsAhead = 12,
fitFunction = train -> auto(train; seasonality = 12))
cv.rmse # 12-vector: RMSE by horizonStationarity and seasonality tests
Sarimax.kpss_test — Function
kpss_test(y::Vector{T}; regression::Symbol=:c, nlags::Union{Symbol,Int}=:legacy) where T <: AbstractFloatKwiatkowski-Phillips-Schmidt-Shin test for stationarity.
Arguments
y::Vector{T}: Time series data where T is a floating point typeregression::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.
Sarimax.ocsb_test — Function
ocsb_test(y::Vector{T}; m::Int=12, lag_method::Symbol=:aic, max_lag::Int=3) where T <: AbstractFloatPerform an OCSB test of seasonality (Osborn, Chui, Smith, and Birchenhall test).
Arguments
y::Vector{T}: Time series datam::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.
Sarimax.automatic_differentiation — Function
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.
Differencing utilities
Sarimax.differentiate — Function
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)differentiate(series::Vector{Fl}, d::Int = 0, D::Int = 0, s::Int = 1) where Fl <: AbstractFloatDifferentiates 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)Sarimax.integrate — Function
integrate(initialValues::Vector{Fl}, diffSeries::Vector{Fl}, d::Int, D::Int, s::Int) where Fl<:AbstractFloatConverts 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.
Sarimax.differentiated_coefficients — Function
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 isFloat64.
Returns
coeffs::Vector{AbstractFloat}: Coefficients for differentiation.
Sarimax.to_ma — Function
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)Parameterizations
Sarimax.reflectionToMA — Function
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,…,qWhen 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.
Sarimax.reflectionToAR — Function
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.
Data handling
Sarimax.load_dataset — Function
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 │
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 │
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).
Sarimax.split_train_test — Function
split_train_test(
data::TimeArray;
trainSize::Fl=0.8
) where Fl<:AbstractFloatSplits the time series in training and testing sets.
Sarimax.build_datetimes — Function
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 arraygranularity::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.
Sarimax.identify_granularity — Function
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.
Sarimax.copy_time_array — Function
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)Sarimax.deepcopy_time_array — Function
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)MLJ integration
Sarimax.SARIMAForecaster — Type
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.
Display
Base.print — Function
print(model::SARIMAModel)Prints the full fitted-model summary (alias for show(stdout, MIME"text/plain"(), model)).
Introspection
Sarimax.has_fit_methods — Function
has_fit_methods(modelType::Type{<:SarimaxModel}) -> BoolCheck 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.
Sarimax.has_hyperparameters_methods — Function
has_hyperparameters_methods(modelType::Type{<:SarimaxModel}) -> BoolChecks 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.
Sarimax.get_hyperparameters_number — Function
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 parametersK.