backtest

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FullFill added in v0.0.7

func FullFill(order *trading.Order, candle *series.Candle) decimal.Decimal

FullFill always fills the entire order.

func HalfFill added in v0.0.7

func HalfFill(order *trading.Order, candle *series.Candle) decimal.Decimal

HalfFill fills 50% of the order (useful for testing partial fills).

func NoCommission added in v0.0.7

func NoCommission(order *trading.Order, fillPrice, fillAmount decimal.Decimal) decimal.Decimal

NoCommission returns zero commission.

func NoSlippage added in v0.0.7

func NoSlippage(order *trading.Order, candle *series.Candle) decimal.Decimal

NoSlippage returns zero slippage.

func NumCPU added in v0.0.7

func NumCPU() int

NumCPU returns the number of logical CPUs available.

func ObjectiveMaxDrawdown added in v0.0.7

func ObjectiveMaxDrawdown(result BacktestResult) float64

ObjectiveMaxDrawdown returns a score where lower drawdown is better. The raw drawdown is negated so that maximizing the score minimizes drawdown.

func ObjectiveNetProfit added in v0.0.7

func ObjectiveNetProfit(result BacktestResult) float64

ObjectiveNetProfit returns the net profit as a score.

func ObjectiveProfitFactor added in v0.0.7

func ObjectiveProfitFactor(result BacktestResult) float64

ObjectiveProfitFactor returns the profit factor as a score.

func ObjectiveSharpeRatio added in v0.0.7

func ObjectiveSharpeRatio(result BacktestResult) float64

ObjectiveSharpeRatio computes a simple Sharpe-like ratio from trade profit percentages.

func ObjectiveWinRate added in v0.0.7

func ObjectiveWinRate(result BacktestResult) float64

ObjectiveWinRate returns the win rate as a score.

Types

type AnalysisResult added in v0.0.3

type AnalysisResult map[string]interface{}

AnalysisResult represents the collected results from all analyzers.

type Analyzer added in v0.0.3

type Analyzer interface {
	Name() string
	Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}
}

Analyzer is an interface for analyzing backtest results.

type AnalyzerRegistry added in v0.0.3

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

AnalyzerRegistry maintains a list of available analyzers.

func NewAnalyzerRegistry added in v0.0.3

func NewAnalyzerRegistry() *AnalyzerRegistry

NewAnalyzerRegistry returns a new AnalyzerRegistry.

func (*AnalyzerRegistry) Add added in v0.0.3

func (ar *AnalyzerRegistry) Add(analyzer Analyzer)

Add adds an analyzer to the registry.

func (*AnalyzerRegistry) Run added in v0.0.3

func (ar *AnalyzerRegistry) Run(trades []metrics.Trade, equityCurve []metrics.EquityPoint) AnalysisResult

Run executes all registered analyzers and returns the combined results.

type AverageTradeDurationAnalyzer added in v0.0.3

type AverageTradeDurationAnalyzer struct{}

func (*AverageTradeDurationAnalyzer) Analyze added in v0.0.3

func (atda *AverageTradeDurationAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*AverageTradeDurationAnalyzer) Name added in v0.0.3

func (atda *AverageTradeDurationAnalyzer) Name() string

type BacktestConfig

type BacktestConfig struct {
	InitialCapital decimal.Decimal
	PositionSize   decimal.Decimal
	RiskPerTrade   decimal.Decimal
	Commission     decimal.Decimal
	Slippage       decimal.Decimal
	AllowShort     bool
	AllowLong      bool
}

type BacktestExporter added in v0.0.7

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

func NewBacktestExporter added in v0.0.7

func NewBacktestExporter(opts ExportOptions) *BacktestExporter

func (*BacktestExporter) Export added in v0.0.7

func (e *BacktestExporter) Export(result BacktestResult, writer io.Writer) error

func (*BacktestExporter) ExportEquityCurve added in v0.0.7

func (e *BacktestExporter) ExportEquityCurve(curve []metrics.EquityPoint, writer io.Writer) error

func (*BacktestExporter) ExportSummary added in v0.0.7

func (e *BacktestExporter) ExportSummary(result BacktestResult, writer io.Writer) error

func (*BacktestExporter) ExportToFile added in v0.0.7

func (e *BacktestExporter) ExportToFile(result BacktestResult, path string) (err error)

func (*BacktestExporter) ExportTrades added in v0.0.7

