goarima

package module
v0.0.0-...-e2dcdfa Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 19, 2026 License: MIT Imports: 12 Imported by: 0

README

goarima

Build Status Go Reference

Sunspots forecast comparison

A pure-Go implementation of ARIMA (AutoRegressive Integrated Moving Average) time-series modeling, with automatic order selection, prediction intervals, full multiplicative seasonal (p,d,q)(P,D,Q)ₘ models, and exogenous regressors (the full SARIMAX family, validated against statsmodels SARIMAX).

It fits and forecasts ARIMA(p, d, q) models. By default, coefficients are estimated with the Hannan-Rissanen method (pure linear algebra), so fitting is deterministic and fast. The trade-off is that the estimates are approximate: they will not match a maximum-likelihood library (statsmodels / pmdarima) exactly. Two optional refinement methods tighten the coefficients, selected with WithMethod: a conditional-sum-of-squares search (WithMethod(goarima.CSS)) and an exact Gaussian maximum-likelihood fit via the Kalman filter (WithMethod(goarima.MLE), matching statsmodels' method="statespace" default). See Limitations.

New to time series? docs/arima.md explains ARIMA and every algorithm implemented here — in plain language with the key equations — for readers new to time-series forecasting.

Install

go get github.com/albertyw/goarima

Requires Go 1.25+.

Usage

Automatic order selection

AutoARIMA chooses d with a KPSS stationarity test and then searches p and q (up to the given maxima) to minimize an information criterion, returning a fitted model. By default it minimizes the AIC with an exhaustive grid search; see Order-search options to change the criterion or strategy.

package main

import (
	"fmt"

	"github.com/albertyw/goarima"
)

func main() {
	series := []float64{112, 118, 132, 129, 121, 135, 148, 148, 136, 119 /* … */}

	model, err := goarima.AutoARIMA(series, goarima.Bounds{MaxP: 5, MaxD: 2, MaxQ: 5})
	if err != nil {
		panic(err)
	}

	o := model.Order()
	fmt.Printf("selected ARIMA(%d,%d,%d)\n", o.P, o.D, o.Q)

	forecast, err := model.Forecast(12) // next 12 steps
	if err != nil {
		panic(err)
	}
	fmt.Println(forecast)
}
Fixed orders

When you already know the orders, construct the model directly:

model, err := goarima.NewARIMA(goarima.Order{P: 1, D: 1, Q: 1})
if err != nil {
	panic(err)
}
if err := model.Fit(series); err != nil {
	panic(err)
}
forecast, err := model.Forecast(10)

Fit returns an error for a series that is too short or contains a NaN or infinite value, and Forecast returns an error if the model has not been fitted yet.

Seasonal models (SARIMA)

For seasonal data with a known period m, goarima fits the full multiplicative SARIMA (p,d,q)(P,D,Q)ₘ model — seasonal differencing (1−Bᵐ)ᴰ plus seasonal AR/MA factors Φₛ(Bᵐ)/Θₛ(Bᵐ). NewSARIMA takes the seasonal orders P, D, Q and period m; AutoSARIMA selects D (via the seasonal-strength test), then d, p, q, P, and Q automatically:

// Explicit: the airline model ARIMA(0,1,1)(0,1,1) with period 12.
model, err := goarima.NewSARIMA(
	goarima.Order{P: 0, D: 1, Q: 1},
	goarima.SeasonalOrder{P: 0, D: 1, Q: 1, Period: 12},
)

// Automatic: choose p, d, q, P, Q (and D) for a monthly (m=12) series.
model, err := goarima.AutoSARIMA(
	series,
	goarima.Bounds{MaxP: 3, MaxD: 1, MaxQ: 3},
	goarima.SeasonalBounds{MaxP: 1, MaxQ: 1, Period: 12},
)

SeasonalOrder() returns {P, D, Q, Period}, and SeasonalPhi()/SeasonalTheta() return the seasonal AR/MA factors (Phi()/Theta() return the regular ones). The fit is validated against statsmodels' SARIMAX class at seasonal_order=(P,D,Q,m). AutoSARIMA accepts the same options as AutoARIMA.

Exogenous regressors (SARIMAX)

To let external predictors drive the series, pass an n×k regressor matrix X with WithExog. goarima fits regression with ARIMA errors, yₜ = Xₜ·β + ηₜ, where ηₜ follows the ARIMA model — the same parameterization as statsmodels SARIMAX with exog= and trend="n". Read the coefficients with Beta() and forecast with Forecast / ForecastInterval, passing the future regressor rows (h×k) via WithFutureExog:

model, err := goarima.NewARIMA(goarima.Order{P: 1, D: 0, Q: 0})
err = model.Fit(series, goarima.WithExog(X), goarima.WithMethod(goarima.MLE))
beta := model.Beta()                                              // estimated β (length k)
forecast, err := model.Forecast(12, goarima.WithFutureExog(futureX)) // futureX is 12×k
fc, err := model.ForecastInterval(12, 0.95, goarima.WithFutureExog(futureX))

β is estimated jointly with the ARMA coefficients under WithMethod(goarima.MLE) / WithMethod(goarima.CSS) (a two-step OLS seed otherwise). WithExog also works with NewSARIMA and threads through AutoARIMA / AutoSARIMA. A model fit with exogenous regressors requires WithFutureExog when forecasting (and a plain model rejects it); the mismatch returns an error.

Coefficient refinement

By default Fit uses the Hannan-Rissanen estimate (WithMethod(goarima.HannanRissanen), the zero value). WithMethod selects one of two refinements instead, each a derivative-free Nelder-Mead search seeded from the Hannan-Rissanen fit:

  • WithMethod(goarima.CSS) minimizes the conditional sum of squares (a least-squares fit).
  • WithMethod(goarima.MLE) minimizes the exact Gaussian negative log-likelihood computed with a Kalman filter, matching statsmodels' method="statespace" default.

Both move the coefficients toward a maximum-likelihood fit and never make the fit worse — a refined estimate is kept only if it is stationary, invertible, and strictly improves on the seed, otherwise the seed is used unchanged.

err := model.Fit(series, goarima.WithMethod(goarima.MLE))
// AutoARIMA accepts the same options and threads them through every candidate fit:
model, err := goarima.AutoARIMA(series, goarima.Bounds{MaxP: 5, MaxD: 2, MaxQ: 5}, goarima.WithMethod(goarima.MLE))
Parameter uncertainty (standard errors & Summary)

After an MLE fit, StdErrors() returns the standard error of each coefficient (β, φ, Φₛ, θ, Θₛ, in that order) and Summary() returns those with z-statistics, p-values, 95% confidence intervals, and model fit statistics (log-likelihood, AIC, BIC). The covariance is the inverse observed information (the numeric Hessian of the exact Gaussian log-likelihood), matching statsmodels' .summary() / .bse under cov_type="approx". Both require WithMethod(goarima.MLE) — standard errors come from the likelihood curvature, so a Hannan-Rissanen (default) or CSS fit returns an error.

err := model.Fit(series, goarima.WithMethod(goarima.MLE))
se, err := model.StdErrors() // one standard error per coefficient
summary, err := model.Summary()
fmt.Print(summary) // fixed-width table of coef / std err / z / P>|z| / CI
Repairing unstable fixed-order fits

By default Fit returns an error when the Hannan-Rissanen estimate for an explicit (p,d,q) lands outside the stationary/invertible region. WithRootRepair() instead reflects the offending roots back inside the unit circle (to their reciprocals) and returns a valid model. It composes with WithMethod(goarima.MLE)/WithMethod(goarima.CSS) (repair yields a valid seed the optimizer then refines) and threads through AutoARIMA/AutoSARIMA.

model, _ := goarima.NewARIMA(goarima.Order{P: 0, D: 0, Q: 1})
// Without WithRootRepair this errors when the MA estimate is non-invertible.
err := model.Fit(series, goarima.WithRootRepair())
// model.Theta() is now invertible (roots reflected inside the unit circle).
Order-search options

AutoARIMA takes four further options that tune how the orders are searched. These are AutoOptions, not FitOptions, so they apply only to AutoARIMA / AutoSARIMA — passing one to a plain Fit is a compile-time error:

  • WithCriterion(c) — the information criterion to minimize: AIC (default), BIC (penalizes extra parameters more), or AICc (small-sample-corrected AIC).
  • WithStepwise() — replace the exhaustive grid with a Hyndman-Khandakar stepwise neighbor search. It fits far fewer candidates (a hill-climb from a few seed orders) but is a heuristic and can miss the grid's global optimum.
  • WithParallel() — fit candidate orders concurrently across GOMAXPROCS goroutines. Selection is deterministic and identical to the serial search, so it only changes speed — and it pays off only when each fit is expensive (e.g. with WithMethod(goarima.MLE)); for the fast default Hannan-Rissanen fits the goroutine overhead outweighs the benefit.
  • WithContext(ctx) — cancel a long order search. When ctx is cancelled (or its deadline passes) AutoARIMA/AutoSARIMA stop between candidate fits and return an error wrapping the context cause.
model, err := goarima.AutoARIMA(series, goarima.Bounds{MaxP: 5, MaxD: 2, MaxQ: 5},
    goarima.WithCriterion(goarima.BIC),
    goarima.WithStepwise(),
)
Prediction intervals

ForecastInterval returns the point forecast together with a two-sided prediction interval at a given confidence level. The standard errors come from the model's MA(∞) representation (Var(k steps) = σ²·Σψ²), with the differencing operators folded into the AR side so the bounds are on the original scale:

fc, err := model.ForecastInterval(12, 0.95) // horizon, confidence level
if err != nil {
	panic(err)
}
fc.Point  // point forecast (identical to Forecast(12))
fc.Lower  // lower bounds
fc.Upper  // upper bounds
fc.StdErr // forecast standard errors

The interval widths match statsmodels' get_forecast().conf_int().

Inspecting a fitted model
model.Order()    // Order{P, D, Q}
model.Phi()      // AR coefficients (copy)
model.Theta()    // MA coefficients (copy)
model.Beta()     // exogenous regression coefficients (copy; empty without WithExog)
model.Sigma2()   // residual variance

The slice getters return copies, so mutating the result never affects the model.

The package also exposes the Difference / Undifference helpers used internally.

How it works

series ──Difference(d)──► center (−mean) ──► Hannan-Rissanen ──► phi, theta
                                                  │
                                  Stage 1: long AR(k) by Yule-Walker → residual proxies
                                  Stage 2: OLS of the series on its lags + residual-proxy lags

Forecast runs the AR+MA recursion forward (future errors = 0), adds the mean back, and integrates once per differencing level to return values on the original scale.

For a full, beginner-friendly walkthrough of these algorithms — AR/MA/I, Yule-Walker, Hannan-Rissanen, and AutoARIMA's order selection — with the key equations and links for further reading, see docs/arima.md.

Examples

The example/ directory contains a runnable demo that runs AutoARIMA on several classic datasets (AirPassengers, Lynx, wine sales, sunspots, wool production, and Australian population) and prints the selected orders, coefficients, and forecasts:

cd example && go run .

make example runs example/compare.py, which fits pmdarima at the orders goarima's AutoARIMA selected for each dataset and prints the two results interleaved for easy comparison. It requires the Python environment described in example/pyproject.toml (installed under example/env) and falls back to the goarima-only demo if that environment is absent.

Trend comparison

make charts renders goarima's AutoARIMA forecast against pmdarima's at the same goarima-selected order, writing one chart per dataset to the gitignored example/charts/. Committed copies live under docs/images/ (two shown below). Both sides are exact-MLE fits, so the AR terms goarima picks let the two forecasts follow each series' cyclic shape together (for over-parameterized orders such as wineind's near-unit-root (3,1,3) the amplitudes can still differ).

