timeseries

package
v0.8.0 Latest Latest
Warning

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

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

Documentation

Overview

Package timeseries is a self-contained, dependency-free time-series analysis toolkit written entirely with the Go standard library (only math, math/cmplx, sort and errors). It operates on plain []float64 sample vectors and does not import the parent algebra module.

The package covers the classical time-series workflow end to end.

Descriptive statistics and transforms

Summaries such as Mean, Variance, StdDev, Median, Quantile, Skewness and Kurtosis, together with reshaping and preprocessing operations: Diff, DiffOrder, SeasonalDiff and their inverses Integrate and SeasonalIntegrate, CumSum, Lag/Lead/Shift, Demean, Standardize, MinMaxNormalize, BoxCox, SimpleReturns, LogReturns, FractionalDifference and least-squares Detrend via FitLinearTrend.

Correlation structure

AutoCovariance, AutoCorrelation (ACF) and PartialAutoCorrelation (PACF via the Durbin–Levinson recursion), cross-correlation (CrossCorrelation), and diagnostic statistics LjungBox, BoxPierce and DurbinWatson.

Smoothing and moving averages

Simple, centered, weighted, triangular and exponential moving averages (MovingAverage, WeightedMovingAverage, ExponentialMovingAverage, DoubleExponentialMovingAverage, TripleExponentialMovingAverage), a family of rolling and expanding window statistics, exponential smoothing (SimpleExponentialSmoothing), Holt's linear-trend method (HoltLinear) and Holt–Winters seasonal smoothing (HoltWinters).

Parametric models

Autoregressive fitting by Yule–Walker (YuleWalker), ordinary least squares (ARFitLeastSquares) and Burg's method (BurgAR); moving-average estimation via the innovations algorithm (MAFit); ARMA fitting with the Hannan–Rissanen procedure (ARMAFit); and ARIMA fitting (ARIMAFit) with automatic differencing and integration. Each model provides forecasting and residual methods, and ARMAToMA/ARMAToAR convert between representations.

Spectral analysis and decomposition

The discrete Fourier transform (DFT), the raw Periodogram, AR spectral density (ARSpectralDensity), SpectralEntropy and dominant-cycle helpers; classical additive and multiplicative seasonal decomposition (SeasonalDecompose) with SeasonallyAdjust and SeasonalIndices.

Stationarity and embedding

Augmented Dickey–Fuller (ADFTest) and KPSS (KPSSTest) helpers, VarianceRatio, number-of-differences estimation (NumberOfDifferences), delay-coordinate embedding (Embed), and matrix builders LagMatrix, HankelMatrix and ToeplitzMatrix. Forecast-accuracy metrics such as RootMeanSquaredError, MeanAbsolutePercentageError, MeanAbsoluteScaledError, RSquared and TheilU round out the package.

Scalar functions return NaN on empty or otherwise undefined input rather than panicking, so callers can test with math.IsNaN. Model-fitting constructors return an error for invalid arguments.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ACFConfidenceBound

func ACFConfidenceBound(n int) float64

ACFConfidenceBound returns the approximate two-sided 95% confidence bound 1.96/√n for the autocorrelations of white noise of length n.

func ADFCriticalValue

func ADFCriticalValue(level float64, trend string) float64

ADFCriticalValue returns an approximate MacKinnon asymptotic critical value for the ADF t-statistic at the given significance level (0.01, 0.05 or 0.10) for the constant-only ("c") or constant-and-trend ("ct") specification. Values come from MacKinnon's response-surface constants (the asymptotic term).

func ARMAToAR

func ARMAToAR(phi, theta []float64, n int) []float64

ARMAToAR returns the first n coefficients π_1,…,π_n of the AR(∞) representation Σ π_j x_{t−j} = e_t implied by the AR coefficients phi and MA coefficients theta (out[j−1] = π_j).

func ARMAToMA

func ARMAToMA(phi, theta []float64, n int) []float64

ARMAToMA returns the first n coefficients ψ_1,…,ψ_n of the MA(∞) representation x_t = Σ ψ_j e_{t−j} implied by the AR coefficients phi and MA coefficients theta (ψ_0 = 1 is omitted; out[j−1] = ψ_j).

func ARSpectralDensity

func ARSpectralDensity(m *ARModel, nf int) (freqs, density []float64)

ARSpectralDensity evaluates the AR power spectral density implied by the model at nf equally spaced frequencies in [0, 0.5]. The density at frequency f is Sigma2 / |1 − Σ Phi_k·e^{−2πi k f}|². It returns the frequencies and the spectral density values.

func Argmax

func Argmax(x []float64) int

Argmax returns the index of the largest value, or -1 if the series is empty. The first index is returned on ties.

func Argmin

func Argmin(x []float64) int

Argmin returns the index of the smallest value, or -1 if the series is empty. The first index is returned on ties.

func AutoCorrelation

func AutoCorrelation(x []float64, maxlag int) []float64

AutoCorrelation returns the sample autocorrelation function (ACF) for lags 0,1,…,maxlag. Element 0 is always 1 (unless the series has zero variance, in which case NaN values are returned).

Example
x := []float64{1, 2, 3, 4, 5}
acf := AutoCorrelation(x, 2)
fmt.Printf("%.1f %.1f %.1f\n", acf[0], acf[1], acf[2])
Output:
1.0 0.4 -0.1

func AutoCorrelationAt

func AutoCorrelationAt(x []float64, k int) float64