func (e *BacktestExporter) ExportTrades(trades []Trade, writer io.Writer) error

type BacktestResult

type BacktestResult struct {
	TotalTrades          int
	WinningTrades        int
	LosingTrades         int
	WinRate              decimal.Decimal
	TotalProfit          decimal.Decimal
	TotalLoss            decimal.Decimal
	NetProfit            decimal.Decimal
	GrossProfit          decimal.Decimal
	GrossLoss            decimal.Decimal
	ProfitFactor         decimal.Decimal
	AverageWin           decimal.Decimal
	AverageLoss          decimal.Decimal
	AverageTrade         decimal.Decimal
	MaxConsecutiveWins   int
	MaxConsecutiveLosses int
	MaxDrawdown          decimal.Decimal
	MaxDrawdownPercent   decimal.Decimal
	RecoveryFactor       decimal.Decimal
	RiskRewardRatio      decimal.Decimal
	CalmarRatio          decimal.Decimal
	SortinoRatio         decimal.Decimal
	SharpeRatio          decimal.Decimal
	CAGR                 decimal.Decimal
	FinalEquity          decimal.Decimal
	InitialCapital       decimal.Decimal
	Trades               []Trade
	Analysis             AnalysisResult
}

type Backtester

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

func NewBacktester

func NewBacktester(s *series.TimeSeries, strategy trading.Strategy) *Backtester

func (*Backtester) AddAnalyzer added in v0.0.3

func (b *Backtester) AddAnalyzer(a Analyzer)

AddAnalyzer adds an analyzer to the backtester.

func (*Backtester) Run

func (b *Backtester) Run(config BacktestConfig) BacktestResult

type BarEventData added in v0.0.7

type BarEventData struct {
	Candle *series.Candle
}

BarEventData contains the candle data for a bar event.

type CommissionModel added in v0.0.7

type CommissionModel func(order *trading.Order, fillPrice, fillAmount decimal.Decimal) decimal.Decimal

CommissionModel computes the commission for an order fill.

func FixedCommission added in v0.0.7

func FixedCommission(amount decimal.Decimal) CommissionModel

FixedCommission returns a fixed commission per order fill.

func PercentCommission added in v0.0.7

func PercentCommission(pct float64) CommissionModel

PercentCommission returns commission as a percentage of fill value.

type DrawdownAnalyzer added in v0.0.3

type DrawdownAnalyzer struct{}

DrawdownAnalyzer analyzes drawdown performance.

func (*DrawdownAnalyzer) Analyze added in v0.0.3

func (a *DrawdownAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*DrawdownAnalyzer) Name added in v0.0.3

func (a *DrawdownAnalyzer) Name() string

type DrawdownStats added in v0.0.3

type DrawdownStats struct {
	MaxDrawdown    decimal.Decimal
	MaxDrawdownPct decimal.Decimal
}

DrawdownStats represents drawdown statistics.

type EquityCurveAnalyzer added in v0.0.3

type EquityCurveAnalyzer struct{}

EquityCurveAnalyzer simply returns the equity curve data points.

func (*EquityCurveAnalyzer) Analyze added in v0.0.3

func (a *EquityCurveAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*EquityCurveAnalyzer) Name added in v0.0.3

func (a *EquityCurveAnalyzer) Name() string

type ErrInvalidWFAConfig added in v0.0.6

type ErrInvalidWFAConfig string

ErrInvalidWFAConfig is returned when WFAConfig fails validation.

func (ErrInvalidWFAConfig) Error added in v0.0.6

func (e ErrInvalidWFAConfig) Error() string

type Event added in v0.0.7

type Event struct {
	Type      EventType
	Timestamp time.Time
	Symbol    string
	Data      any
}

Event represents a market event in chronological order.

type EventDrivenBacktester added in v0.0.7

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

EventDrivenBacktester processes market events bar-by-bar for realistic order simulation.

func NewEventDrivenBacktester added in v0.0.7

func NewEventDrivenBacktester() *EventDrivenBacktester

NewEventDrivenBacktester creates a new event-driven backtester.

func (*EventDrivenBacktester) AddAnalyzer added in v0.0.7

func (edb *EventDrivenBacktester) AddAnalyzer(a Analyzer)

AddAnalyzer adds an analyzer to the backtester.

func (*EventDrivenBacktester) Register added in v0.0.7

func (edb *EventDrivenBacktester) Register(symbol string, broker *SimulatedBroker, strategy trading.Strategy)

