Skip to main content

optionstratlib_backtest/backtesting/
mod.rs

1//! Backtesting
2//! ```mermaid
3//! classDiagram
4//! direction LR
5//!     class BacktestResult {
6//!         +GeneralPerformanceMetrics general_performance
7//!         +OptionsSpecificMetrics options_metrics
8//!         +TradeStatistics trade_statistics
9//!         +DrawdownAnalysis drawdown_analysis
10//!         +CapitalUtilization capital_utilization
11//!         +TimeSeriesData time_series
12//!         +Vec~TradeRecord~ trades
13//!         +MarketConditionMetrics? market_conditions
14//!         +VolatilityData? volatility_data
15//!         +AdvancedRiskMetrics? risk_metrics
16//!         +SimulationResult? monte_carlo_simulation
17//!         +String strategy_name
18//!         +DateTime test_period_start
19//!         +DateTime test_period_end
20//!         +Decimal initial_capital
21//!         +Decimal final_capital
22//!         +HashMap custom_metrics
23//!     }
24//!
25//!     class GeneralPerformanceMetrics {
26//!         +Decimal total_return
27//!         +Decimal annualized_return
28//!         +Positive? volatility
29//!         +Positive? downside_deviation
30//!         +Decimal? sharpe_ratio
31//!         +Decimal? sortino_ratio
32//!         +Decimal? calmar_ratio
33//!         +Decimal? win_rate
34//!         +Decimal? profit_factor
35//!         +Decimal? avg_gain
36//!         +Decimal? avg_loss
37//!         +Decimal? gain_loss_ratio
38//!     }
39//!
40//!     class OptionsSpecificMetrics {
41//!         +Decimal? return_on_margin
42//!         +Decimal? return_on_premium
43//!         +Decimal? premium_capture
44//!         +Decimal? avg_delta_exposure
45//!         +Decimal? avg_gamma_exposure
46//!         +Decimal? avg_theta_exposure
47//!         +Decimal? avg_vega_exposure
48//!         +Decimal? avg_vanna_exposure
49//!         +Decimal? avg_vomma_exposure
50//!         +Decimal? avg_veta_exposure
51//!         +Decimal? avg_charm_exposure
52//!         +Decimal? avg_color_exposure
53//!         +Decimal? calls_percentage
54//!         +Decimal? puts_percentage
55//!         +Decimal? long_percentage
56//!         +Decimal? short_percentage
57//!     }
58//!
59//!     class TradeStatistics {
60//!         +usize number_of_trades
61//!         +usize winners
62//!         +usize losers
63//!         +usize break_even
64//!         +Decimal average_trade_return
65//!         +Decimal median_trade_return
66//!         +Decimal? largest_win
67//!         +Decimal? largest_loss
68//!         +Positive average_holding_period
69//!         +Positive median_holding_period
70//!         +Positive min_holding_period
71//!         +Positive max_holding_period
72//!         +usize long_trades
73//!         +usize short_trades
74//!         +usize call_trades
75//!         +usize put_trades
76//!         +usize spread_trades
77//!     }
78//!
79//!     class DrawdownAnalysis {
80//!         +Decimal max_drawdown
81//!         +Positive max_drawdown_duration
82//!         +Positive? recovery_duration
83//!         +Positive time_to_max_drawdown
84//!         +Vec~DrawdownEvent~ drawdowns
85//!         +Decimal avg_drawdown
86//!         +Positive? avg_recovery_time
87//!         +Positive total_underwater_days
88//!         +Decimal underwater_percentage
89//!     }
90//!
91//!     class CapitalUtilization {
92//!         +Decimal max_capital_used
93//!         +Decimal avg_capital_used
94//!         +Decimal capital_efficiency
95//!         +Decimal total_margin_used
96//!         +Decimal max_margin_used
97//!         +Decimal avg_margin_used
98//!         +Decimal total_premium_paid
99//!         +Decimal total_premium_received
100//!         +Decimal net_premium
101//!         +Decimal max_position_size
102//!         +Decimal avg_position_size
103//!     }
104//!
105//!     class TimeSeriesData {
106//!         +Vec timestamps
107//!         +Vec equity_curve
108//!         +Vec drawdown_curve
109//!         +Vec margin_usage
110//!         +Vec position_count
111//!         +Vec? delta_exposure
112//!         +Vec? gamma_exposure
113//!         +Vec? theta_exposure
114//!         +Vec? vega_exposure
115//!         +Vec? vanna_exposure
116//!         +Vec? vomma_exposure
117//!         +Vec? veta_exposure
118//!         +Vec? charm_exposure
119//!         +Vec? color_exposure
120//!         +HashMap custom_series
121//!         +new(capacity)
122//!         +add_data_point()
123//!         +add_greeks()
124//!         +add_custom_metric()
125//!     }
126//!
127//!     class TradeRecord {
128//!         +Uuid id
129//!         +DateTime entry_date
130//!         +DateTime? exit_date
131//!         +Positive? duration
132//!         +Uuid? strategy
133//!         +Position position
134//!         +Decimal? exit_price
135//!         +Decimal? slippage
136//!         +Decimal? profit_loss
137//!         +Decimal? return_percentage
138//!         +Decimal? margin_required
139//!         +ExitReason? exit_reason
140//!         +String? notes
141//!         +GreeksSnapshot? entry_greeks
142//!         +GreeksSnapshot? exit_greeks
143//!     }
144//!
145//!     class MarketConditionMetrics {
146//!         +Positive bull_market_days
147//!         +Positive bear_market_days
148//!         +Positive sideways_market_days
149//!         +Positive high_volatility_days
150//!         +Positive low_volatility_days
151//!         +Decimal? avg_market_volatility
152//!     }
153//!
154//!     class VolatilityData {
155//!         +bool implied_volatility_used
156//!         +Decimal? avg_iv_traded
157//!         +Decimal? iv_percentile_traded
158//!         +Decimal? iv_rank_traded
159//!     }
160//!
161//!     class AdvancedRiskMetrics {
162//!         +Decimal? value_at_risk_95
163//!         +Decimal? value_at_risk_99
164//!         +Decimal? expected_shortfall
165//!         +Decimal? tail_ratio
166//!         +usize max_consecutive_losses
167//!         +Decimal? ulcer_index
168//!         +Decimal? pain_index
169//!     }
170//!
171//!     class SimulationResult {
172//!         +usize simulation_count
173//!         +RiskMetricsSimulation risk_metrics
174//!         +HashMap final_equity_percentiles
175//!         +Vec? sample_paths
176//!     }
177//!
178//!     class CustomMetrics {
179//!         String to Decimal mapping
180//!     }
181//!
182//!     class RollingMetrics {
183//!         +Positive window_size
184//!         +Vec timestamps
185//!         +Vec rolling_returns
186//!         +Vec rolling_volatility
187//!         +Vec rolling_sharpe
188//!         +Vec rolling_sortino
189//!         +Vec rolling_win_rate
190//!     }
191//!
192//!     class BenchmarkComparison {
193//!         +String benchmark_name
194//!         +Decimal benchmark_return
195//!         +Decimal alpha
196//!         +Decimal beta
197//!         +Decimal correlation
198//!         +Decimal tracking_error
199//!         +Decimal? information_ratio
200//!         +Decimal? up_capture
201//!         +Decimal? down_capture
202//!     }
203//!
204//!     class DrawdownEvent {
205//!         +NaiveDateTime start_date
206//!         +NaiveDateTime bottom_date
207//!         +NaiveDateTime? recovery_date
208//!         +Decimal magnitude
209//!         +Positive duration
210//!         +Positive? recovery_duration
211//!     }
212//!
213//!     class RiskMetricsSimulation {
214//!     }
215//!
216//!     class EquityPercentiles {
217//!         u8 to Decimal mapping
218//!     }
219//!
220//!     class SamplePaths {
221//!         Vec of Vec of Decimal
222//!     }
223//!
224//!     class GreeksSnapshot {
225//!     }
226//!
227//!     class Position {
228//!     }
229//!
230//!     class ExitReason {
231//!         TargetReached
232//!         StopLoss
233//!         Expiration
234//!         RollOver
235//!         ManualClose
236//!         MarginCall
237//!         Other(String)
238//!     }
239//!
240//!     class CustomSeries {
241//!         String to Vec mapping
242//!     }
243//!
244//!     class TimestampSeries {
245//!         Vec of DateTime
246//!     }
247//!
248//!     class EquityCurve {
249//!         Vec of Decimal
250//!     }
251//!
252//!     class DrawdownCurve {
253//!         Vec of Decimal
254//!     }
255//!
256//!     class MarginUsage {
257//!         Vec of Decimal
258//!     }
259//!
260//!     class PositionCount {
261//!         Vec of usize
262//!     }
263//!
264//!     class GreeksExposure {
265//!         Vectors of Delta, Gamma, Theta, Vega, Vanna, Vomma, Veta, Charm, Color
266//!     }
267//!
268//!     class WindowSize {
269//!         Positive value
270//!     }
271//!
272//!     class RollingTimestamps {
273//!         Vec of NaiveDateTime
274//!     }
275//!
276//!     class RollingReturns {
277//!         Vec of Decimal
278//!     }
279//!
280//!     class RollingVolatility {
281//!         Vec of Decimal
282//!     }
283//!
284//!     class RollingSharpe {
285//!         Vec of Decimal
286//!     }
287//!
288//!     class RollingSortino {
289//!         Vec of Decimal
290//!     }
291//!
292//!     class RollingWinRate {
293//!         Vec of Decimal
294//!     }
295//!
296//!     <<abstract>> CustomMetrics
297//!     <<abstract>> EquityPercentiles
298//!     <<abstract>> SamplePaths
299//!     <<enumeration>> ExitReason
300//!     <<abstract>> CustomSeries
301//!     <<abstract>> TimestampSeries
302//!     <<abstract>> EquityCurve
303//!     <<abstract>> DrawdownCurve
304//!     <<abstract>> MarginUsage
305//!     <<abstract>> PositionCount
306//!     <<abstract>> GreeksExposure
307//!     <<abstract>> WindowSize
308//!     <<abstract>> RollingTimestamps
309//!     <<abstract>> RollingReturns
310//!     <<abstract>> RollingVolatility
311//!     <<abstract>> RollingSharpe
312//!     <<abstract>> RollingSortino
313//!     <<abstract>> RollingWinRate
314//!
315//!     BacktestResult *-- GeneralPerformanceMetrics
316//!     BacktestResult *-- OptionsSpecificMetrics
317//!     BacktestResult *-- TradeStatistics
318//!     BacktestResult *-- DrawdownAnalysis
319//!     BacktestResult *-- CapitalUtilization
320//!     BacktestResult *-- TimeSeriesData
321//!     BacktestResult *-- TradeRecord : many
322//!     BacktestResult o-- MarketConditionMetrics : optional
323//!     BacktestResult o-- VolatilityData : optional
324//!     BacktestResult o-- AdvancedRiskMetrics : optional
325//!     BacktestResult o-- SimulationResult : monte_carlo
326//!     BacktestResult o-- CustomMetrics : key-value pairs
327//!     RollingMetrics --o BacktestResult : calculated from
328//!     BenchmarkComparison --o BacktestResult : compared to
329//!     DrawdownAnalysis *-- DrawdownEvent : many
330//!     SimulationResult *-- RiskMetricsSimulation
331//!     SimulationResult o-- EquityPercentiles : percentile map
332//!     SimulationResult o-- SamplePaths : optional
333//!     TradeRecord o-- GreeksSnapshot : entry_greeks
334//!     TradeRecord o-- GreeksSnapshot : exit_greeks
335//!     TradeRecord o-- Position : position details
336//!     TradeRecord o-- ExitReason : reason for exit
337//!     TimeSeriesData o-- CustomSeries : name-values map
338//!     TimeSeriesData o-- TimestampSeries : date points
339//!     TimeSeriesData o-- EquityCurve : values over time
340//!     TimeSeriesData o-- DrawdownCurve : values over time
341//!     TimeSeriesData o-- MarginUsage : values over time
342//!     TimeSeriesData o-- PositionCount : count over time
343//!     TimeSeriesData o-- GreeksExposure : optional
344//!     RollingMetrics o-- WindowSize : period length
345//!     RollingMetrics o-- RollingTimestamps : period dates
346//!     RollingMetrics o-- RollingReturns : values over periods
347//!     RollingMetrics o-- RollingVolatility : values over periods
348//!     RollingMetrics o-- RollingSharpe : values over periods
349//!     RollingMetrics o-- RollingSortino : values over periods
350//!     RollingMetrics o-- RollingWinRate : values over periods
351//!     Position --o TradeRecord : many
352//!     GreeksSnapshot --o TradeRecord
353//! ```
354//!
355
356/// GeneralPerformanceMetrics
357///
358/// Purpose:
359/// Stores key performance and risk metrics for any trading strategy.
360///
361/// Fields:
362/// total_return: Total return over the entire period.
363/// annualized_return: Yearly compounded return.
364/// volatility: Standard deviation of returns (optional).
365/// downside_deviation: Standard deviation of negative returns (optional).
366/// sharpe_ratio: Risk-adjusted return vs volatility (optional).
367/// sortino_ratio: Risk-adjusted return vs downside risk (optional).
368/// calmar_ratio: Annualized return over max drawdown (optional).
369/// win_rate: % of winning trades (optional).
370/// profit_factor: Gross profits / Gross losses (optional).
371/// avg_gain: Average winning trade (optional).
372/// avg_loss: Average losing trade (optional).
373/// gain_loss_ratio: Avg gain divided by avg loss (optional).
374pub mod metrics;
375
376/// Adapters between the generic simulation contracts (`PathOutcome`,
377/// `PathStatistics`) and the strategy-bound `SimulationResult` /
378/// `SimulationStatsResult` shapes. Backtesting owns the conversion so the
379/// simulation layer never has to name a strategy.
380pub mod adapters;
381
382/// Simulation orchestration for the single-leg strategies (`LongCall`,
383/// `LongPut`, `ShortCall`, `ShortPut`): the `Simulate` implementations,
384/// the shared per-path evaluator and the `SingleLegSimulation` contract
385/// that captures what differs between the four.
386pub mod stats;
387
388pub mod strategy_simulation;
389
390/// This module defines the structure that aggregates and stores all results produced during a trading backtest simulation.
391///
392/// It includes:
393/// Core performance metrics (returns, volatility, Sharpe, win rates, etc.).
394/// Options-specific metrics (return on margin, Greeks exposure).
395/// Detailed trade statistics and individual trade records.
396/// Full drawdown analysis (max drawdown, recovery times).
397/// Capital utilization data (capital usage, margin tracking).
398/// Time-series data for an equity curve, drawdowns, Greeks, and custom series.
399/// Optional metrics about market conditions (bull/bear days, volatility environment).
400/// Optional implied volatility tracking at trade times.
401/// Optional advanced risk metrics (VaR, Expected Shortfall, Ulcer Index).
402/// Optional Monte Carlo simulations for probabilistic risk and outcome analysis.
403/// General metadata: strategy name, test period start/end, initial/final capital, and space for custom metrics.
404///
405/// The BacktestResult struct is designed to fully capture all relevant information about how a strategy performed during a test, allowing deep analytics, reporting, and risk assessment.
406pub mod results;
407
408/// This module defines the core data structures needed to analyze trading performance, risk, and capital utilization for backtests or live trading systems.
409///
410/// It captures:
411/// Global trading statistics like number of trades, average returns, win/loss rates, and trade holding times.
412/// Full analysis of drawdown events, including severity, duration, and recovery tracking.
413/// Usage of capital and margin over time, including how efficiently capital is deployed.
414/// Time-series tracking for key metrics like equity curve, drawdowns, margin usage, and options Greeks exposure.
415/// Full trade-by-trade recording, storing all relevant information from entry to exit (including slippage, PnL, Greeks, exit reasons).
416/// Implied volatility data recorded during trades to analyze volatility conditions at trade times.
417///
418/// It is designed to be fully serializable (serde) for easy storage, reporting, or integration into larger analytics systems.
419pub mod types;
420
421pub use metrics::*;
422pub use results::*;
423pub use stats::SimulationStats;
424pub use strategy_simulation::Simulate;
425pub use types::*;