forecaster

package module
v0.3.14 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2025 License: MIT Imports: 17 Imported by: 0

README

go-forecaster

Go Report Card codecov GoDoc License

go-forecaster is a Go library designed for time-series forecasting. It enables users to model and predict data with strong seasonal components, events, holidays, change points, and trends. The library offers functionalities for fitting forecast models, making future predictions, and visualizing results using Apache ECharts.​

Features

  • Model Fitting: Fit time-series data to capture trends, seasonal patterns, and events.
  • Prediction: Generate forecasts for future time points based on fitted models.
  • Visualization: Create interactive line charts to visualize actual data alongside forecasts and confidence intervals.
  • Changepoint Detection: Identify points where the time-series data exhibits abrupt changes in trend or seasonality.
  • Event Components: Incorporate and analyze the impact of specific events on the time-series data.

Examples

Contains a daily seasonal component with 2 anomalous behaviors along with 2 registered change points Forecast Example

Contains a daily seasonal component with a trend change point which resets Forecast With Trend Example

Auto-changepoint detection and fit Forecast With Auto-Changepoint Detection Example

Installation

To install go-forecaster, use go get:

go get github.com/aouyang1/go-forecaster

Usage

Here's a basic example demonstrating how to use go-forecaster:

package main

import (
    "fmt"
    "time"

    "github.com/aouyang1/go-forecaster"
)

func main() {
    // Sample time-series data
    times := []time.Time{...} // Your time data here
    values := []float64{...}  // Corresponding values

    // Initialize the forecaster with default options
    f, err := forecaster.New(nil)
    if err != nil {
        fmt.Println("Error initializing forecaster:", err)
        return
    }

    // Fit the model to the data
    err = f.Fit(times, values)
    if err != nil {
        fmt.Println("Error fitting model:", err)
        return
    }

    // Generate future time points for prediction
    futureTimes, err := f.MakeFuturePeriods(10, 24*time.Hour)
    if err != nil {
        fmt.Println("Error generating future periods:", err)
        return
    }

    // Predict future values
    results, err := f.Predict(futureTimes)
    if err != nil {
        fmt.Println("Error making predictions:", err)
        return
    }

    // Output the predictions
    for i, t := range futureTimes {
        fmt.Printf("Date: %s, Forecast: %.2f\n", t.Format("2006-01-02"), results.Forecast[i])
    }
}

This example initializes a forecaster, fits it to sample data, and predicts future values. For more detailed examples, refer to the examples directory in the repository.

Visualization

go-forecaster integrates with Apache ECharts to provide interactive visualizations of your forecasts. After fitting a model, you can generate an HTML visualization:

// Assuming 'f' is your fitted Forecaster instance
err := f.PlotFit(outputWriter, nil)
if err != nil {
    fmt.Println("Error generating plot:", err)
}

This will create an HTML file displaying the original data, the forecast, and confidence intervals.

Documentation

Comprehensive documentation is available on pkg.go.dev, detailing all available functions and types.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are welcome! If you encounter issues or have suggestions for improvements, please open an issue or submit a pull request.

Documentation

Overview

Package forecaster is the high level forecasting package for fitting and predicting other time points given a single time series. This will generate a model for both the forecast values as well as the uncertainty value. Uncertainty here represents the lower and upper bounds to be expected of a time series. This has only univariate time series support.

Example (ForecasterWithOutliers)
t, y, opt := setupWithOutliers()

defer recoverForecastPanic(nil)

if err := runForecastExample(opt, t, y, "examples/forecaster.html"); err != nil {
	panic(err)
}
Example (ForecasterWithPulses)
t, y, opt := setupWithPulses()

defer recoverForecastPanic(nil)

if err := runForecastExample(opt, t, y, "examples/forecaster_pulses.html"); err != nil {
	panic(err)
}
Example (ForecasterWithTrend)
t, y := generateExampleSeriesWithTrend()

changepoints := []options.Changepoint{
	options.NewChangepoint("trendstart", t[len(t)/2]),
	options.NewChangepoint("rebaseline", t[len(t)*17/20]),
}

opt := &Options{
	SeriesOptions: &SeriesOptions{
		ForecastOptions: &options.Options{
			SeasonalityOptions: options.SeasonalityOptions{
				SeasonalityConfigs: []options.SeasonalityConfig{
					options.NewDailySeasonalityConfig(12),
					options.NewWeeklySeasonalityConfig(12),
				},
			},
			Iterations: 500,
			Tolerance:  1e-3,
			ChangepointOptions: options.ChangepointOptions{
				Changepoints: changepoints,
				EnableGrowth: true,
			},
		},
		OutlierOptions: NewOutlierOptions(),
	},
	UncertaintyOptions: &UncertaintyOptions{
		ForecastOptions: &options.Options{
			SeasonalityOptions: options.SeasonalityOptions{
				SeasonalityConfigs: []options.SeasonalityConfig{
					options.NewDailySeasonalityConfig(12),
					options.NewWeeklySeasonalityConfig(12),
				},
			},
			Iterations: 250,
			Tolerance:  1e-2,
			ChangepointOptions: options.ChangepointOptions{
				Changepoints: nil,
			},
		},
		ResidualWindow: 100,
		ResidualZscore: 4.0,
	},
}