AutoCorrelationAt returns the sample autocorrelation at lag k, i.e. AutoCovarianceAt(x,k) divided by the lag-0 autocovariance.

func AutoCovariance

func AutoCovariance(x []float64, maxlag int) []float64

AutoCovariance returns the biased sample autocovariances of the series for lags 0,1,…,maxlag. Element 0 is the population variance.

func AutoCovarianceAt

func AutoCovarianceAt(x []float64, k int) float64

AutoCovarianceAt returns the biased sample autocovariance of the series at lag k: (1/n)·Σ (x_t − x̄)(x_{t+k} − x̄). It returns NaN if k is negative or ≥ len(x).

func AutocorrelationMatrix

func AutocorrelationMatrix(x []float64, p int) [][]float64

AutocorrelationMatrix returns the p×p symmetric Toeplitz autocorrelation matrix of the series, with element (i,j) equal to the sample autocorrelation at lag |i−j|. It is the coefficient matrix of the Yule–Walker equations.

func BoxCox

func BoxCox(x []float64, lambda float64) []float64

BoxCox applies the Box–Cox power transform with parameter lambda. For lambda = 0 it returns the natural log; otherwise (x^lambda − 1)/lambda. Non-positive inputs map to NaN.

func BoxPierce

func BoxPierce(x []float64, h int) float64

BoxPierce returns the Box–Pierce Q statistic for the first h autocorrelation lags, the simpler large-sample precursor to LjungBox.

func BrownDoubleExponential

func BrownDoubleExponential(x []float64, alpha float64, h int) []float64

BrownDoubleExponential returns Brown's single-parameter double exponential smoothing (linear-trend) forecast for the series. It computes the singly and doubly smoothed statistics with parameter alpha, forms the level and trend at the final point, and returns the h-step-ahead forecasts. It returns nil for an out-of-range alpha or empty x.

func Clip

func Clip(x []float64, lo, hi float64) []float64

Clip constrains every observation to the closed interval [lo,hi].

func CoefficientOfVariation

func CoefficientOfVariation(x []float64) float64

CoefficientOfVariation returns the ratio of the sample standard deviation to the mean, a scale-free measure of dispersion.

func CrossCorrelation

func CrossCorrelation(x, y []float64, maxlag int) []float64

CrossCorrelation returns the cross-correlation function of x and y for lags −maxlag,…,0,…,maxlag as a slice of length 2·maxlag+1, indexed so that out[maxlag+k] is the correlation at lag k.

func CrossCorrelationAt

func CrossCorrelationAt(x, y []float64, k int) float64

CrossCorrelationAt returns the sample cross-correlation between x and y at lag k, normalized by the product of the two series' standard deviations.

func CrossCovarianceAt

func CrossCovarianceAt(x, y []float64, k int) float64

CrossCovarianceAt returns the sample cross-covariance between x and y at lag k: (1/n)·Σ (x_t − x̄)(y_{t+k} − ȳ) for k ≥ 0, and the symmetric definition for k < 0. The two series must have equal length; otherwise NaN is returned.

func CumProd

func CumProd(x []float64) []float64

CumProd returns the cumulative product of the series.

func CumSum

func CumSum(x []float64) []float64

CumSum returns the cumulative sum of the series: out[i] = x[0]+…+x[i].

func CumulativeMovingAverage

func CumulativeMovingAverage(x []float64) []float64

CumulativeMovingAverage returns the running (expanding-window) mean of the series: out[i] is the mean of x[0..i].

func CumulativePeriodogram

func CumulativePeriodogram(x []float64) []float64

CumulativePeriodogram returns the normalized cumulative periodogram of the series over the non-zero Fourier frequencies, a monotone sequence rising from near 0 to 1 used to inspect departures from white noise.

func DFT

func DFT(x []float64) []complex128

DFT returns the discrete Fourier transform of the real series x, a complex spectrum of the same length computed by direct summation: X_k = Σ_t x_t·exp(−2πi·k·t/n).

func Demean

func Demean(x []float64) []float64

Demean returns the series with its mean subtracted from every observation.

func Detrend

func Detrend(x []float64) []float64

Detrend removes a least-squares linear trend from the series, returning the residuals x[i] − (a + b·i).

func Diff

func Diff(x []float64) []float64

Diff returns the first difference of the series: out[i] = x[i+1] − x[i]. The result has length len(x)−1 (empty for a series shorter than two).

func DiffOrder

func DiffOrder(x []float64, d int) []float64

DiffOrder applies the first difference d times. Differencing d times shortens the series by d. A d of zero returns a copy of x.

func DominantFrequency

func DominantFrequency(x []float64) float64

DominantFrequency returns the non-zero Fourier frequency with the largest periodogram power, i.e. the strongest cyclical component of the series. It returns NaN if the series is too short.

func DominantPeriod

func DominantPeriod(x []float64) float64

DominantPeriod returns the reciprocal of DominantFrequency, i.e. the length (in samples) of the strongest cycle in the series. It returns NaN if no non-zero frequency dominates.

func DoubleExponentialMovingAverage

func DoubleExponentialMovingAverage(x []float64, alpha float64) []float64

DoubleExponentialMovingAverage returns the DEMA indicator, 2·EMA(x) − EMA(EMA(x)), which reduces the lag of a plain EMA. It returns nil for an out-of-range alpha.

func DurbinWatson

func DurbinWatson(e []float64) float64

DurbinWatson returns the Durbin–Watson statistic of a residual series, Σ(e_t − e_{t−1})² / Σe_t², which detects lag-1 autocorrelation. Values near 2 indicate no autocorrelation.

