finance_query/backtesting/mod.rs
1//! Backtesting engine for trading strategy simulation.
2//!
3//! This module provides a complete backtesting framework with:
4//! - Expression-based strategy builder for custom entry/exit conditions
5//! - Pre-built strategies (SMA, RSI, MACD, Bollinger, SuperTrend, Donchian)
6//! - Full technical indicator coverage (40+ indicators)
7//! - Position tracking with long/short support
8//! - Stop-loss, take-profit, and trailing stop management
9//! - Comprehensive performance metrics
10//!
11//! # Quick Start
12//!
13//! ```no_run
14//! use finance_query::{Ticker, Interval, TimeRange};
15//! use finance_query::backtesting::{SmaCrossover, BacktestConfig};
16//!
17//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
18//! let ticker = Ticker::new("AAPL").await?;
19//! let result = ticker.backtest(
20//! SmaCrossover::new(10, 20),
21//! Interval::OneDay,
22//! TimeRange::OneYear,
23//! None,
24//! ).await?;
25//!
26//! println!("Return: {:.2}%", result.metrics.total_return_pct);
27//! println!("Sharpe: {:.2}", result.metrics.sharpe_ratio);
28//! println!("Max Drawdown: {:.2}%", result.metrics.max_drawdown_pct * 100.0);
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! # Custom Strategies with StrategyBuilder
34//!
35//! Build custom strategies using the fluent builder API:
36//!
37//! ```ignore
38//! use finance_query::backtesting::StrategyBuilder;
39//! use finance_query::backtesting::refs::*;
40//! use finance_query::backtesting::condition::*;
41//!
42//! let strategy = StrategyBuilder::new("RSI Mean Reversion")
43//! .entry(
44//! rsi(14).crosses_below(30.0)
45//! .and(price().above_ref(sma(200)))
46//! )
47//! .exit(
48//! rsi(14).crosses_above(70.0)
49//! .or(stop_loss(0.05))
50//! )
51//! .build();
52//! ```
53//!
54//! # Configuration
55//!
56//! ```no_run
57//! use finance_query::backtesting::BacktestConfig;
58//!
59//! let config = BacktestConfig::builder()
60//! .initial_capital(50_000.0)
61//! .commission_pct(0.001) // 0.1% per trade
62//! .slippage_pct(0.0005) // 0.05% slippage
63//! .stop_loss_pct(0.05) // 5% stop-loss
64//! .take_profit_pct(0.15) // 15% take-profit
65//! .allow_short(true)
66//! .build()
67//! .unwrap();
68//! ```
69//!
70//! # Pre-built Strategies
71//!
72//! | Strategy | Parameters | Description |
73//! |----------|------------|-------------|
74//! | [`SmaCrossover`] | fast, slow periods | Dual SMA crossover |
75//! | [`RsiReversal`] | period, oversold, overbought | Mean reversion on RSI |
76//! | [`MacdSignal`] | fast, slow, signal periods | MACD line crossover |
77//! | [`BollingerMeanReversion`] | period, std_dev | Buy at lower band |
78//! | [`SuperTrendFollow`] | period, multiplier | Trend following |
79//! | [`DonchianBreakout`] | period | Channel breakout |
80//!
81//! # Available Indicators
82//!
83//! The strategy builder supports all indicators via [`refs`]:
84//!
85//! - **Moving Averages**: `sma`, `ema`, `wma`, `dema`, `tema`, `hma`, `vwma`, `alma`, `mcginley`
86//! - **Oscillators**: `rsi`, `stochastic`, `stochastic_rsi`, `cci`, `williams_r`, `cmo`, `awesome_oscillator`
87//! - **Trend**: `macd`, `adx`, `aroon`, `supertrend`, `ichimoku`, `parabolic_sar`
88//! - **Volatility**: `atr`, `bollinger`, `keltner`, `donchian`, `choppiness_index`
89//! - **Volume**: `obv`, `vwap`, `mfi`, `cmf`, `chaikin_oscillator`, `accumulation_distribution`, `balance_of_power`
90//!
91//! # Available Conditions
92//!
93//! Build conditions via [`condition`]:
94//!
95//! - **Comparisons**: `above()`, `below()`, `crosses_above()`, `crosses_below()`, `between()`, `equals()`
96//! - **Composites**: `and()`, `or()`, `not()`
97//! - **Position Management**: `stop_loss()`, `take_profit()`, `trailing_stop()`, `trailing_take_profit()`
98//! - **Position State**: `has_position()`, `no_position()`, `is_long()`, `is_short()`, `in_profit()`, `in_loss()`
99
100pub mod condition;
101mod config;
102mod engine;
103mod error;
104mod position;
105pub mod refs;
106mod result;
107mod signal;
108pub mod strategy;
109
110// Re-export main types
111pub use config::{BacktestConfig, BacktestConfigBuilder};
112pub use engine::BacktestEngine;
113pub use error::{BacktestError, Result};
114pub use position::{Position, PositionSide, Trade};
115pub use result::{BacktestResult, EquityPoint, PerformanceMetrics, SignalRecord};
116pub use signal::{Signal, SignalDirection, SignalMetadata, SignalStrength};
117
118// Re-export strategy types
119pub use strategy::{Strategy, StrategyContext};
120
121// Re-export strategy builder
122pub use strategy::StrategyBuilder;
123
124// Re-export pre-built strategies
125pub use strategy::{
126 BollingerMeanReversion, DonchianBreakout, MacdSignal, RsiReversal, SmaCrossover,
127 SuperTrendFollow,
128};