Register associates a symbol with its broker and strategy.

func (*EventDrivenBacktester) Run added in v0.0.7

func (edb *EventDrivenBacktester) Run(events []Event) (map[string]BacktestResult, error)

Run processes events in chronological order and returns per-symbol results.

type EventType added in v0.0.7

type EventType string

EventType defines the type of event.

const (
	// EventBar represents a bar (candle) event.
	EventBar EventType = "bar"
)

type ExpectancyAnalyzer added in v0.0.3

type ExpectancyAnalyzer struct{}

func (*ExpectancyAnalyzer) Analyze added in v0.0.3

func (ea *ExpectancyAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*ExpectancyAnalyzer) Name added in v0.0.3

func (ea *ExpectancyAnalyzer) Name() string

type ExpectancyPerTradeAnalyzer added in v0.0.3

type ExpectancyPerTradeAnalyzer struct{}

func (*ExpectancyPerTradeAnalyzer) Analyze added in v0.0.3

func (ept *ExpectancyPerTradeAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*ExpectancyPerTradeAnalyzer) Name added in v0.0.3

func (ept *ExpectancyPerTradeAnalyzer) Name() string

type ExportFormat added in v0.0.7

type ExportFormat string
const (
	ExportFormatCSV  ExportFormat = "csv"
	ExportFormatJSON ExportFormat = "json"
)

type ExportOptions added in v0.0.7

type ExportOptions struct {
	Format        ExportFormat
	TimeFormat    string
	PrettyPrint   bool
	IncludeHeader bool
}

func DefaultExportOptions added in v0.0.7

func DefaultExportOptions() ExportOptions

type FillPriceSource added in v0.0.7

type FillPriceSource int

FillPriceSource determines which price to use for market order fills.

const (
	// FillAtOpen fills market orders at the bar's open price.
	FillAtOpen FillPriceSource = iota
	// FillAtClose fills market orders at the bar's close price.
	FillAtClose
)

type MCMethod added in v0.0.7

type MCMethod string

MCMethod defines the Monte Carlo simulation method.

const (
	// MCMethodTradeShuffle randomly reorders trades.
	MCMethodTradeShuffle MCMethod = "trade_shuffle"
	// MCMethodBootstrap resamples trades with replacement.
	MCMethodBootstrap MCMethod = "bootstrap"
	// MCMethodRandomStart takes a random contiguous subset of trades.
	MCMethodRandomStart MCMethod = "random_start"
)

type MCSimulationConfig added in v0.0.7

type MCSimulationConfig struct {
	// Simulations is the number of Monte Carlo runs. Default 10000.
	Simulations int
	// ConfidenceLevel is the confidence level for intervals, e.g. 0.95.
	ConfidenceLevel float64
	// Method is the simulation method.
	Method MCMethod
	// Seed is the random seed. Zero means time-based.
	Seed int64
}

MCSimulationConfig configures the Monte Carlo simulation.

func DefaultMCSimulationConfig added in v0.0.7

func DefaultMCSimulationConfig() MCSimulationConfig

DefaultMCSimulationConfig returns a default configuration.

type MCSimulationResult added in v0.0.7

type MCSimulationResult struct {
	SimulatedEquityCurves          [][]metrics.EquityPoint
	FinalEquityStats               MCStats
	MaxDrawdownStats               MCStats
	SharpeStats                    MCStats
	BelowInitialCapitalProbability float64
	Percentiles                    map[string]map[float64]decimal.Decimal
}

MCSimulationResult holds the outcome of a Monte Carlo simulation.

type MCStats added in v0.0.7

type MCStats struct {
	Mean   decimal.Decimal
	Median decimal.Decimal
	StdDev decimal.Decimal
	Min    decimal.Decimal
	Max    decimal.Decimal
}

MCStats holds aggregate statistics across simulations.

type MaxConsecutiveAnalyzer added in v0.0.3

type MaxConsecutiveAnalyzer struct{}

func (*MaxConsecutiveAnalyzer) Analyze added in v0.0.3

func (mca *MaxConsecutiveAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*MaxConsecutiveAnalyzer) Name added in v0.0.3

func (mca *MaxConsecutiveAnalyzer) Name() string

type MonteCarloSimulator added in v0.0.7

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

MonteCarloSimulator runs Monte Carlo simulations on backtest results.

func NewMonteCarloSimulator added in v0.0.7