defer recoverForecastPanic(nil)

if err := runForecastExample(opt, t, y, "examples/forecaster_with_trend.html"); err != nil {
	panic(err)
}

Index

Examples

Constants

View Source
const (
	MinResidualWindow       = 2
	MinResidualSize         = 2
	MinResidualWindowFactor = 4
)

Variables

View Source
var (
	ErrInsufficientResidual         = errors.New("insufficient samples from residual after outlier removal")
	ErrEmptyTimeDataset             = errors.New("no timedataset or uninitialized")
	ErrCannotInferInterval          = errors.New("cannot infer interval from training data time")
	ErrNoSeriesOrUncertaintyOptions = errors.New("no series or uncertainty options provided")
)

Functions

func LineForecaster added in v0.0.5

func LineForecaster(trainingData *timedataset.TimeDataset, fitRes, forecastRes *Results) *charts.Line

LineForecaster generates an echart line chart for a give fit result plotting the expected values along with the forecasted, upper, lower values.

func LineTSeries added in v0.0.5

func LineTSeries(title string, seriesName []string, t []time.Time, y [][]float64, forecastStartIdx int) *charts.Line

LineTSeries generates an echart multi-line chart for some arbitrary time/value combination. The input y is a slice of series that much have the same length as the input time slice.

Types

type Forecaster

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

Forecaster fits a forecast model and can be used to generate forecasts

func New

func New(opt *Options) (*Forecaster, error)

New creates a new instance of a Forecaster using thhe provided options. If no options are provided a default is used.

func NewFromModel

func NewFromModel(model Model) (*Forecaster, error)

NewFromModel creates a new instance of Forecaster from a pre-existing model. This should be generated from from a previous forecaster call to Model().

func (*Forecaster) EventComponent added in v0.2.11

func (f *Forecaster) EventComponent() []float64

EventComponent returns the event component after fitting the fourier series

func (*Forecaster) Fit

func (f *Forecaster) Fit(t []time.Time, y []float64) error

Fit uses the input time dataset and fits the forecast model

func (*Forecaster) FitResults added in v0.0.5

func (f *Forecaster) FitResults() *Results

FitResults returns the results of the fit which includes the forecast, upper, and lower values

func (*Forecaster) MakeFuturePeriods added in v0.2.3

func (f *Forecaster) MakeFuturePeriods(periods int, freq time.Duration) ([]time.Time, error)

MakeFuturePeriods generates a slice of time after the last point in the training data. By default a zero freq will be inferred from the training data.

func (*Forecaster) Model

func (f *Forecaster) Model() (Model, error)

Model generates a serializeable representaioon of the fit options, series model, and uncertainty model. This can be used to initialize a new Forecaster for immediate predictions skipping the training step.

func (*Forecaster) PlotFit added in v0.0.5

func (f *Forecaster) PlotFit(w io.Writer, opt *PlotOpts) error

PlotFit uses the Apache Echarts library to generate an html file showing the resulting fit, model components, and fit residual

func (*Forecaster) Predict

func (f *Forecaster) Predict(t []time.Time) (*Results, error)

Predict takes in any set of time samples and generates a forecast, upper, lower values per time point

func (*Forecaster) Residuals

func (f *Forecaster) Residuals() []float64

Residuals returns the difference between the final series fit against the training data

func (*Forecaster) Score added in v0.2.1

func (f *Forecaster) Score(t []time.Time, y []float64) (float64, error)

Score computes the coefficient of determination of the prediction

func (*Forecaster) SeasonalityComponent

func (f *Forecaster) SeasonalityComponent() []float64

SeasonalityComponent returns the seasonality component after fitting the fourier series

func (*Forecaster) SeriesCoefficients

func (f *Forecaster) SeriesCoefficients() (map[string]float64, error)

SeriesCoefficients returns all coefficient weight associated with the component label string

func (*Forecaster) SeriesIntercept

func (f *Forecaster) SeriesIntercept() (float64, error)

SeriesIntercept returns the intercept of the series fit

func (*Forecaster) SeriesModelEq added in v0.0.4

func (f *Forecaster) SeriesModelEq() (string, error)

SeriesModelEq returns a string representation of the fit series model represented as y ~ b + m1x1 + m2x2 ...

func (*Forecaster) TrainingData added in v0.0.5

func (f *Forecaster) TrainingData() *timedataset.TimeDataset

TrainingData returns the training data used to fit the current forecaster model

func (*Forecaster) TrendComponent

func (f *Forecaster) TrendComponent() []float64

TrendComponent returns the trend component created by changepoints after fitting

func (*Forecaster) Uncertainty added in v0.2.0

func (f *Forecaster) Uncertainty() []float64

Uncertainty returns the uncertainty series used to forecast the upper lower bounds

func (*Forecaster) UncertaintyCoefficients added in v0.2.0

