study

package
v0.12.2 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package study provides a framework for running a strategy multiple times with different configurations and synthesizing the results into a report. Parameter sweeps are cross-producted with study configurations to produce the run matrix. Results are collected and passed to a study-specific Analyze function that composes a report from report primitives.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WindowedScore added in v0.5.0

func WindowedScore(rp report.ReportablePortfolio, window DateRange, metric portfolio.PerformanceMetric) float64

WindowedScore computes the given metric for rp restricted to the closed date interval [window.Start, window.End]. It returns NaN if the metric cannot be computed (e.g. the window contains no data).

func WindowedScoreExcluding added in v0.5.0

func WindowedScoreExcluding(rp report.ReportablePortfolio, window DateRange, exclude []DateRange, metric portfolio.PerformanceMetric) float64

WindowedScoreExcluding computes the given metric for rp over window, ignoring sub-ranges listed in exclude. It computes the metric on each non-excluded segment and returns the duration-weighted average. When exclude is empty it delegates directly to WindowedScore.

Types

type BayesianOption added in v0.5.0

type BayesianOption func(*bayesianStrategy)

BayesianOption configures the Bayesian search strategy.

func WithBatchSize added in v0.5.0

func WithBatchSize(size int) BayesianOption

WithBatchSize sets the number of candidates returned per guided iteration.

func WithInitialSamples added in v0.5.0

func WithInitialSamples(count int) BayesianOption

WithInitialSamples sets the number of random samples drawn on the first call to Next.

func WithMaxIterations added in v0.5.0

func WithMaxIterations(max int) BayesianOption

WithMaxIterations sets the maximum number of guided (non-initial) iterations before the strategy signals completion.

type CombinationScore added in v0.5.0

type CombinationScore struct {
	Params map[string]string
	Preset string
	Score  float64
	Runs   []RunResult
}

CombinationScore records the outcome of evaluating one parameter combination.

type DateRange added in v0.5.0

type DateRange struct {
	Start time.Time
	End   time.Time
}

DateRange represents a closed interval of time [Start, End].

func SubtractRanges added in v0.6.0

func SubtractRanges(window DateRange, exclude []DateRange) []DateRange

SubtractRanges returns the portions of window not covered by any range in exclude. Exclude ranges are assumed non-overlapping. The returned slices share boundary timestamps with the exclusion ranges; this is acceptable because metric computations are insensitive to a single shared data point.

type EngineCustomizer

type EngineCustomizer interface {
	EngineOptions(cfg RunConfig) []engine.Option
}

EngineCustomizer is an optional interface that a Study can implement to customize per-run engine construction. When the runner detects that a study implements this interface, it calls EngineOptions for each run and appends the returned options to the base options before constructing the engine.

type Numeric

type Numeric interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64
}

Numeric constrains SweepRange to integer and floating-point types.

type ParamSweep

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

ParamSweep describes how to vary a single strategy parameter across runs.

func SweepDuration

func SweepDuration(field string, min, max, step time.Duration) ParamSweep

SweepDuration generates duration values from min to max with the given step.

func SweepPresets

func SweepPresets(presets ...string) ParamSweep

SweepPresets varies named parameter presets.

func SweepRange

func SweepRange[T Numeric](field string, min, max, step T) ParamSweep

SweepRange generates values from min to max (inclusive) with the given step.

func SweepValues

func SweepValues(field string, values ...string) ParamSweep

SweepValues provides explicit string values for a field.

func (ParamSweep) Field

func (ps ParamSweep) Field() string

Field returns the name of the parameter field being swept.

func (ParamSweep) IsPreset

func (ps ParamSweep) IsPreset() bool

IsPreset reports whether this sweep varies named presets rather than a single field.

func (ParamSweep) Max added in v0.5.0

func (ps ParamSweep) Max() string

Max returns the string-encoded upper bound of the sweep range, or empty for discrete sweeps.

func (ParamSweep) Min added in v0.5.0

func (ps ParamSweep) Min() string

Min returns the string-encoded lower bound of the sweep range, or empty for discrete sweeps.

func (ParamSweep) Values

func (ps ParamSweep) Values() []string

Values returns the list of string-encoded values for this sweep.

type Progress

type Progress struct {
	RunName    string
	RunIndex   int
	TotalRuns  int
	BatchIndex int
	BatchSize  int
	Status     RunStatus
	Err        error
}

Progress is sent on a channel as runs execute.

type Result

type Result struct {
	Runs   []RunResult
	Report report.Report
	Err    error
}

Result is sent on a channel when the study completes.

type RunConfig

type RunConfig struct {
	Name     string
	Start    time.Time
	End      time.Time
	Deposit  float64
	Preset   string
	Params   map[string]string
	Metadata map[string]string
}

RunConfig fully specifies what the engine should do for a single run.

func CrossProduct

func CrossProduct(base []RunConfig, sweeps []ParamSweep) []RunConfig

CrossProduct combines base configs with sweeps to produce the full run matrix.

type RunResult

type RunResult struct {
	Config    RunConfig
	Portfolio report.ReportablePortfolio
	Err       error
}