func NewMonteCarloSimulator(config MCSimulationConfig) *MonteCarloSimulator

NewMonteCarloSimulator creates a new simulator with the given config.

func (*MonteCarloSimulator) Run added in v0.0.7

Run executes the Monte Carlo simulation on the provided backtest result.

type MultiAssetBacktester added in v0.0.3

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

MultiAssetBacktester runs backtests across multiple assets simultaneously

func NewMultiAssetBacktester added in v0.0.3

func NewMultiAssetBacktester(strategy trading.Strategy) *MultiAssetBacktester

func (*MultiAssetBacktester) AddAsset added in v0.0.3

func (m *MultiAssetBacktester) AddAsset(symbol string, s *series.TimeSeries)

func (*MultiAssetBacktester) Run added in v0.0.3

Run performs a backtest across all assets. This is a simplified version where each asset is tested independently for now. A true portfolio backtester would handle rebalancing and correlation.

type ObjectiveFunction added in v0.0.7

type ObjectiveFunction func(result BacktestResult) float64

ObjectiveFunction scores a backtest result. Higher is better.

type OptimizationConfig added in v0.0.7

type OptimizationConfig struct {
	Method          OptimizationMethod
	ParameterSpaces []ParameterSpace
	ObjectiveFunc   ObjectiveFunction
	RandomSamples   int // Total random samples for random search
	MaxWorkers      int // Parallelism; 0 means sequential
	ProgressFunc    func(completed, total int)
	Seed            int64 // For reproducible random search; 0 means time-based
}

OptimizationConfig configures the optimization run.

func (OptimizationConfig) Validate added in v0.0.7

func (c OptimizationConfig) Validate() error

Validate checks that the optimization configuration is valid.

type OptimizationFunc added in v0.0.6

type OptimizationFunc func(ts *series.TimeSeries) (StrategyFactory, BacktestConfig)

OptimizationFunc is a user-provided function that optimizes strategy configuration on the given in-sample time series and returns a factory that can build a fresh strategy for any sub-series.

type OptimizationMethod added in v0.0.7

type OptimizationMethod string

OptimizationMethod defines the parameter search strategy.

const (
	// OptMethodGridSearch exhaustively searches the discretized parameter space.
	OptMethodGridSearch OptimizationMethod = "grid_search"
	// OptMethodRandomSearch randomly samples within parameter bounds.
	OptMethodRandomSearch OptimizationMethod = "random_search"
)

type OptimizationResult added in v0.0.7

type OptimizationResult struct {
	BestConfig map[string]float64
	BestScore  float64
	AllResults []ParameterSetResult
	Duration   time.Duration
	TotalRuns  int
}

OptimizationResult holds the outcome of a parameter optimization run.

type Optimizer added in v0.0.7

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

Optimizer runs parameter optimization over a backtest strategy.

func NewOptimizer added in v0.0.7

func NewOptimizer(config OptimizationConfig) (*Optimizer, error)

NewOptimizer creates a new optimizer with the given configuration.

func (*Optimizer) Optimize added in v0.0.7

func (o *Optimizer) Optimize(
	ts *series.TimeSeries,
	strategyFactory func(params map[string]float64) trading.Strategy,
	btConfig BacktestConfig,
) (*OptimizationResult, error)

Optimize searches for the best strategy parameters on the given time series.

type ParameterSetResult added in v0.0.7

type ParameterSetResult struct {
	Params map[string]float64
	Score  float64
	Result BacktestResult
}

ParameterSetResult holds the score for a single parameter combination.

type ParameterSpace added in v0.0.7

type ParameterSpace struct {
	Name string
	Min  float64
	Max  float64
	Step float64 // For grid search; must be > 0
}

ParameterSpace defines the range and step for a single parameter.

func (ParameterSpace) Validate added in v0.0.7

func (ps ParameterSpace) Validate() error

Validate checks that the parameter space is valid.

type PartialFillModel added in v0.0.7

type PartialFillModel func(order *trading.Order, candle *series.Candle) decimal.Decimal

PartialFillModel determines how much of an order fills. Returns the filled amount (must be <= order.Amount).

type PortfolioResult added in v0.0.3

type PortfolioResult struct {
	AssetResults map[string]BacktestResult
	TotalEquity  decimal.Decimal
}

PortfolioResult combines results from multiple assets

type PortfolioSimulator added in v0.0.3