func Embed

func Embed(x []float64, m, tau int) [][]float64

Embed constructs a time-delay (Takens) embedding of the series with embedding dimension m and delay tau. Row i is [x[i], x[i+tau], …, x[i+(m−1)tau]]; the matrix has len(x)−(m−1)·tau rows and m columns. It returns nil if the arguments are invalid or the series is too short.

func Energy

func Energy(x []float64) float64

Energy returns the sum of squared observations of the series.

func EstimateSeasonalPeriod

func EstimateSeasonalPeriod(x []float64, maxLag int) int

EstimateSeasonalPeriod returns the lag (≥ 2) of the largest peak in the autocorrelation function up to maxLag, a data-driven estimate of the dominant seasonal period. It returns 0 if no interior peak is found.

func ExpTransform

func ExpTransform(x []float64) []float64

ExpTransform returns the exponential of each observation (the inverse of LogTransform).

func ExpandingMax

func ExpandingMax(x []float64) []float64

ExpandingMax returns the running maximum: out[i] = max(x[0..i]).

func ExpandingMean

func ExpandingMean(x []float64) []float64

ExpandingMean returns the expanding-window mean, identical to CumulativeMovingAverage.

func ExpandingMin

func ExpandingMin(x []float64) []float64

ExpandingMin returns the running minimum: out[i] = min(x[0..i]).

func ExpandingSum

func ExpandingSum(x []float64) []float64

ExpandingSum returns the expanding-window sum, identical to CumSum.

func ExponentialMovingAverage

func ExponentialMovingAverage(x []float64, alpha float64) []float64

ExponentialMovingAverage returns the exponentially weighted moving average with smoothing factor alpha in (0,1]: out[0] = x[0] and out[i] = alpha·x[i] + (1−alpha)·out[i−1]. It returns nil for an out-of-range alpha.

func ExponentialMovingAverageSpan

func ExponentialMovingAverageSpan(x []float64, span int) []float64

ExponentialMovingAverageSpan returns the exponential moving average using the span convention alpha = 2/(span+1), common in technical analysis. It returns nil if span < 1.

func First

func First(x []float64) float64

First returns the first observation of the series, or NaN if empty.

func FlattenMatrix

func FlattenMatrix(m [][]float64) []float64

FlattenMatrix returns a row-major flattening of a matrix into a single slice, a convenience for feeding embedded matrices to routines that expect flat data.

func FourierFrequencies

func FourierFrequencies(n int, d float64) []float64

FourierFrequencies returns the n Fourier frequencies (in cycles per sample unit) associated with a length-n DFT: k/(n·d) for k = 0,…,n−1, where d is the sample spacing.

func FracDiffWeights

func FracDiffWeights(d float64, n int) []float64

FracDiffWeights returns the first n binomial weights of the fractional differencing operator (1−B)^d. weight[0] is 1 and weight[k] = −weight[k−1]·(d−k+1)/k.

func FractionalDifference

func FractionalDifference(x []float64, d float64) []float64

FractionalDifference applies the fractional differencing operator (1−B)^d to the series using an expanding window of binomial weights. The result has the same length as x; early observations use only the available past. For integer d this reproduces ordinary differencing (padded at the front).

func HankelMatrix

func HankelMatrix(x []float64, rows int) [][]float64

HankelMatrix builds the Hankel matrix of the series with the given number of rows: element (i,j) is x[i+j]. The matrix has len(x)−rows+1 columns. It returns nil if rows < 1 or rows > len(x).

func InnovationsAlgorithm

func InnovationsAlgorithm(gamma []float64, maxlag int) ([][]float64, []float64)

InnovationsAlgorithm runs the innovations algorithm on the autocovariance sequence gamma (length ≥ maxlag+1) and returns the innovation coefficients theta as a lower-triangular matrix (theta[n][j] for 1 ≤ j ≤ n) together with the one-step prediction error variances v[0..maxlag]. These coefficients are the basis of the moving-average innovations estimator.

func Integrate

func Integrate(d []float64, x0 float64) []float64

Integrate is the inverse of Diff: given the first-difference series d and an initial value x0, it reconstructs the original series by cumulative summation. The result has length len(d)+1.

func InverseBoxCox

func InverseBoxCox(y []float64, lambda float64) []float64

InverseBoxCox inverts the Box–Cox transform with parameter lambda.

func InverseDFT

func InverseDFT(X []complex128) []complex128

InverseDFT returns the inverse discrete Fourier transform of the complex spectrum X, a complex series of the same length. For a spectrum produced by DFT the imaginary parts are numerically negligible.

func IsStationaryADF

func IsStationaryADF(x []float64, lags int, level float64) bool

IsStationaryADF reports whether the augmented Dickey–Fuller test rejects the unit-root null at the given significance level (typically 0.05), i.e. whether the series appears stationary. It uses no deterministic trend.

func Kurtosis

func Kurtosis(x []float64) float64

Kurtosis returns the excess kurtosis (fourth standardized moment minus 3) of the series. It returns NaN if the series has fewer than two observations or zero variance.

func Lag

func Lag(x []float64, k int) []float64

Lag shifts the series forward by k steps, padding the first k positions with NaN. The result has the same length as x. A negative k delegates to Lead.

func LagMatrix

func LagMatrix(x []float64, p int) ([][]float64, []float64)