Wool production (woolyrnq) — goarima AutoARIMA vs pmdarima AirPassengers — goarima AutoARIMA vs pmdarima
Wool Production forecast comparison AirPassengers forecast comparison
Seasonal forecasting (SARIMAX)

docs/examples.md collects worked examples — non-seasonal AutoARIMA (vs pmdarima) and the two seasonal examples below, AirPassengers and WineInd, comparing AutoSARIMA against statsmodels SARIMAX — with the charts inline and the exact settings used to generate them (example/plot_seasonal.py).

AirPassengers — goarima AutoSARIMA vs statsmodels SARIMAX WineInd — goarima AutoSARIMA vs statsmodels SARIMAX
AirPassengers seasonal forecast WineInd seasonal forecast
Regression with ARIMA errors (SARIMAX exog)

docs/examples.md also walks through an exogenous-regressor example (example/plot_exog.py): a covariate-driven demand series where WithExog lets the forecast (with WithFutureExog) track a known future covariate while a plain ARIMA reverts to the mean. goarima's exog forecast lands on top of statsmodels SARIMAX at the same order.

Regression with ARIMA errors

Limitations

This is a pure-Go implementation that aims for clarity over completeness:

  • Approximate by default. The default Hannan-Rissanen fit is close to, but not identical to, statsmodels' default. The optional WithMethod(goarima.MLE) refinement adds an exact Gaussian maximum-likelihood fit (Kalman filter), though small numeric differences from statsmodels remain. For seasonal AR/MA models, the fast default uses an approximate seasonal seed; WithMethod(goarima.MLE) matches SARIMAX.
  • Unstable fixed-order fits are rejected by default; opt into repair. Without WithRootRepair(), an explicit (p,d,q) whose Hannan-Rissanen estimate falls outside the stationary/invertible region returns an error. Pass WithRootRepair() to instead reflect the offending roots back inside the unit circle and return a valid model. (WithMethod(goarima.MLE)/WithMethod(goarima.CSS) already keep the refined fit in-region, matching statsmodels' default enforce_*.)

Development

make test      # unit tests, vet, gofmt, go mod tidy, golangci-lint, govulncheck
make race      # race detector
make cover     # coverage report
make benchmark # benchmarks
make charts    # trend-comparison charts -> example/charts/ (gitignored; needs example/env)
Integration tests

integration_test.go (in the external goarima_test package, so it uses only the exported API) compares goarima against committed reference fixtures — no network or Python at test time. It checks fixed-order fits and auto_arima selection against pmdarima, a seasonal NewSARIMA fit against statsmodels SARIMAX, analytic closed-forms, and a goarima golden baseline (including an AutoSARIMA lock). Regenerate the fixtures (needs the example/env venv) when goarima's numerics intentionally change:

cd example && env/bin/python gen_reference.py   # pmdarima reference fixtures
go test -run TestGoldenWithMLE -update          # goarima golden baseline

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Difference

func Difference(y []float64, d int) []float64

Difference applies d-th order differencing to the series, returning a series of length len(y)-d. Each pass replaces the series with consecutive differences.

func SeasonalDifference

func SeasonalDifference(y []float64, m, D int) []float64

SeasonalDifference applies D passes of lag-m differencing to y, returning a series of length len(y)-D*m. Each pass replaces y_t with y_t - y_{t-m}. A pass on a series of length <= m returns an empty slice. D == 0 returns a copy.

func SeasonalUndifference

func SeasonalUndifference(diffPred, anchor []float64) []float64

SeasonalUndifference reverses one pass of lag-m seasonal differencing by adding each value of diffPred to the value m steps earlier. anchor holds the last m values on the pre-difference scale in chronological order (oldest first): the first m results integrate onto anchor, later ones onto earlier results. The seasonal period m is len(anchor).

func Undifference

func Undifference(diffPred []float64, lastOrig float64) []float64

Undifference reverses a single order of differencing by cumulatively summing diffPred onto lastOrig, the last observed value on the original scale.

Types

type ARIMA

type ARIMA struct {
	// contains filtered or unexported fields
}

func AutoARIMA

func AutoARIMA(series []float64, max Bounds, opts ...AutoOption) (*ARIMA, error)

AutoARIMA selects ARIMA orders automatically and returns a fitted model.

The differencing order d is chosen by the KPSS stationarity test (difference until the series tests stationary, up to max.MaxD). The non-seasonal orders p and q are then chosen by an exhaustive grid search over 0..max.MaxP and 0..max.MaxQ that minimizes an information criterion; the (0,0) combination is skipped. Candidate orders whose fit fails (e.g. too few observations) are skipped.

The criterion defaults to AIC and can be changed with WithCriterion (AIC, BIC, or AICc). Any FitOption (e.g. WithMethod) is threaded through to every candidate fit and the final refit, so candidates are scored and the final model is fit with the same options.

Note that the criterion is always computed from the residual variance (see score), even when WithMethod(MLE) is supplied: the refinement lowers each candidate's residual variance and thus influences selection, but the score is not the exact Gaussian-likelihood criterion. A likelihood-based criterion is left to a later phase.

func AutoSARIMA

func AutoSARIMA(series []float64, max Bounds, seasonal SeasonalBounds, opts ...AutoOption) (*ARIMA, error)

AutoSARIMA selects seasonal ARIMA orders automatically for a known seasonal period seasonal.Period (>= 2) and returns a fitted model. It chooses the seasonal differencing order D (0 or 1) with the seasonal-strength measure, then the regular differencing order d with the KPSS test on the seasonally- differenced series, then the non-seasonal orders p,q and the seasonal AR/MA orders P,Q with the same search AutoARIMA uses, over 0..max.MaxP, 0..max.MaxQ, 0..seasonal.MaxP, 0..seasonal.MaxQ (grid by default; WithStepwise / WithParallel honored).

The criterion defaults to AIC (WithCriterion to change it). Any FitOption (e.g. WithMethod) is threaded through to every candidate fit and the final refit, exactly as in AutoARIMA.

func NewARIMA

func NewARIMA(order Order) (*ARIMA, error)

NewARIMA constructs a non-seasonal ARIMA model. It is shorthand for NewSARIMA(order, SeasonalOrder{}).

func NewSARIMA

func NewSARIMA(order Order, seasonal SeasonalOrder) (*ARIMA, error)

NewSARIMA constructs a seasonal ARIMA model of the multiplicative class

φ(B)·Φₛ(Bᵐ)·(1−B)ᵈ(1−Bᵐ)ᴰ y_t = θ(B)·Θₛ(Bᵐ)·ε_t,

with non-seasonal orders order and seasonal orders seasonal. The seasonal period must be >= 2 whenever any seasonal order (P, D, or Q) is positive.

func (*ARIMA) Beta

func (m *ARIMA) Beta() []float64

Beta returns a copy of the exogenous regression coefficients (length k), or an empty slice when the model was fit without exogenous regressors.

func (*ARIMA) Fit

func (m *ARIMA) Fit(series []float64, opts ...FitOption) error

Fit estimates the model's coefficients from series. It differences the series (seasonally then regularly) per the configured orders, centers it, and fits the (multiplicative seasonal) ARMA factors by Hannan-Rissanen; WithMethod(CSS) or WithMethod(MLE) then refines that seed. WithExog fits regression with ARIMA errors, and WithRootRepair reflects an unstable estimate back into the stationary/invertible region instead of erroring. After a successful Fit the coefficients and forecast state are available via the accessors, and Forecast / ForecastInterval may be called.

Fit returns an error if series is too short for the requested orders, contains a NaN or ±Inf, or the ARMA estimation fails (e.g. a non-stationary/non-invertible fit without WithRootRepair). The search-only options (WithCriterion, WithStepwise, WithParallel, WithContext) are AutoOptions and cannot be passed to Fit — that is a compile-time error.

func (*ARIMA) Forecast

func (m *ARIMA) Forecast(h int, opts ...ForecastOption) ([]float64, error)

Forecast returns the h-step point forecast on the original scale. If the model was fit with exogenous regressors (WithExog), the matching future regressors must be supplied via WithFutureExog (and must not be supplied otherwise); the regression mean of those regressors is then added to the forecast.

func (*ARIMA) ForecastInterval

func (m *ARIMA) ForecastInterval(h int, level float64, opts ...ForecastOption) (*Forecast, error)

ForecastInterval returns the h-step point forecast together with a two-sided prediction interval at the given confidence level (e.g. 0.95). The forecast standard errors come from the model's MA(∞) representation: Var(k steps) = σ²·Σ_{j<k} ψ_j², with the differencing operators folded into the AR side so the variances are on the original (integrated) scale.

If the model was fit with exogenous regressors (WithExog), the matching future regressors must be supplied via WithFutureExog (and must not be supplied otherwise); their regression mean shifts Point/Lower/Upper. β estimation uncertainty is excluded from the band, matching statsmodels' default conf_int.

func (*ARIMA) LastE

func (m *ARIMA) LastE() []float64

LastE returns a copy of the last q residuals.

func (*ARIMA) LastOrig

func (m *ARIMA) LastOrig() float64

LastOrig returns the last original value (for undifferencing).

func (*ARIMA) LastY

func (m *ARIMA) LastY() []float64

LastY returns a copy of the last p differenced observations.

func (*ARIMA) Order

func (m *ARIMA) Order() Order

Order returns the non-seasonal ARIMA orders (p, d, q).

func (*ARIMA) Phi

func (m *ARIMA) Phi() []float64

Phi returns a copy of the regular AR coefficients (the φ factor, length p).

func (*ARIMA) SeasonalOrder

func (m *ARIMA) SeasonalOrder() SeasonalOrder

SeasonalOrder returns the seasonal orders (P, D, Q) and period m.

func (*ARIMA) SeasonalPhi

func (m *ARIMA) SeasonalPhi() []float64

SeasonalPhi returns a copy of the seasonal AR coefficients (the Φₛ factor, length P).

func (*ARIMA) SeasonalTheta

func (m *ARIMA) SeasonalTheta() []float64

SeasonalTheta returns a copy of the seasonal MA coefficients (the Θₛ factor, length Q).

func (*ARIMA) Sigma2

func (m *ARIMA) Sigma2() float64

Sigma2 returns the variance of the residuals. This is not used in forecasting but can be useful for diagnostics.

func (*ARIMA) StdErrors

func (m *ARIMA) StdErrors() ([]float64, error)

StdErrors returns the standard errors of the fitted coefficients (β, φ, Φₛ, θ, Θₛ) in canonical order. It requires an MLE fit (WithMethod(MLE)) and returns an error otherwise, or if the information matrix was singular. An entry is NaN when its estimated variance is non-positive (a weakly identified coefficient).

func (*ARIMA) Summary

func (m *ARIMA) Summary() (*Summary, error)

Summary returns the parameter-inference summary for an MLE-fit model (coefficient estimates, standard errors, z-statistics, p-values, and confidence intervals, plus model-level fit statistics). It returns an error if the model was not fit with WithMethod(MLE).

func (*ARIMA) Theta

func (m *ARIMA) Theta() []float64

Theta returns a copy of the regular MA coefficients (the θ factor, length q).

type AutoOption

type AutoOption interface {
	// contains filtered or unexported methods
}

AutoOption configures an AutoARIMA/AutoSARIMA order search. It is the superset of FitOption: every FitOption is an AutoOption (threaded through to the candidate and final fits), plus the search-only options WithCriterion, WithStepwise, WithParallel, and WithContext — which apply only to the search and, by not satisfying FitOption, cannot be passed to a plain Fit.

func WithContext

func WithContext(ctx context.Context) AutoOption

WithContext supplies a context whose cancellation aborts an AutoARIMA/AutoSARIMA order search; the call then returns an error wrapping the context cause. This is a search-only option: it returns an AutoOption, so it cannot be passed to a plain Fit. Cancellation is observed between candidate fits (a single in-flight fit is not interrupted). A nil context is treated as context.Background().

func WithCriterion

func WithCriterion(c Criterion) AutoOption

WithCriterion selects the information criterion AutoARIMA minimizes during order selection (AIC, BIC, or AICc). The default is AIC. This is a search-only option: it returns an AutoOption, so it cannot be passed to a plain Fit.

func WithParallel

func WithParallel() AutoOption

WithParallel makes AutoARIMA fit candidate orders concurrently, across up to GOMAXPROCS goroutines. Selection is deterministic and identical to the serial search (results are reduced in a fixed order), so this only changes speed. This is a search-only option: it returns an AutoOption, so it cannot be passed to a plain Fit.

func WithStepwise

func WithStepwise() AutoOption

WithStepwise makes AutoARIMA select p and q with a Hyndman-Khandakar stepwise neighbor search instead of the exhaustive grid. It usually fits far fewer candidates at the cost of being a heuristic (it can miss the grid's global optimum). This is a search-only option: it returns an AutoOption, so it cannot be passed to a plain Fit.

type Bounds

type Bounds struct {
	MaxP int
	MaxD int
	MaxQ int
}

Bounds are the non-seasonal search bounds for AutoARIMA/AutoSARIMA: the maximum AR order (MaxP), differencing order (MaxD), and MA order (MaxQ) the search considers. Each is an inclusive upper bound on the range searched from 0.

type Criterion

type Criterion int

Criterion selects the information criterion AutoARIMA minimizes during order selection. The zero value is AIC, so the default selection is unchanged.

const (
	// AIC is the Akaike Information Criterion: n·ln(σ²) + 2k.
	AIC Criterion = iota
	// BIC is the Bayesian (Schwarz) Information Criterion: n·ln(σ²) + k·ln(n).
	// It penalizes extra parameters more heavily than AIC for n > e² ≈ 7.4.
	BIC
	// AICc is the AIC with a small-sample correction:
	// AIC + 2k(k+1)/(n−k−1). It is +Inf when n−k−1 ≤ 0.
	AICc
)

type FitOption

type FitOption interface {
	AutoOption
	// contains filtered or unexported methods
}

FitOption configures optional Fit behavior; every FitOption is also an AutoOption, since the auto searches fit too. The zero set of options keeps the default Hannan-Rissanen estimator. Fit-relevant options are WithMethod, WithExog, and WithRootRepair.

func WithExog

func WithExog(X [][]float64) FitOption

WithExog supplies an n×k matrix of exogenous regressors X (n = len(series)), fitting regression with ARIMA errors: y_t = X_t·β + η_t, where η follows the ARIMA model. The estimated β is available via Beta(); forecasts must pass the matching future regressors via WithFutureExog to Forecast / ForecastInterval.

func WithMethod

func WithMethod(m Method) FitOption

WithMethod selects the estimator (HannanRissanen, CSS, or MLE). The default, used when WithMethod is not supplied, is HannanRissanen.

func WithRootRepair

func WithRootRepair() FitOption

WithRootRepair makes Fit project an unstable Hannan-Rissanen estimate back into the stationary/invertible region — reflecting any AR/MA root on or inside the unit circle to its reciprocal (see roots.go) — instead of returning an error. It is off by default. It composes with WithMethod(CSS)/WithMethod(MLE) (repair yields a valid seed that the optimizer then refines) and threads through AutoARIMA/AutoSARIMA, where it makes otherwise-rejected orders eligible.

type Forecast

type Forecast struct {
	Point  []float64 // point forecast
	Lower  []float64 // Point − z·StdErr
	Upper  []float64 // Point + z·StdErr
	StdErr []float64 // forecast standard error, sqrt(forecast-error variance)
}

Forecast bundles an h-step point forecast with its prediction interval. Every slice has length h; Point is identical to what Forecast(h) returns.

type ForecastOption

type ForecastOption interface {
	// contains filtered or unexported methods
}

ForecastOption configures Forecast/ForecastInterval. The only option is WithFutureExog, required exactly when the model was fit with WithExog.

func WithFutureExog

func WithFutureExog(X [][]float64) ForecastOption

WithFutureExog supplies the future regressor rows for forecasting a model fit with WithExog. futureX must be exactly h×k (k = number of regressors at fit time); Forecast/ForecastInterval add the regression mean futureX·β. It is required exactly when the model was fit with exogenous regressors.

type Method

type Method int

Method selects the estimator Fit uses. The default (HannanRissanen) is a linear-algebra seed with no optimizer; CSS and MLE refine that seed and are never worse than it (a refined estimate is kept only if it is stationary, invertible, and strictly improves the objective, otherwise the seed is used).

const (
	// HannanRissanen is the default: a two-stage linear-algebra estimate with no
	// iterative optimizer (see estimate.go).
	HannanRissanen Method = iota
	// CSS refines the Hannan-Rissanen seed by minimizing the conditional sum of
	// squares (see refine.go).
	CSS
	// MLE refines the Hannan-Rissanen seed by exact Gaussian maximum likelihood
	// via the Kalman filter (see mle.go and statespace.go). It matches the
	// exact-likelihood fit of modern statsmodels (method="statespace").
	MLE
)

type Order

type Order struct {
	P int // AR order p
	D int // differencing order d
	Q int // MA order q
}

Order holds the non-seasonal ARIMA orders (p, d, q): the AR order, the differencing order, and the MA order. The fields carry the conventional lowercase ARIMA letters p/d/q (capitalized because Go exports capitalized fields); the seasonal counterparts live in SeasonalOrder.

type ParamStat

type ParamStat struct {
	Name    string
	Coef    float64
	StdErr  float64
	ZScore  float64 // Coef / StdErr
	PValue  float64 // two-sided, standard normal
	CILower float64 // 95% by default
	CIUpper float64
}

ParamStat is one row of a Summary: a coefficient with its inference stats.

type SeasonalBounds

type SeasonalBounds struct {
	MaxP   int
	MaxQ   int
	Period int
}

SeasonalBounds are the seasonal search bounds for AutoSARIMA: the maximum seasonal AR order (MaxP) and seasonal MA order (MaxQ), plus the fixed seasonal Period (m >= 2). There is no seasonal MaxD — the seasonal differencing order D is auto-selected as 0 or 1 by the seasonal-strength test.

type SeasonalOrder

type SeasonalOrder struct {
	P      int // seasonal AR order
	D      int // seasonal differencing order
	Q      int // seasonal MA order
	Period int // seasonal period m
}

SeasonalOrder holds the multiplicative seasonal orders (P, D, Q) and the seasonal period m. Period must be >= 2 whenever any of P, D, or Q is positive.

type Summary

type Summary struct {
	Params []ParamStat // one row per coefficient, then a final sigma2 row
	NObs   int
	LogLik float64
	AIC    float64
	BIC    float64
	Sigma2 float64
}

Summary bundles a fitted (MLE) model's parameter statistics and fit metrics.

func (*Summary) String

func (s *Summary) String() string

String renders the Summary as a fixed-width table (statsmodels-like).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL