forecaster

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2024 License: MIT Imports: 15 Imported by: 0

README

go-forecaster

forecasting library

Go Report Card 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"

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

func MyForecast(t []time.Time, y []float64) (*forecaster.Results, error) {
	f, err := forecaster.New(nil)
	if err != nil {
		return nil, err
	}
	if err := f.Fit(t, y); err != nil {
		return nil, err
	}
	eq, err := f.SeriesModelEq()
	if err != nil {
	  return nil, err
	}
	fmt.Fprintln(os.Stderr, eq)

	return f.Predict(td.T)
}	

Documentation

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")
	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) *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

Example
t, y := generateExampleSeries()

changepoints := []changepoint.Changepoint{
	changepoint.New("anomaly1", t[len(t)/2]),
	changepoint.New("anomaly2", t[len(t)*17/20]),
}

opt := &Options{
	SeriesOptions: &forecast.Options{
		DailyOrders:  12,
		WeeklyOrders: 12,
		ChangepointOptions: forecast.ChangepointOptions{
			Changepoints: changepoints,
		},
	},
	ResidualOptions: &forecast.Options{
		DailyOrders:  12,
		WeeklyOrders: 12,
		ChangepointOptions: forecast.ChangepointOptions{
			Changepoints: changepoints,
		},
	},
	OutlierOptions: NewOutlierOptions(),
	ResidualWindow: 100,
	ResidualZscore: 4.0,
}

f, err := New(opt)
if err != nil {
	panic(err)
}
if err := f.Fit(t, y); err != nil {
	panic(err)
}

m, err := f.Model()
if err != nil {
	panic(err)
}
out, err := json.MarshalIndent(m, "", "  ")
if err != nil {
	panic(err)
}
fmt.Fprintln(os.Stderr, string(out))

if err := f.PlotFit("examples/forecaster.html", nil); err != nil {
	panic(err)
}
Output:

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) 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) 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(path string, 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) ResidualCoefficients

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

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

func (*Forecaster) ResidualIntercept

func (f *Forecaster) ResidualIntercept() float64

ResidualIntercept returns the intercept of the uncertainty fit

func (*Forecaster) ResidualModelEq added in v0.0.4

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

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

func (*Forecaster) Residuals

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

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

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

type Model

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

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

type Options

type Options struct {
	SeriesOptions   *forecast.Options `json:"-"`
	ResidualOptions *forecast.Options `json:"-"`

	OutlierOptions *OutlierOptions `json:"outlier_options"`
	ResidualWindow int             `json:"residual_window"`
	ResidualZscore float64         `json:"residual_zscore"`
}

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

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"`
	ResidualComponents forecast.Components `json:"residual_components"`
}

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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