LagMatrix builds a design matrix of lagged values for autoregressive modeling. Row i (for i from 0) contains [x[t−1], x[t−2], …, x[t−p]] where t = p+i, so the matrix has len(x)−p rows and p columns. The aligned targets x[t] are returned as the second result. It returns nil, nil if p < 1 or p ≥ len(x).

func Last

func Last(x []float64) float64

Last returns the final observation of the series, or NaN if empty.

func Lead

func Lead(x []float64, k int) []float64

Lead shifts the series backward by k steps, padding the last k positions with NaN. The result has the same length as x. A negative k delegates to Lag.

func LevinsonDurbin

func LevinsonDurbin(gamma []float64, p int) ([]float64, float64)

LevinsonDurbin solves the Yule–Walker equations for an AR(p) model from the autocovariance sequence gamma (which must have length at least p+1). It returns the p AR coefficients and the innovation variance.

func LjungBox

func LjungBox(x []float64, h int) float64

LjungBox returns the Ljung–Box Q statistic for the first h autocorrelation lags, a test for overall autocorrelation. Under the null of no autocorrelation Q is approximately chi-squared with h degrees of freedom.

func LogReturns

func LogReturns(x []float64) []float64

LogReturns returns the log returns of the series: out[i] = ln(x[i+1]/x[i]). The result has length len(x)−1.

func LogTransform

func LogTransform(x []float64) []float64

LogTransform returns the natural logarithm of each observation. Non-positive inputs map to NaN.

func Max

func Max(x []float64) float64

Max returns the largest value in the series, or NaN if it is empty.

func Mean

func Mean(x []float64) float64

Mean returns the arithmetic mean of the series, or NaN if it is empty.

func MeanAbsoluteDeviation

func MeanAbsoluteDeviation(x []float64) float64

MeanAbsoluteDeviation returns the mean of the absolute deviations from the series mean.

func MeanAbsoluteError

func MeanAbsoluteError(actual, forecast []float64) float64

MeanAbsoluteError returns the mean of |actual − forecast| over the aligned pairs. It returns NaN if the lengths differ or are zero.

func MeanAbsolutePercentageError

func MeanAbsolutePercentageError(actual, forecast []float64) float64

MeanAbsolutePercentageError returns the mean of |(actual − forecast)/actual| as a fraction (multiply by 100 for a percentage). Pairs with a zero actual value are skipped. It returns NaN if the lengths differ or no valid pair exists.

func MeanAbsoluteScaledError

func MeanAbsoluteScaledError(actual, forecast, train []float64, m int) float64

MeanAbsoluteScaledError returns the MASE of the forecast, the mean absolute error scaled by the mean absolute error of a naive one-step (seasonal-period m) forecast computed on the training series train. A value below 1 means the forecast beats the naive benchmark. It returns NaN on length mismatch or an undefined scale.

func MeanError

func MeanError(actual, forecast []float64) float64

MeanError returns the mean forecast error (bias) actual − forecast over the aligned pairs. It returns NaN if the lengths differ or are zero.

func MeanSquaredError

func MeanSquaredError(actual, forecast []float64) float64

MeanSquaredError returns the mean of (actual − forecast)² over the aligned pairs. It returns NaN if the lengths differ or are zero.

func Median

func Median(x []float64) float64

Median returns the median of the series, or NaN if it is empty. The input is not modified.

func MedianAbsoluteError

func MedianAbsoluteError(actual, forecast []float64) float64

MedianAbsoluteError returns the median of |actual − forecast| over the aligned pairs, a robust accuracy measure.

func MedianFilter

func MedianFilter(x []float64, w int) []float64

MedianFilter returns the centered running median with window length w, truncating the window at the boundaries so the output length equals the input length. It returns nil if w < 1.

func Min

func Min(x []float64) float64

Min returns the smallest value in the series, or NaN if it is empty.

func MinMaxNormalize

func MinMaxNormalize(x []float64) []float64

MinMaxNormalize rescales the series linearly to the unit interval [0,1]. If all values are equal the result is all zeros.

func MovingAverage

func MovingAverage(x []float64, w int) []float64

MovingAverage returns the causal (trailing) simple moving average with window length w: out[i] is the mean of the up-to-w most recent samples ending at i. At the start, where fewer than w samples exist, the average uses the samples seen so far. The result has the same length as x. It returns nil if w < 1.

func MovingAverageCentered

func MovingAverageCentered(x []float64, w int) []float64

MovingAverageCentered returns the centered simple moving average with window length w, truncating the window at the boundaries so the output length equals the input length. For even w the window is biased one sample toward the past. It returns nil if w < 1.

func MovingAverageValid

func MovingAverageValid(x []float64, w int) []float64

MovingAverageValid returns the centered simple moving average over full windows only, so the result has length len(x)−w+1. It returns nil if w < 1 or w > len(x).

func NumberOfDifferences

func NumberOfDifferences(x []float64, lags, maxD int, level float64) int

NumberOfDifferences estimates the order of differencing needed to make the series stationary by repeatedly applying the ADF test (constant, given lags) and differencing until stationarity is achieved or maxD is reached.

func PartialAutoCorrelation

func PartialAutoCorrelation(x []float64, maxlag int) []float64

PartialAutoCorrelation returns the sample partial autocorrelation function (PACF) for lags 0,1,…,maxlag computed with the Durbin–Levinson recursion. Element 0 is 1 by convention and element k is the last coefficient of the fitted AR(k) model.

func Percentile

func Percentile(x []float64, p float64) float64

Percentile returns the p-th percentile (0 ≤ p ≤ 100) of the series.

func Periodogram