RunResult pairs a config with its outcome.

type RunStatus

type RunStatus int

RunStatus represents the state of a single run within a study.

const (
	RunStarted RunStatus = iota
	RunCompleted
	RunFailed
)

type Runner

type Runner struct {
	Study          Study
	NewStrategy    func() engine.Strategy
	Options        []engine.Option
	Workers        int
	Sweeps         []ParamSweep
	SearchStrategy SearchStrategy
	Splits         []Split
	Objective      portfolio.Rankable
}

Runner holds study configuration and executes the study.

func (*Runner) Run

func (runner *Runner) Run(ctx context.Context) (<-chan Progress, <-chan Result, error)

Run executes the study and returns channels for progress and the final result. If Configurations() fails, Run returns nil channels and the error synchronously.

type Scenario added in v0.5.0

type Scenario struct {
	Name        string
	Description string
	Start       time.Time
	End         time.Time
}

Scenario describes a historical market stress period with a name, description, and the date range over which the stress event occurred.

func AllScenarios added in v0.5.0

func AllScenarios() []Scenario

AllScenarios returns the built-in set of historical market stress scenarios.

func ScenariosByName added in v0.5.0

func ScenariosByName(names []string) ([]Scenario, error)

ScenariosByName returns the subset of AllScenarios matching the given names, preserving the order of the names slice. It returns an error if any name is not found in AllScenarios.

type SearchStrategy added in v0.5.0

type SearchStrategy interface {
	Next(scores []CombinationScore) (configs []RunConfig, done bool)
}

SearchStrategy generates parameter combinations to evaluate. Next is called with all previously scored combinations and returns the next batch of RunConfigs to execute. done=true signals that no further calls are needed.

func NewBayesian added in v0.5.0

func NewBayesian(sweeps []ParamSweep, seed int64, opts ...BayesianOption) SearchStrategy

NewBayesian creates a Bayesian optimization search strategy. It uses a Gaussian process surrogate model and Expected Improvement acquisition to guide the search.

func NewGrid added in v0.5.0

func NewGrid(sweeps ...ParamSweep) SearchStrategy

NewGrid returns a SearchStrategy that exhaustively enumerates all combinations of the given parameter sweeps. The first call to Next returns all configurations and done=true; subsequent calls return nothing.

func NewRandom added in v0.5.0

func NewRandom(sweeps []ParamSweep, samples int, seed int64) SearchStrategy

NewRandom returns a SearchStrategy that samples the given number of random parameter combinations. For sweeps with a non-empty Min()/Max(), values are drawn uniformly from [min, max] as float64. For sweeps without range bounds, values are drawn from the Values() list. seed controls reproducibility.

type Split added in v0.5.0

type Split struct {
	Name      string
	FullRange DateRange
	Train     DateRange
	Test      DateRange
	Exclude   []DateRange
}

Split describes a single train/test partition of a date range, optionally excluding sub-ranges from the training period.

func KFold added in v0.5.0

func KFold(start, end time.Time, folds int) ([]Split, error)

KFold partitions [start, end] into the given number of equal folds. Each split holds one fold out as the test set and trains on the full range, with the test fold listed in Exclude. It returns an error if folds < 2.

func ScenarioLeaveNOut added in v0.5.0

func ScenarioLeaveNOut(scenarios []Scenario, holdOut int) ([]Split, error)

ScenarioLeaveNOut produces C(len(scenarios), holdOut) splits. Each split holds out holdOut scenarios as the test set. Any remaining scenario that overlaps a held-out scenario is added to Exclude. The FullRange spans the earliest Start to the latest End across all scenarios. It returns an error if holdOut < 1 or holdOut > len(scenarios).

func TrainTest added in v0.5.0

func TrainTest(start, cutoff, end time.Time) ([]Split, error)

TrainTest produces a single split where training covers [start, cutoff] and testing covers [cutoff, end]. It returns an error if start >= end or if cutoff falls outside [start, end].

func WalkForward added in v0.5.0

func WalkForward(start, end time.Time, minTrain, testLen, step time.Duration) ([]Split, error)

WalkForward produces an expanding-window walk-forward validation. The first split trains on [start, start+minTrain) and tests on [start+minTrain, start+minTrain+testLen). Each subsequent split advances the test window by step and expands the training window accordingly. It returns an error if minTrain+testLen exceeds end-start.

type Study

type Study interface {
	Name() string
	Description() string
	Configurations(ctx context.Context) ([]RunConfig, error)
	Analyze(results []RunResult) (report.Report, error)
}

Study is the interface that each study type implements.

Directories

Path Synopsis
Package optimize implements the parameter-optimization study type.
Package optimize implements the parameter-optimization study type.
Package report defines the Report interface for Vue-based HTML reports and provides a Render function that produces self-contained HTML files.
Package report defines the Report interface for Vue-based HTML reports and provides a Render function that produces self-contained HTML files.
Package stress implements the stress test study type.
Package stress implements the stress test study type.

Jump to

Keyboard shortcuts

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