#[non_exhaustive]pub struct BacktestConfig {Show 18 fields
pub initial_capital: f64,
pub commission: f64,
pub commission_pct: f64,
pub slippage_pct: f64,
pub position_size_pct: f64,
pub max_positions: Option<usize>,
pub allow_short: bool,
pub min_signal_strength: f64,
pub stop_loss_pct: Option<f64>,
pub take_profit_pct: Option<f64>,
pub close_at_end: bool,
pub risk_free_rate: f64,
pub trailing_stop_pct: Option<f64>,
pub reinvest_dividends: bool,
pub bars_per_year: f64,
pub spread_pct: f64,
pub transaction_tax_pct: f64,
pub commission_fn: Option<CommissionFn>,
}Expand description
Configuration for backtest execution.
Use BacktestConfig::builder() to construct with the builder pattern.
§Example
use finance_query::backtesting::BacktestConfig;
let config = BacktestConfig::builder()
.initial_capital(50_000.0)
.commission_pct(0.001)
.slippage_pct(0.0005)
.allow_short(true)
.stop_loss_pct(0.05)
.take_profit_pct(0.10)
.build()
.unwrap();Fields (Non-exhaustive)§
This struct is marked as non-exhaustive
Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.initial_capital: f64Initial portfolio capital in base currency
commission: f64Commission per trade (flat fee)
commission_pct: f64Commission as percentage of trade value (0.0 - 1.0)
slippage_pct: f64Slippage as percentage of price (0.0 - 1.0)
position_size_pct: f64Position sizing: fraction of equity per trade (0.0 - 1.0)
max_positions: Option<usize>Maximum number of concurrent positions (None = unlimited)
allow_short: boolAllow short selling
min_signal_strength: f64Require signal strength threshold to trigger trades (0.0 - 1.0)
stop_loss_pct: Option<f64>Stop-loss percentage (0.0 - 1.0). Auto-exit if loss exceeds this.
take_profit_pct: Option<f64>Take-profit percentage (0.0 - 1.0). Auto-exit if profit exceeds this.
close_at_end: boolClose any open position at end of backtest
risk_free_rate: f64Annual risk-free rate for Sharpe/Sortino/Calmar ratio calculations (0.0 - 1.0).
Defaults to 0.0. Use the current T-bill rate for accurate ratios
(e.g. 0.05 for 5% annual). Converted to a per-period rate internally.
trailing_stop_pct: Option<f64>Trailing stop percentage (0.0 - 1.0).
For long positions: tracks the peak (highest) price since entry and triggers an exit when the price drops this fraction below the peak.
For short positions: tracks the trough (lowest) price since entry and triggers an exit when the price rises this fraction above the trough.
Checked before strategy signals each bar, same as stop_loss_pct and
take_profit_pct. Exit slippage is applied.
reinvest_dividends: boolWhen true, dividend income received during a holding period is
notionally reinvested: the income is included in the trade’s P&L as
if additional shares were purchased at the dividend ex-date close price.
When false (default), dividend income is simply added to P&L at close.
In both cases the dividend amount is recorded on the Trade for reporting.
bars_per_year: f64Number of bars per calendar year, used for annualising returns and ratios.
Defaults to 252.0 (US equity daily bars). Set to 52.0 for weekly
bars, 12.0 for monthly, or 252.0 * 6.5 (≈ 1638) for hourly bars.
This affects annualised return, Sharpe, Sortino, Calmar, and all
benchmark metrics.
spread_pct: f64Symmetric bid-ask spread as a fraction of price (0.0 – 1.0).
On each fill, half the spread widens the entry price adversely and
half widens the exit price adversely (independent of slippage_pct,
which models directional market impact). For example, a 0.0002 spread
(2 bps) costs 1 bp on entry and 1 bp on exit.
Defaults to 0.0.
transaction_tax_pct: f64Transaction tax as a fraction of trade value, applied on buy orders only (0.0 – 1.0).
Models jurisdiction-specific purchase taxes such as the UK Stamp Duty Reserve Tax (0.5 %). Applied on:
- Long entries (buying shares)
- Short exits (covering the short — i.e. buying to close)
Defaults to 0.0.
commission_fn: Option<CommissionFn>Custom commission function f(size, price) -> commission.
When Some, replaces the flat commission + percentage
commission_pct fields. The function receives the fill quantity
(size) and the fill price (price) and must return the total
commission amount in the same currency as initial_capital.
Not serialized — reconstruct after deserialization if needed.
Implementations§
Source§impl BacktestConfig
impl BacktestConfig
Sourcepub fn zero_cost() -> Self
pub fn zero_cost() -> Self
Create a zero-cost configuration with no commission, slippage, spread, or tax.
Useful for unit tests and frictionless benchmark comparisons.
All other fields use the same defaults as BacktestConfig::default().
Sourcepub fn builder() -> BacktestConfigBuilder
pub fn builder() -> BacktestConfigBuilder
Create a new builder
Sourcepub fn calculate_commission(&self, size: f64, price: f64) -> f64
pub fn calculate_commission(&self, size: f64, price: f64) -> f64
Calculate commission for a fill.
When commission_fn is set it takes precedence over the flat
commission + percentage commission_pct fields.
Sourcepub fn apply_entry_slippage(&self, price: f64, is_long: bool) -> f64
pub fn apply_entry_slippage(&self, price: f64, is_long: bool) -> f64
Apply slippage to a price (for entry).
Sourcepub fn apply_exit_slippage(&self, price: f64, is_long: bool) -> f64
pub fn apply_exit_slippage(&self, price: f64, is_long: bool) -> f64
Apply slippage to a price (for exit).
Sourcepub fn apply_entry_spread(&self, price: f64, is_long: bool) -> f64
pub fn apply_entry_spread(&self, price: f64, is_long: bool) -> f64
Apply the bid-ask spread to an entry fill price (half-spread adverse).
Long entries pay the ask (price rises by spread_pct / 2);
short entries receive the bid (price falls by spread_pct / 2).
Sourcepub fn apply_exit_spread(&self, price: f64, is_long: bool) -> f64
pub fn apply_exit_spread(&self, price: f64, is_long: bool) -> f64
Apply the bid-ask spread to an exit fill price (half-spread adverse).
Long exits receive the bid (price falls by spread_pct / 2);
short exits pay the ask (price rises by spread_pct / 2).
Sourcepub fn calculate_transaction_tax(&self, trade_value: f64, is_buy: bool) -> f64
pub fn calculate_transaction_tax(&self, trade_value: f64, is_buy: bool) -> f64
Calculate the transaction tax on a fill.
Tax applies only to buy orders (is_buy = true):
- Long entries (opening a long position)
- Short exits (covering a short position)
Returns 0.0 for all sell orders.
Sourcepub fn calculate_position_size(&self, available_capital: f64, price: f64) -> f64
pub fn calculate_position_size(&self, available_capital: f64, price: f64) -> f64
Calculate position size based on available capital.
price must be the fully-adjusted entry price (after slippage and
spread) so that subsequent fill guards (entry_value + costs > cash)
do not over-allocate capital.
When commission_fn is set the commission component cannot be
analytically solved for, so only spread and transaction-tax fractions
are deducted from the denominator; the fill-rejection guard catches any
remaining over-allocation.
Trait Implementations§
Source§impl Clone for BacktestConfig
impl Clone for BacktestConfig
Source§fn clone(&self) -> BacktestConfig
fn clone(&self) -> BacktestConfig
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for BacktestConfig
impl Debug for BacktestConfig
Source§impl Default for BacktestConfig
impl Default for BacktestConfig
Source§impl<'de> Deserialize<'de> for BacktestConfig
impl<'de> Deserialize<'de> for BacktestConfig
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Auto Trait Implementations§
impl Freeze for BacktestConfig
impl !RefUnwindSafe for BacktestConfig
impl Send for BacktestConfig
impl Sync for BacktestConfig
impl Unpin for BacktestConfig
impl UnsafeUnpin for BacktestConfig
impl !UnwindSafe for BacktestConfig
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more