func Periodogram(x []float64) (freqs, power []float64)

Periodogram returns the one-sided raw periodogram of the series, an estimate of the power at each Fourier frequency. The returned slices freqs and power have length ⌊n/2⌋+1; power[j] = |Σ x_t·e^{−2πi j t/n}|² / n. The mean is removed before the transform.

func PopStdDev

func PopStdDev(x []float64) float64

PopStdDev returns the population standard deviation (square root of PopVariance).

func PopVariance

func PopVariance(x []float64) float64

PopVariance returns the population (divide-by-n) variance of the series. It returns NaN for an empty series.

func Quantile

func Quantile(x []float64, q float64) float64

Quantile returns the q-quantile (0 ≤ q ≤ 1) of the series using linear interpolation between order statistics. It returns NaN for an empty series or an out-of-range q. The input is not modified.

func RSquared

func RSquared(actual, forecast []float64) float64

RSquared returns the coefficient of determination R² = 1 − SS_res/SS_tot of the forecast relative to the mean of the actual series. It returns NaN on length mismatch or when the actual series has zero variance.

func Range

func Range(x []float64) float64

Range returns the difference between the maximum and minimum values.

func ReflectionCoefficients

func ReflectionCoefficients(x []float64, p int) []float64

ReflectionCoefficients returns the partial autocorrelation (reflection / PARCOR) coefficients k_1,…,k_p produced by the Levinson–Durbin recursion on the series, one per order from 1 to p.

func Rescale

func Rescale(x []float64, a, b float64) []float64

Rescale linearly maps the series to the interval [a,b].

func Reverse

func Reverse(x []float64) []float64

Reverse returns a new series with the observations in reverse order.

func RollingMax

func RollingMax(x []float64, w int) []float64

RollingMax returns the trailing rolling maximum over full windows of length w. It returns nil if w < 1 or w > len(x).

func RollingMean

func RollingMean(x []float64, w int) []float64

RollingMean returns the trailing rolling mean over full windows of length w, producing len(x)−w+1 values. It returns nil if w < 1 or w > len(x).

func RollingMedian

func RollingMedian(x []float64, w int) []float64

RollingMedian returns the trailing rolling median over full windows of length w. It returns nil if w < 1 or w > len(x).

func RollingMin

func RollingMin(x []float64, w int) []float64

RollingMin returns the trailing rolling minimum over full windows of length w. It returns nil if w < 1 or w > len(x).

func RollingStdDev

func RollingStdDev(x []float64, w int) []float64

RollingStdDev returns the trailing rolling sample standard deviation over full windows of length w. It returns nil if w < 2 or w > len(x).

func RollingSum

func RollingSum(x []float64, w int) []float64

RollingSum returns the trailing rolling sum over full windows of length w. It returns nil if w < 1 or w > len(x).

func RollingVariance

func RollingVariance(x []float64, w int) []float64

RollingVariance returns the trailing rolling sample variance over full windows of length w. It returns nil if w < 2 or w > len(x).

func RootMeanSquare

func RootMeanSquare(x []float64) float64

RootMeanSquare returns sqrt(mean(x²)), the quadratic mean of the series.

func RootMeanSquaredError

func RootMeanSquaredError(actual, forecast []float64) float64

RootMeanSquaredError returns the square root of MeanSquaredError.

func SESForecast

func SESForecast(x []float64, alpha float64, h int) []float64

SESForecast returns the h-step-ahead forecast of a simple exponential smoothing model fitted to x with parameter alpha. Because the model has no trend, every forecast equals the final smoothed level, so the returned slice of length h is constant. It returns nil for an out-of-range alpha or empty x.

func SeasonalDiff

func SeasonalDiff(x []float64, s int) []float64

SeasonalDiff returns the seasonal difference at lag s: out[i] = x[i+s] − x[i]. The result has length len(x)−s. It returns an empty slice if s < 1 or s ≥ len(x).

func SeasonalIndices

func SeasonalIndices(x []float64, period int, mult bool) []float64

SeasonalIndices returns the per-phase seasonal factors of the series for the given period (length period): additive deviations that sum to zero when mult is false, or multiplicative factors that average to one when mult is true. It returns nil for an invalid period or too-short series.

func SeasonalIntegrate

func SeasonalIntegrate(d []float64, seed []float64, s int) []float64

SeasonalIntegrate is the inverse of SeasonalDiff at lag s: given the seasonal-difference series d and the s initial values seed (the first season of the original series), it reconstructs the original series of length len(d)+s. It returns nil if len(seed) != s.

func SeasonallyAdjust

func SeasonallyAdjust(x []float64, period int, mult bool) []float64

SeasonallyAdjust removes the estimated seasonal component from the series, returning the seasonally adjusted series (trend plus residual for the additive model, or the series divided by the seasonal factors for the multiplicative model). It returns nil for an invalid period or too-short series.

func Shift

func Shift(x []float64, k int, fill float64) []float64

Shift shifts the series forward by k steps, filling vacated positions with fill. A negative k shifts backward. The result has the same length as x.

func SimpleExponentialSmoothing

func SimpleExponentialSmoothing(x []float64, alpha float64) []float64

SimpleExponentialSmoothing returns the simple exponentially smoothed series with smoothing parameter alpha in (0,1): s[0] = x[0] and s[t] = alpha·x[t] + (1−alpha)·s[t−1]. It returns nil for an out-of-range alpha. This is identical to ExponentialMovingAverage.

func SimpleReturns

func SimpleReturns(x []float64) []float64

