forecaster

package module
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2025 License: MIT Imports: 16 Imported by: 0

README

go-forecaster

forecasting library

Go Report Card codecov GoDoc License

Example 1

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

Example 2

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

Example 3

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

Example Use

import (
  "fmt"
  "time"

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

func MyForecast(t []time.Time, y []float64) ([]float64, error) {
  // initialize forecaster
  f, err := forecaster.New(nil)
  if err != nil {
    return nil, err
  }

  // fit the model
  if err := f.Fit(t, y); err != nil {
    return nil, err
  }

  // create future time slice with 10 samples after last training time at minute level
  // granularity
  horizon, err := f.MakeFuturePeriods(10, time.Minute)
  if err != nil {
    return nil, err
  }
  return f.Predict(horizon)
} 

Documentation

Index

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")
	ErrNoOptionsInModel     = errors.New("no options set in model")
	ErrCannotInferInterval  = errors.New("cannot infer interval from training data time")
)

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

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

UncertaintyIntercept returns the intercept of the uncertainty fit

func (*Forecaster) UncertaintyModelEq added in v0.2.0

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

ResidualModelEq 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"`
}

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"`
}

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:"-"`
	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:"-"`
	ResidualWindow  int              `json:"residual_window"`
	ResidualZscore  float64          `json:"residual_zscore"`
}

func NewUncertaintyOptions added in v0.2.0

func NewUncertaintyOptions() *UncertaintyOptions

Directories

Path Synopsis
floatsunrolled is inspired by the SIMD blog post https://github.com/camdencheek/simd_blog/blob/main/main.go
floatsunrolled is inspired by the SIMD blog post https://github.com/camdencheek/simd_blog/blob/main/main.go

Jump to

Keyboard shortcuts

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