type PortfolioSimulator struct {
	InitialCapital decimal.Decimal
	Fees           decimal.Decimal
	Slippage       decimal.Decimal
}

PortfolioSimulator simulates a portfolio based on signals

func NewPortfolioSimulator added in v0.0.3

func NewPortfolioSimulator(initialCapital, fees, slippage float64) *PortfolioSimulator

NewPortfolioSimulator returns a new PortfolioSimulator

func (*PortfolioSimulator) SimulateLongOnly added in v0.0.3

func (ps *PortfolioSimulator) SimulateLongOnly(s *series.TimeSeries, signals []int) BacktestResult

SimulateLongOnly simulates a long-only portfolio based on buy/sell signals

type Position

type Position struct {
	EntryTime  int
	EntryPrice decimal.Decimal
	Direction  string
	Quantity   decimal.Decimal
	StopLoss   decimal.Decimal
	TakeProfit decimal.Decimal
}

type ProfitFactorAnalyzer added in v0.0.3

type ProfitFactorAnalyzer struct{}

func (*ProfitFactorAnalyzer) Analyze added in v0.0.3

func (pfa *ProfitFactorAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*ProfitFactorAnalyzer) Name added in v0.0.3

func (pfa *ProfitFactorAnalyzer) Name() string

type RExpectancyAnalyzer added in v0.0.3

type RExpectancyAnalyzer struct{}

func (*RExpectancyAnalyzer) Analyze added in v0.0.3

func (rea *RExpectancyAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*RExpectancyAnalyzer) Name added in v0.0.3

func (rea *RExpectancyAnalyzer) Name() string

type SharpeRatioAnalyzer added in v0.0.3

type SharpeRatioAnalyzer struct {
	RiskFreeRate decimal.Decimal
}

SharpeRatioAnalyzer calculates the Sharpe Ratio.

func (*SharpeRatioAnalyzer) Analyze added in v0.0.3

func (a *SharpeRatioAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*SharpeRatioAnalyzer) Name added in v0.0.3

func (a *SharpeRatioAnalyzer) Name() string

type SimulatedBroker added in v0.0.7

type SimulatedBroker struct {
	Symbol           string
	InitialCapital   decimal.Decimal
	Equity           decimal.Decimal
	CommissionModel  CommissionModel
	SlippageModel    SlippageModel
	FillPriceSource  FillPriceSource
	PartialFillModel PartialFillModel
	AllowLong        bool
	AllowShort       bool
	// contains filtered or unexported fields
}

SimulatedBroker simulates order execution for a single asset.

func NewSimulatedBroker added in v0.0.7

func NewSimulatedBroker(symbol string, initialCapital decimal.Decimal) *SimulatedBroker

NewSimulatedBroker creates a new simulated broker.

func (*SimulatedBroker) BacktestResult added in v0.0.7

func (b *SimulatedBroker) BacktestResult() BacktestResult

BacktestResult converts broker state to a BacktestResult.

func (*SimulatedBroker) ProcessBar added in v0.0.7

func (b *SimulatedBroker) ProcessBar(index int, candle *series.Candle)

ProcessBar processes all pending orders against the given candle and records the pre-trade equity.

func (*SimulatedBroker) ProcessStrategySignal added in v0.0.7

func (b *SimulatedBroker) ProcessStrategySignal(shouldEnter, shouldExit bool, index int, candle *series.Candle)

ProcessStrategySignal handles immediate market orders from strategy signals. Market orders fill at the configured FillPriceSource within the current bar. When both AllowLong and AllowShort are true, short entries take priority because the Strategy interface does not specify direction.

func (*SimulatedBroker) SubmitOrder added in v0.0.7

func (b *SimulatedBroker) SubmitOrder(order *trading.Order)

SubmitOrder submits an order to the broker. It becomes pending and is evaluated against subsequent bars.

type SlippageModel added in v0.0.7

type SlippageModel func(order *trading.Order, candle *series.Candle) decimal.Decimal

SlippageModel computes the slippage for an order fill. Positive slippage worsens the fill (higher for buy, lower for sell).

func FixedSlippage added in v0.0.7

func FixedSlippage(amount decimal.Decimal) SlippageModel

FixedSlippage returns a fixed slippage amount.

type StrategyFactory added in v0.0.6

type StrategyFactory func(ts *series.TimeSeries) trading.Strategy

