Skip to main content

BacktestConfig

Struct BacktestConfig 

Source
#[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
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§initial_capital: f64

Initial portfolio capital in base currency

§commission: f64

Commission per trade (flat fee)

§commission_pct: f64

Commission as percentage of trade value (0.0 - 1.0)

§slippage_pct: f64

Slippage as percentage of price (0.0 - 1.0)

§position_size_pct: f64

Position sizing: fraction of equity per trade (0.0 - 1.0)

§max_positions: Option<usize>

Maximum number of concurrent positions (None = unlimited)

§allow_short: bool

Allow short selling

§min_signal_strength: f64

Require 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: bool

Close any open position at end of backtest

§risk_free_rate: f64

Annual 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: bool

When 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: f64

Number 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: f64

Symmetric 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: f64

Transaction 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

Source

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().

Source

pub fn builder() -> BacktestConfigBuilder

Create a new builder

Source

pub fn validate(&self) -> Result<()>

Validate configuration parameters

Source

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.

Source

pub fn apply_entry_slippage(&self, price: f64, is_long: bool) -> f64

Apply slippage to a price (for entry).

Source

pub fn apply_exit_slippage(&self, price: f64, is_long: bool) -> f64

Apply slippage to a price (for exit).

Source

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).

Source

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).

Source

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.

Source

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

Source§

fn clone(&self) -> BacktestConfig

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BacktestConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for BacktestConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for BacktestConfig

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for BacktestConfig

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Key for T
where T: Clone,

Source§

fn align() -> usize

The alignment necessary for the key. Must return a power of two.
Source§

fn size(&self) -> usize

The size of the key in bytes.
Source§

unsafe fn init(&self, ptr: *mut u8)

Initialize the key in the given memory location. Read more
Source§

unsafe fn get<'a>(ptr: *const u8) -> &'a T

Get a reference to the key from the given memory location. Read more
Source§

unsafe fn drop_in_place(ptr: *mut u8)

Drop the key in place. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> PlanCallbackArgs for T

Source§

impl<T> PlanCallbackOut for T