SimpleReturns returns the simple (arithmetic) returns of the series: out[i] = x[i+1]/x[i] − 1. The result has length len(x)−1.

func Skewness

func Skewness(x []float64) float64

Skewness returns the sample skewness (third standardized moment) using the population standard deviation in the denominator. It returns NaN if the series has fewer than two observations or zero variance.

func SlidingWindows

func SlidingWindows(x []float64, w, step int) [][]float64

SlidingWindows returns the list of consecutive full windows of length w over the series, each stepped by step positions. Each window is a fresh copy. It returns nil if w < 1, step < 1 or w > len(x).

func SpectralEntropy

func SpectralEntropy(x []float64) float64

SpectralEntropy returns the normalized spectral (Shannon) entropy of the series computed from its periodogram, a value in [0,1] that is near 1 for white noise and near 0 for a pure sinusoid. It returns NaN if the series is too short.

func SqrtTransform

func SqrtTransform(x []float64) []float64

SqrtTransform returns the square root of each observation. Negative inputs map to NaN.

func Standardize

func Standardize(x []float64) []float64

Standardize returns the z-scored series (x − mean)/stddev using the sample standard deviation. If the standard deviation is zero the result is all zeros.

func StdDev

func StdDev(x []float64) float64

StdDev returns the sample standard deviation (square root of Variance).

func Sum

func Sum(x []float64) float64

Sum returns the sum of all observations in the series.

func SymmetricMAPE

func SymmetricMAPE(actual, forecast []float64) float64

SymmetricMAPE returns the symmetric mean absolute percentage error, the mean of |actual − forecast| / ((|actual| + |forecast|)/2) as a fraction. Pairs where both values are zero are skipped.

func TakensThetaAutoMI

func TakensThetaAutoMI(x []float64, maxLag int) int

TakensThetaAutoMI returns the lag at which the sample autocorrelation of the series first drops to or below 1/e, a common heuristic for choosing the delay in a time-delay embedding. It searches lags 1..maxLag and returns 0 if the threshold is never crossed.

func TheilU

func TheilU(actual, forecast []float64) float64

TheilU returns Theil's U2 forecast-accuracy statistic, the ratio of the RMSE of the forecast to the RMSE of a naive no-change forecast. Values below 1 indicate the forecast improves on the naive benchmark. The actual and forecast slices are aligned one-step-ahead predictions; the naive benchmark uses the previous actual value, so both must have length ≥ 2. It returns NaN on invalid input.

func TimeDelayEmbedding

func TimeDelayEmbedding(x []float64, dimension, delay int) [][]float64

TimeDelayEmbedding is an alias for Embed with the conventional argument order (dimension then delay), returning the delay-coordinate matrix.

func ToeplitzMatrix

func ToeplitzMatrix(c []float64) [][]float64

ToeplitzMatrix builds the symmetric Toeplitz matrix whose first row and column are c: element (i,j) is c[|i−j|]. It returns nil for an empty c.

func TrendComponent

func TrendComponent(x []float64, period int) []float64

TrendComponent returns the classical moving-average trend estimate of the series for the given period, with NaN at boundary positions. It returns nil if the period is invalid.

func TrendLine

func TrendLine(x []float64) []float64

TrendLine returns the fitted trend values a + b·i for the series.

func TriangularMovingAverage

func TriangularMovingAverage(x []float64, w int) []float64

TriangularMovingAverage returns a trailing weighted moving average whose weights increase linearly from 1 up to w (giving most weight to the most recent sample), a smooth double-averaging filter. It returns nil if w < 1.

func TripleExponentialMovingAverage

func TripleExponentialMovingAverage(x []float64, alpha float64) []float64

TripleExponentialMovingAverage returns the TEMA indicator, 3·EMA − 3·EMA² + EMA³, which further reduces lag. It returns nil for an out-of-range alpha.

func Variance

func Variance(x []float64) float64

Variance returns the sample (unbiased, divide-by-n−1) variance of the series. It returns NaN if fewer than two observations are present.

func VarianceRatio

func VarianceRatio(x []float64, q int) float64

VarianceRatio returns the Lo–MacKinlay variance ratio of the series at horizon q: the variance of q-period differences divided by q times the variance of one-period differences. A value near 1 is consistent with a random walk; values away from 1 indicate mean reversion (<1) or trending (>1). It returns NaN for q < 2 or a too-short series.

func WeightedMovingAverage

func WeightedMovingAverage(x []float64, weights []float64) []float64

WeightedMovingAverage returns the causal weighted moving average whose window length equals len(weights). out[i] is Σ weights[j]·x[i−len+1+j] divided by the sum of the weights used; at the boundary the trailing weights are applied to the available samples. It returns nil for empty weights.

Types

type ADFResult

type ADFResult struct {
	Statistic float64 // ADF t-statistic on the lagged-level coefficient
	Gamma     float64 // estimated coefficient on y_{t-1}
	Lags      int     // number of augmenting difference lags used
	NObs      int     // number of observations in the regression
	Trend     string  // deterministic terms: "c" (constant) or "ct" (constant+trend)
}

ADFResult holds the outcome of an augmented Dickey–Fuller test.

func ADFTest

func ADFTest(x []float64, lags int, trend bool) (*ADFResult, error)

ADFTest performs the augmented Dickey–Fuller test for a unit root in the series. The regression is Δy_t = α + (β·t if trend) + γ·y_{t−1} + Σ δ_i·Δy_{t−i} + ε_t with the requested number of augmenting lags; the returned statistic is γ̂/se(γ̂). A more negative statistic is stronger evidence against a unit root (against non-stationarity). Set trend true to include a linear time trend. It returns an error if the series is too short.