StrategyFactory creates a fresh strategy instance bound to the given series. Used by WalkForwardAnalyzer to prevent indicator state leakage between in-sample and out-of-sample runs.

type SystemQualityNumberAnalyzer added in v0.0.3

type SystemQualityNumberAnalyzer struct{}

func (*SystemQualityNumberAnalyzer) Analyze added in v0.0.3

func (sqna *SystemQualityNumberAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*SystemQualityNumberAnalyzer) Name added in v0.0.3

func (sqna *SystemQualityNumberAnalyzer) Name() string

type Trade

type Trade struct {
	EntryTime     int
	EntryPrice    decimal.Decimal
	ExitTime      int
	ExitPrice     decimal.Decimal
	Direction     string
	Quantity      decimal.Decimal
	Profit        decimal.Decimal
	ProfitPercent decimal.Decimal
	Duration      int
}

type TradeStats added in v0.0.3

type TradeStats struct {
	TotalTrades    int
	WinningTrades  int
	LosingTrades   int
	WinRate        decimal.Decimal
	ProfitFactor   decimal.Decimal
	Expectancy     decimal.Decimal
	AverageWin     decimal.Decimal
	AverageLoss    decimal.Decimal
	TotalNetProfit decimal.Decimal
}

TradeStats represents basic trade statistics.

type TradeStatsAnalyzer added in v0.0.3

type TradeStatsAnalyzer struct{}

TradeStatsAnalyzer analyzes trade-level performance.

func (*TradeStatsAnalyzer) Analyze added in v0.0.3

func (a *TradeStatsAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*TradeStatsAnalyzer) Name added in v0.0.3

func (a *TradeStatsAnalyzer) Name() string

type WFAAggregateMetrics added in v0.0.6

type WFAAggregateMetrics struct {
	TotalWindows             int
	AverageInSampleSharpe    decimal.Decimal
	AverageOutOfSampleSharpe decimal.Decimal
	DegradationRate          decimal.Decimal // (IS - OOS) / |IS|, lower is better
	WinningWindowsPercent    decimal.Decimal // % of OOS windows with positive net profit
	AverageInSampleProfit    decimal.Decimal
	AverageOutOfSampleProfit decimal.Decimal
}

WFAAggregateMetrics summarizes performance across all WFA windows.

type WFAConfig added in v0.0.6

type WFAConfig struct {
	InSampleWindowSize    int // Number of candles for in-sample (training)
	OutOfSampleWindowSize int // Number of candles for out-of-sample (testing)
	StepSize              int // How many candles to roll forward each window
}

WFAConfig configures the walk-forward analysis parameters.

func (WFAConfig) Validate added in v0.0.6

func (c WFAConfig) Validate() error

Validate checks that the WFA configuration is sensible.

type WFAResult added in v0.0.6

type WFAResult struct {
	Windows          []WFWindowResult
	AggregateMetrics WFAAggregateMetrics
}

WFAResult is the complete output of a walk-forward analysis.

type WFWindowResult added in v0.0.6

type WFWindowResult struct {
	WindowIndex       int
	InSampleStart     int
	InSampleEnd       int
	OutOfSampleStart  int
	OutOfSampleEnd    int
	InSampleResult    BacktestResult
	OutOfSampleResult BacktestResult
}

WFWindowResult holds the backtest results for a single WFA window.

type WalkForwardAnalyzer added in v0.0.6

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

WalkForwardAnalyzer runs walk-forward analysis on a time series.

func NewWalkForwardAnalyzer added in v0.0.6

func NewWalkForwardAnalyzer(config WFAConfig) (*WalkForwardAnalyzer, error)

NewWalkForwardAnalyzer creates a new WFA analyzer.

func (*WalkForwardAnalyzer) Run added in v0.0.6

func (wfa *WalkForwardAnalyzer) Run(
	ts *series.TimeSeries,
	optimize OptimizationFunc,
) (*WFAResult, error)

Run executes walk-forward analysis on the provided time series.

type WinLossRatioAnalyzer added in v0.0.3

type WinLossRatioAnalyzer struct{}

func (*WinLossRatioAnalyzer) Analyze added in v0.0.3

func (wlra *WinLossRatioAnalyzer) Analyze(trades []metrics.Trade, equityCurve []metrics.EquityPoint) interface{}

func (*WinLossRatioAnalyzer) Name added in v0.0.3

func (wlra *WinLossRatioAnalyzer) Name() string

Jump to

Keyboard shortcuts

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