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 ¶
- func ACFConfidenceBound(n int) float64
- func ADFCriticalValue(level float64, trend string) float64
- func ARMAToAR(phi, theta []float64, n int) []float64
- func ARMAToMA(phi, theta []float64, n int) []float64
- func ARSpectralDensity(m *ARModel, nf int) (freqs, density []float64)
- func Argmax(x []float64) int
- func Argmin(x []float64) int
- func AutoCorrelation(x []float64, maxlag int) []float64
- func AutoCorrelationAt(x []float64, k int) float64
- func AutoCovariance(x []float64, maxlag int) []float64
- func AutoCovarianceAt(x []float64, k int) float64
- func AutocorrelationMatrix(x []float64, p int) [][]float64
- func BoxCox(x []float64, lambda float64) []float64
- func BoxPierce(x []float64, h int) float64
- func BrownDoubleExponential(x []float64, alpha float64, h int) []float64
- func Clip(x []float64, lo, hi float64) []float64
- func CoefficientOfVariation(x []float64) float64
- func CrossCorrelation(x, y []float64, maxlag int) []float64
- func CrossCorrelationAt(x, y []float64, k int) float64
- func CrossCovarianceAt(x, y []float64, k int) float64
- func CumProd(x []float64) []float64
- func CumSum(x []float64) []float64
- func CumulativeMovingAverage(x []float64) []float64
- func CumulativePeriodogram(x []float64) []float64
- func DFT(x []float64) []complex128
- func Demean(x []float64) []float64
- func Detrend(x []float64) []float64
- func Diff(x []float64) []float64
- func DiffOrder(x []float64, d int) []float64
- func DominantFrequency(x []float64) float64
- func DominantPeriod(x []float64) float64
- func DoubleExponentialMovingAverage(x []float64, alpha float64) []float64
- func DurbinWatson(e []float64) float64
- func Embed(x []float64, m, tau int) [][]float64
- func Energy(x []float64) float64
- func EstimateSeasonalPeriod(x []float64, maxLag int) int
- func ExpTransform(x []float64) []float64
- func ExpandingMax(x []float64) []float64
- func ExpandingMean(x []float64) []float64
- func ExpandingMin(x []float64) []float64
- func ExpandingSum(x []float64) []float64
- func ExponentialMovingAverage(x []float64, alpha float64) []float64
- func ExponentialMovingAverageSpan(x []float64, span int) []float64
- func First(x []float64) float64
- func FlattenMatrix(m [][]float64) []float64
- func FourierFrequencies(n int, d float64) []float64
- func FracDiffWeights(d float64, n int) []float64
- func FractionalDifference(x []float64, d float64) []float64
- func HankelMatrix(x []float64, rows int) [][]float64
- func InnovationsAlgorithm(gamma []float64, maxlag int) ([][]float64, []float64)
- func Integrate(d []float64, x0 float64) []float64
- func InverseBoxCox(y []float64, lambda float64) []float64
- func InverseDFT(X []complex128) []complex128
- func IsStationaryADF(x []float64, lags int, level float64) bool
- func Kurtosis(x []float64) float64
- func Lag(x []float64, k int) []float64
- func LagMatrix(x []float64, p int) ([][]float64, []float64)
- func Last(x []float64) float64
- func Lead(x []float64, k int) []float64
- func LevinsonDurbin(gamma []float64, p int) ([]float64, float64)
- func LjungBox(x []float64, h int) float64
- func LogReturns(x []float64) []float64
- func LogTransform(x []float64) []float64
- func Max(x []float64) float64
- func Mean(x []float64) float64
- func MeanAbsoluteDeviation(x []float64) float64
- func MeanAbsoluteError(actual, forecast []float64) float64
- func MeanAbsolutePercentageError(actual, forecast []float64) float64
- func MeanAbsoluteScaledError(actual, forecast, train []float64, m int) float64
- func MeanError(actual, forecast []float64) float64
- func MeanSquaredError(actual, forecast []float64) float64
- func Median(x []float64) float64
- func MedianAbsoluteError(actual, forecast []float64) float64
- func MedianFilter(x []float64, w int) []float64
- func Min(x []float64) float64
- func MinMaxNormalize(x []float64) []float64
- func MovingAverage(x []float64, w int) []float64
- func MovingAverageCentered(x []float64, w int) []float64
- func MovingAverageValid(x []float64, w int) []float64
- func NumberOfDifferences(x []float64, lags, maxD int, level float64) int
- func PartialAutoCorrelation(x []float64, maxlag int) []float64
- func Percentile(x []float64, p float64) float64
- func Periodogram(x []float64) (freqs, power []float64)
- func PopStdDev(x []float64) float64
- func PopVariance(x []float64) float64
- func Quantile(x []float64, q float64) float64
- func RSquared(actual, forecast []float64) float64
- func Range(x []float64) float64
- func ReflectionCoefficients(x []float64, p int) []float64
- func Rescale(x []float64, a, b float64) []float64
- func Reverse(x []float64) []float64
- func RollingMax(x []float64, w int) []float64
- func RollingMean(x []float64, w int) []float64
- func RollingMedian(x []float64, w int) []float64
- func RollingMin(x []float64, w int) []float64
- func RollingStdDev(x []float64, w int) []float64
- func RollingSum(x []float64, w int) []float64
- func RollingVariance(x []float64, w int) []float64
- func RootMeanSquare(x []float64) float64
- func RootMeanSquaredError(actual, forecast []float64) float64
- func SESForecast(x []float64, alpha float64, h int) []float64
- func SeasonalDiff(x []float64, s int) []float64
- func SeasonalIndices(x []float64, period int, mult bool) []float64
- func SeasonalIntegrate(d []float64, seed []float64, s int) []float64
- func SeasonallyAdjust(x []float64, period int, mult bool) []float64
- func Shift(x []float64, k int, fill float64) []float64
- func SimpleExponentialSmoothing(x []float64, alpha float64) []float64
- func SimpleReturns(x []float64) []float64
- func Skewness(x []float64) float64
- func SlidingWindows(x []float64, w, step int) [][]float64
- func SpectralEntropy(x []float64) float64
- func SqrtTransform(x []float64) []float64
- func Standardize(x []float64) []float64
- func StdDev(x []float64) float64
- func Sum(x []float64) float64
- func SymmetricMAPE(actual, forecast []float64) float64
- func TakensThetaAutoMI(x []float64, maxLag int) int
- func TheilU(actual, forecast []float64) float64
- func TimeDelayEmbedding(x []float64, dimension, delay int) [][]float64
- func ToeplitzMatrix(c []float64) [][]float64
- func TrendComponent(x []float64, period int) []float64
- func TrendLine(x []float64) []float64
- func TriangularMovingAverage(x []float64, w int) []float64
- func TripleExponentialMovingAverage(x []float64, alpha float64) []float64
- func Variance(x []float64) float64
- func VarianceRatio(x []float64, q int) float64
- func WeightedMovingAverage(x []float64, weights []float64) []float64
- type ADFResult
- type ARIMAModel
- type ARMAModel
- type ARModel
- type Decomposition
- type HoltModel
- type HoltWintersModel
- type KPSSResult
- type LinearFit
- type MAModel
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ACFConfidenceBound ¶
ACFConfidenceBound returns the approximate two-sided 95% confidence bound 1.96/√n for the autocorrelations of white noise of length n.
func ADFCriticalValue ¶
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 ¶
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 ¶
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 ¶
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 ¶
Argmax returns the index of the largest value, or -1 if the series is empty. The first index is returned on ties.
func Argmin ¶
Argmin returns the index of the smallest value, or -1 if the series is empty. The first index is returned on ties.
func AutoCorrelation ¶
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 ¶
AutoCorrelationAt returns the sample autocorrelation at lag k, i.e. AutoCovarianceAt(x,k) divided by the lag-0 autocovariance.
func AutoCovariance ¶
AutoCovariance returns the biased sample autocovariances of the series for lags 0,1,…,maxlag. Element 0 is the population variance.
func AutoCovarianceAt ¶
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 ¶
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 ¶
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 ¶
BoxPierce returns the Box–Pierce Q statistic for the first h autocorrelation lags, the simpler large-sample precursor to LjungBox.
func BrownDoubleExponential ¶
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 CoefficientOfVariation ¶
CoefficientOfVariation returns the ratio of the sample standard deviation to the mean, a scale-free measure of dispersion.
func CrossCorrelation ¶
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 ¶
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 ¶
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 CumulativeMovingAverage ¶
CumulativeMovingAverage returns the running (expanding-window) mean of the series: out[i] is the mean of x[0..i].
func CumulativePeriodogram ¶
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 Detrend ¶
Detrend removes a least-squares linear trend from the series, returning the residuals x[i] − (a + b·i).
func Diff ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 EstimateSeasonalPeriod ¶
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 ¶
ExpTransform returns the exponential of each observation (the inverse of LogTransform).
func ExpandingMax ¶
ExpandingMax returns the running maximum: out[i] = max(x[0..i]).
func ExpandingMean ¶
ExpandingMean returns the expanding-window mean, identical to CumulativeMovingAverage.
func ExpandingMin ¶
ExpandingMin returns the running minimum: out[i] = min(x[0..i]).
func ExpandingSum ¶
ExpandingSum returns the expanding-window sum, identical to CumSum.
func ExponentialMovingAverage ¶
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 ¶
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 FlattenMatrix ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 Lead ¶
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 ¶
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 ¶
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 ¶
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 ¶
LogTransform returns the natural logarithm of each observation. Non-positive inputs map to NaN.
func MeanAbsoluteDeviation ¶
MeanAbsoluteDeviation returns the mean of the absolute deviations from the series mean.
func MeanAbsoluteError ¶
MeanAbsoluteError returns the mean of |actual − forecast| over the aligned pairs. It returns NaN if the lengths differ or are zero.
func MeanAbsolutePercentageError ¶
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 ¶
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 ¶
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 ¶
MeanSquaredError returns the mean of (actual − forecast)² over the aligned pairs. It returns NaN if the lengths differ or are zero.
func Median ¶
Median returns the median of the series, or NaN if it is empty. The input is not modified.
func MedianAbsoluteError ¶
MedianAbsoluteError returns the median of |actual − forecast| over the aligned pairs, a robust accuracy measure.
func MedianFilter ¶
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 MinMaxNormalize ¶
MinMaxNormalize rescales the series linearly to the unit interval [0,1]. If all values are equal the result is all zeros.
func MovingAverage ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Percentile returns the p-th percentile (0 ≤ p ≤ 100) of the series.
func Periodogram ¶
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 ¶
PopStdDev returns the population standard deviation (square root of PopVariance).
func PopVariance ¶
PopVariance returns the population (divide-by-n) variance of the series. It returns NaN for an empty series.
func Quantile ¶
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 ¶
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 ReflectionCoefficients ¶
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 RollingMax ¶
RollingMax returns the trailing rolling maximum over full windows of length w. It returns nil if w < 1 or w > len(x).
func RollingMean ¶
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 ¶
RollingMedian returns the trailing rolling median over full windows of length w. It returns nil if w < 1 or w > len(x).
func RollingMin ¶
RollingMin returns the trailing rolling minimum over full windows of length w. It returns nil if w < 1 or w > len(x).
func RollingStdDev ¶
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 ¶
RollingSum returns the trailing rolling sum over full windows of length w. It returns nil if w < 1 or w > len(x).
func RollingVariance ¶
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 ¶
RootMeanSquare returns sqrt(mean(x²)), the quadratic mean of the series.
func RootMeanSquaredError ¶
RootMeanSquaredError returns the square root of MeanSquaredError.
func SESForecast ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SqrtTransform returns the square root of each observation. Negative inputs map to NaN.
func Standardize ¶
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 SymmetricMAPE ¶
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 ¶
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 ¶
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 ¶
TimeDelayEmbedding is an alias for Embed with the conventional argument order (dimension then delay), returning the delay-coordinate matrix.
func ToeplitzMatrix ¶
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 ¶
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 TriangularMovingAverage ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
DickeyFuller performs the simple (non-augmented) Dickey–Fuller test with a constant, equivalent to ADFTest with zero augmenting lags and no trend.
type ARIMAModel ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
Forecast returns the h-step-ahead recursive forecasts of the AR model given the observed history x, feeding predicted values back in as needed.
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 ¶
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 ¶
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.
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 ¶
LinearFit holds the coefficients of a straight line y = Intercept + Slope·t.
func FitLinearTrend ¶
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.
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 ¶
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.