func DickeyFuller

func DickeyFuller(x []float64) (*ADFResult, error)

DickeyFuller performs the simple (non-augmented) Dickey–Fuller test with a constant, equivalent to ADFTest with zero augmenting lags and no trend.

type ARIMAModel

type ARIMAModel struct {
	P, D, Q int
	ARMA    *ARMAModel
	// contains filtered or unexported fields
}

ARIMAModel is a fitted ARIMA(p,d,q) model: after d-fold differencing the series is modeled as ARMA(p,q). The stored tail retains the last d level values needed to integrate forecasts back to the original scale.

func ARIMAFit

func ARIMAFit(x []float64, p, d, q int) (*ARIMAModel, error)

ARIMAFit fits an ARIMA(p,d,q) model by differencing the series d times and fitting an ARMA(p,q) model to the result. It returns an error for invalid orders or an insufficiently long series.

func (*ARIMAModel) Forecast

func (m *ARIMAModel) Forecast(h int) []float64

Forecast returns the h-step-ahead forecasts of the ARIMA model on the original scale, integrating the differenced ARMA forecasts back up through the d retained anchor values.

type ARMAModel

type ARMAModel struct {
	P      int       // AR order
	Q      int       // MA order
	Phi    []float64 // AR coefficients, length P
	Theta  []float64 // MA coefficients, length Q
	Mean   float64   // series mean μ
	Sigma2 float64   // innovation variance
}

ARMAModel is a fitted autoregressive moving-average model x_t − μ = Σ Phi[i]·(x_{t−i−1} − μ) + e_t + Σ Theta[j]·e_{t−j−1}.

func ARMAFit

func ARMAFit(x []float64, p, q int) (*ARMAModel, error)

ARMAFit fits an ARMA(p,q) model with the two-stage Hannan–Rissanen procedure: a long autoregression estimates the innovations, then x_t is regressed on its own lags and the estimated innovation lags. It returns an error for invalid orders or an insufficiently long series.

func (*ARMAModel) Forecast

func (m *ARMAModel) Forecast(x []float64, h int) []float64

Forecast returns the h-step-ahead forecasts of the ARMA model given the observed history x, feeding forecasts back for the AR part and dropping future (zero-expectation) innovations for the MA part.

func (*ARMAModel) Residuals

func (m *ARMAModel) Residuals(x []float64) []float64

Residuals returns the estimated innovations of the ARMA model reconstructed from the series by inverting the recursion, using zero pre-sample values.

type ARModel

type ARModel struct {
	Order     int       // AR order p
	Phi       []float64 // AR coefficients, length p
	Mean      float64   // series mean μ
	Intercept float64   // constant term c
	Sigma2    float64   // white-noise (innovation) variance
}

ARModel is a fitted autoregressive model of a given order. The mean-adjusted form is x_t − μ = Σ_{i=1}^{p} Phi[i−1]·(x_{t−i} − μ) + e_t, with Intercept = μ·(1 − ΣPhi) so that x_t = Intercept + Σ Phi[i]·x_{t−i} + e_t.

func ARFitLeastSquares

func ARFitLeastSquares(x []float64, p int) (*ARModel, error)

ARFitLeastSquares fits an AR(p) model by ordinary least squares regression of x_t on its p lagged values and an intercept. It returns an error if p < 1 or there are too few usable rows.

func BurgAR

func BurgAR(x []float64, p int) (*ARModel, error)

BurgAR fits an AR(p) model using Burg's method, which minimizes the sum of forward and backward prediction errors and is well conditioned for short series. It returns an error if p < 1 or the series is too short.

func YuleWalker

func YuleWalker(x []float64, p int) (*ARModel, error)

YuleWalker fits an AR(p) model to the series by solving the Yule–Walker equations via the Levinson–Durbin recursion. It returns an error if p < 1 or the series is shorter than p+1.

func (*ARModel) Forecast

func (m *ARModel) Forecast(x []float64, h int) []float64

Forecast returns the h-step-ahead recursive forecasts of the AR model given the observed history x, feeding predicted values back in as needed.

func (*ARModel) Predict

func (m *ARModel) Predict(x []float64) []float64

Predict returns the in-sample one-step-ahead predictions of the AR model for the series x. The first Order elements, which lack sufficient history, are set to NaN.

func (*ARModel) Residuals

func (m *ARModel) Residuals(x []float64) []float64

Residuals returns the in-sample one-step-ahead residuals x_t − x̂_t of the AR model, with NaN for the first Order positions.

type Decomposition

type Decomposition struct {
	Observed       []float64
	Trend          []float64
	Seasonal       []float64
	Residual       []float64
	Period         int
	Multiplicative bool
}

Decomposition holds the additive or multiplicative decomposition of a series into trend, seasonal and residual components, each aligned with the original observations. Positions where the trend is undefined (near the boundaries) hold NaN.

func SeasonalDecompose

func SeasonalDecompose(x []float64, period int, mult bool) *Decomposition

SeasonalDecompose performs a classical seasonal decomposition of the series with the given period. If mult is true a multiplicative model (x = trend·seasonal·residual) is used, otherwise an additive model (x = trend + seasonal + residual). The seasonal component is the average detrended value per phase, normalized to sum to zero (additive) or to average one (multiplicative), and repeated across the series. It returns nil if the period is invalid or the series is shorter than two periods.