func (f *Forecaster) UncertaintyCoefficients() (map[string]float64, error)

UncertaintyCoefficients returns all uncertainty coefficient weights associated with the component label string

func (*Forecaster) UncertaintyIntercept added in v0.2.0

func (f *Forecaster) UncertaintyIntercept() (float64, error)

UncertaintyIntercept returns the intercept of the uncertainty fit

func (*Forecaster) UncertaintyModelEq added in v0.2.0

func (f *Forecaster) UncertaintyModelEq() (string, error)

UncertaintyModelEq returns a string representation of the fit uncertainty model represented as y ~ b + m1x1 + m2x2 ...

type Model

type Model struct {
	Options     *Options       `json:"options"`
	Series      forecast.Model `json:"series_model"`
	Uncertainty forecast.Model `json:"uncertainty_model"`
}

Model is a serializeable representation of the forecaster's configurations and models for the forecast and uncertainty.

func (Model) JSONPrettyPrint added in v0.2.0

func (m Model) JSONPrettyPrint(w io.Writer) error

func (Model) TablePrint added in v0.2.0

func (m Model) TablePrint(w io.Writer) error

type Options

type Options struct {
	SeriesOptions       *SeriesOptions      `json:"series_options"`
	UncertaintyOptions  *UncertaintyOptions `json:"uncertainty_options"`
	MinValue            *float64            `json:"min_value"`
	MaxValue            *float64            `json:"max_value"`
	MinUncertaintyValue float64             `json:"min_uncertainty_value"`
}

Options represents all forecaster options for outlier removal, forecast fit, and uncertainty fit

func NewDefaultOptions added in v0.0.5

func NewDefaultOptions() *Options

NewDefaultOptions generates a default set of options for a forecaster

func (*Options) SetMaxValue added in v0.2.5

func (o *Options) SetMaxValue(val float64)

func (*Options) SetMinValue added in v0.2.5

func (o *Options) SetMinValue(val float64)

type OutlierOptions

type OutlierOptions struct {
	NumPasses       int     `json:"num_passes"`
	UpperPercentile float64 `json:"upper_percentile"`
	LowerPercentile float64 `json:"lower_percentile"`
	TukeyFactor     float64 `json:"tukey_factor"`

	// Events are explicitly set time ranges that are excluded from training
	Events []options.Event `json:"events"`
}

OutlierOptions configures the outlier removal pre-process using the Tukey Method. The outlier removal process is done by multiple iterations of fitting the training data to a model and each step removing outliers. For IQR set UpperPercentile too 0.75, LowerPercentile to 0.25, and TukeyFactor to 1.5.

func NewOutlierOptions

func NewOutlierOptions() *OutlierOptions

NewOutlierOptions generates a default set of outlier options

type PlotOpts added in v0.1.3

type PlotOpts struct {
	HorizonCnt      int
	HorizonInterval time.Duration
}

PlotOpts sets the horizon to forecast out. By default will use 10% of the training size assuming even intervals between points and the first two points are used to infer the horizon interval.

type Results

type Results struct {
	T        []time.Time `json:"time"`
	Forecast []float64   `json:"forecast"`
	Upper    []float64   `json:"upper"`
	Lower    []float64   `json:"lower"`

	SeriesComponents      forecast.Components `json:"series_components"`
	UncertaintyComponents forecast.Components `json:"uncertainty_components"`
}

Results returns the input time points with their predicted forecast, upper, and lower values. Slices will be of the same length.

type SeriesOptions added in v0.2.0

type SeriesOptions struct {
	ForecastOptions *options.Options `json:"forecast_options"`
	OutlierOptions  *OutlierOptions  `json:"outlier_options"`
}

func NewSeriesOptions added in v0.2.0

func NewSeriesOptions() *SeriesOptions

type UncertaintyOptions added in v0.2.0

type UncertaintyOptions struct {
	ForecastOptions *options.Options `json:"forecast_options"`
	ResidualWindow  int              `json:"residual_window"`
	ResidualZscore  float64          `json:"residual_zscore"`
}

func NewUncertaintyOptions added in v0.2.0

func NewUncertaintyOptions() *UncertaintyOptions

Directories

Path Synopsis
Package feature represents a feature type modelled in the forecast
Package feature represents a feature type modelled in the forecast
Package forecast performs a single linear model fit and predict for a univariate timeseries
Package forecast performs a single linear model fit and predict for a univariate timeseries
options
Package options contains all forecast options for a linear fit of a univariate time series
Package options contains all forecast options for a linear fit of a univariate time series
util
Package util are extra utility methods
Package util are extra utility methods
Package linearmodel is a collection of linear regression fitting implementations to be used in the forecaster
Package linearmodel is a collection of linear regression fitting implementations to be used in the forecaster
mat is an extension of the mat package in gonum
mat is an extension of the mat package in gonum
Package stats is a collection of helpful statistical methods
Package stats is a collection of helpful statistical methods
Package timedataset represents a univariate timeseries with equal time and value samples
Package timedataset represents a univariate timeseries with equal time and value samples

Jump to

Keyboard shortcuts

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