type HoltModel

type HoltModel struct {
	Alpha float64   // level smoothing parameter
	Beta  float64   // trend smoothing parameter
	Level []float64 // fitted level component, one per observation
	Trend []float64 // fitted trend component, one per observation
}

HoltModel is a fitted Holt linear-trend (double exponential smoothing) model.

func HoltLinear

func HoltLinear(x []float64, alpha, beta float64) (*HoltModel, error)

HoltLinear fits Holt's linear-trend method to the series with level and trend smoothing parameters alpha and beta, both in (0,1]. The level is initialized to x[0] and the trend to x[1]−x[0]. It returns an error if the parameters are out of range or the series has fewer than two observations.

Example
x := []float64{1, 2, 3, 4}
m, _ := HoltLinear(x, 0.5, 0.5)
fmt.Println(m.Forecast(2))
Output:
[5 6]

func (*HoltModel) Fitted

func (m *HoltModel) Fitted() []float64

Fitted returns the in-sample one-step-ahead forecasts, ŷ_t = level_{t−1} + trend_{t−1} for t ≥ 1, with the first element set to the initial level.

func (*HoltModel) Forecast

func (m *HoltModel) Forecast(h int) []float64

Forecast returns the h-step-ahead forecasts from the fitted model: ŷ_{n+k} = level + k·trend for k = 1,…,h.

func (*HoltModel) SSE

func (m *HoltModel) SSE(x []float64) float64

SSE returns the in-sample sum of squared one-step-ahead forecast errors for the observations x the model was fitted to (indices 1…n−1).

type HoltWintersModel

type HoltWintersModel struct {
	Alpha          float64   // level smoothing parameter
	Beta           float64   // trend smoothing parameter
	Gamma          float64   // seasonal smoothing parameter
	Period         int       // seasonal period m
	Multiplicative bool      // seasonality type
	Level          []float64 // fitted level component
	Trend          []float64 // fitted trend component
	Season         []float64 // fitted seasonal component
}

HoltWintersModel is a fitted Holt–Winters triple exponential smoothing model with additive or multiplicative seasonality of a fixed period.

func HoltWinters

func HoltWinters(x []float64, alpha, beta, gamma float64, period int, mult bool) (*HoltWintersModel, error)

HoltWinters fits the Holt–Winters seasonal method to the series with the given smoothing parameters (all in (0,1]) and seasonal period. If mult is true multiplicative seasonality is used, otherwise additive. The series must contain at least two full seasons. It returns an error on invalid arguments.

func (*HoltWintersModel) Fitted

func (m *HoltWintersModel) Fitted() []float64

Fitted returns the in-sample one-step-ahead forecasts of the Holt–Winters model. The first Period elements (used for initialization) are set to the observed values via the initial seasonal factors.

func (*HoltWintersModel) Forecast

func (m *HoltWintersModel) Forecast(h int) []float64

Forecast returns the h-step-ahead forecasts from the fitted Holt–Winters model, recycling the most recent seasonal factors.

type KPSSResult

type KPSSResult struct {
	Statistic float64 // KPSS LM statistic
	Lags      int     // truncation lag for the long-run variance
	Trend     string  // "c" for level stationarity, "ct" for trend stationarity
}

KPSSResult holds the outcome of a KPSS stationarity test.

func KPSSTest

func KPSSTest(x []float64, lag int, trend bool) (*KPSSResult, error)

KPSSTest performs the Kwiatkowski–Phillips–Schmidt–Shin test whose null hypothesis is that the series is (level- or trend-) stationary. Residuals are taken from a regression on a constant (trend=false) or a constant and linear trend (trend=true); the statistic is Σ S_t² / (n²·σ²_LR) with a Newey–West long-run variance estimate using the given truncation lag. A large statistic is evidence against stationarity. It returns an error if the series is too short.

type LinearFit

type LinearFit struct {
	Intercept float64
	Slope     float64
}

LinearFit holds the coefficients of a straight line y = Intercept + Slope·t.

func FitLinearTrend

func FitLinearTrend(x []float64) LinearFit

FitLinearTrend fits a straight line y = a + b·t to the series against the index t = 0,1,…,n−1 by ordinary least squares and returns the coefficients.

func (LinearFit) At

func (f LinearFit) At(t float64) float64

At evaluates the fitted line at index t.

type MAModel

type MAModel struct {
	Order  int       // MA order q
	Theta  []float64 // MA coefficients, length q
	Mean   float64   // series mean μ
	Sigma2 float64   // innovation variance
}

MAModel is a fitted moving-average model x_t = μ + e_t + Σ Theta[i]·e_{t−i−1}, with innovation variance Sigma2.

func MAFit

func MAFit(x []float64, q int) (*MAModel, error)

MAFit estimates an MA(q) model using the innovations algorithm applied to the sample autocovariances of the series. It returns an error if q < 1 or the series is too short.

func (*MAModel) Forecast

func (m *MAModel) Forecast(x []float64, h int) []float64

Forecast returns the h-step-ahead forecasts of the MA(q) model given the observed history x. Because an MA(q) process is uncorrelated beyond lag q, forecasts revert to the mean after q steps.

func (*MAModel) Residuals

func (m *MAModel) Residuals(x []float64) []float64

Residuals returns the estimated innovations of the MA model reconstructed from the series by inverting the moving-average recursion: e_t = (x_t − μ) − Σ Theta[i]·e_{t−i−1}, with pre-sample innovations taken as zero.

Jump to

Keyboard shortcuts

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