Skip to main content

qs_backtest/
lib.rs

1//! `qs-backtest` — Backtesting engine for the quant-system workspace.
2//!
3//! This crate provides tools for replaying historical market data through the
4//! [`qs_core::TradeEngine`] to evaluate trading strategies and predefined
5//! signal sets.
6//!
7//! # Two modes of operation
8//!
9//! 1. **Strategy-driven** — implement the [`Strategy`] trait; the runner feeds
10//!    market data tick-by-tick and your strategy decides when to act.
11//! 2. **Signal replay** - provide strict timestamped [`RawSignal`] values; the runner injects them at the correct moments while replaying price data.
12//!
13//! # Key types
14//!
15//! | Type | Purpose |
16//! |------|---------|
17//! | [`BacktestRunner`] | Orchestrates the backtest loop (both modes) |
18//! | [`BacktestExecutor`] | Tracks simulated fills, positions, and P&L |
19//! | [`BacktestResult`] | Final report with P&L, drawdown, and execution artifacts |
20//! | [`DataFeed`] | Trait for sequential market event sources |
21//! | [`Strategy`] | Trait for strategy-driven backtests |
22
23pub mod artifacts;
24pub mod currency;
25pub mod data_feed;
26pub mod economic_support;
27pub mod evaluation;
28pub mod executor;
29pub mod future_executor;
30pub mod ledger;
31pub mod mtm;
32pub mod portfolio;
33pub mod profile;
34pub mod report;
35pub mod runner;
36pub mod sizing;
37pub mod strategy;
38
39// ── Convenience re-exports ──────────────────────────────────────────────────
40
41pub use artifacts::{
42    CloseEvent, CompletedPosition, CostEvent, ExecutionMetadata, FutureBacktestArtifacts,
43    InstrumentSizingArtifact, MarketEntrySizingAudit, MarketEntrySizingBasis, NetPnlOutcome,
44    OpenPositionSnapshot, PendingOrderLifecycleEvent, PendingOrderLifecycleState,
45    PendingOrderSnapshot, RecordedFill, ReplayInstrumentArtifact, ReplayInstrumentManifest,
46    RiskBasisStatus, RiskTranche,
47};
48pub use qs_core::{
49    CommissionModel, CostBasis, CostCharge, CostKind, CostValidationError, InstrumentCosts,
50    SwapAmount, SwapSchedule,
51};
52
53pub use currency::{
54    ConversionError, ConversionLeg, ConversionLegAudit, ConversionPriceSide, ConversionQuoteBook,
55    ConversionResult, ConversionRoute, FxPair, FxPairDirection, QuoteValidationError,
56    RunCurrencyPlan, RunCurrencyPlanError, resolve_conversion_route, resolve_fx_pair,
57};
58pub use data_feed::BarExecutionPrices;
59pub use data_feed::{DataFeed, MarketEvent, VecFeed};
60pub use economic_support::{
61    EconomicSupportError, LEGACY_ECONOMIC_GUARD_ID, LegacyEconomicModel, SupportedLegacyEconomics,
62    guarded_instrument_spec, resolve_legacy_economics,
63};
64pub use evaluation::{
65    BootstrapConfig, BreakdownDimension, EvaluationContext, EvaluationOptions, EvaluationReport,
66    EvaluationSection, GroupFilter, PositionFilter, PositionSide,
67};
68pub use executor::BacktestExecutor;
69pub use future_executor::FutureExecutor;
70pub use mtm::{
71    DEFAULT_MTM_MAX_POINTS, MAX_MTM_MAX_POINTS, MIN_MTM_MAX_POINTS, MtmCurveCollector,
72    MtmOutputPolicy, MtmOutputPolicyError, MtmOutputSummary,
73};
74pub use profile::{
75    EntryGeometryPolicy, EntryLevelResolution, EntryProfileRoutingError, EntryResolutionContext,
76    GeneratedTargetResolution, ManagementProfile, PositionRef, PositionResolver,
77    PreparedEntryProfiles, PriceGridSource, ProfileApplicationError, ProfileError, ProfileRegistry,
78    ProfileRegistryError, ProfileValidationError, RawSignal, ResolvedEntry, RuleConfigDef,
79    StoplossMode, TargetResolution, TargetResolutionSource, TargetSelection, TargetSource,
80    allocate_target_units, resolve_signal, resolve_unprofiled_entry,
81};
82pub use report::{
83    BacktestResult, CloseReasonStats, DurationStats, MonthlyReturn, PositionSummary, RiskMetrics,
84    StreakStats, SubsetStats, TradeResult,
85};
86pub use runner::{
87    BacktestRunner, FutureQuoteConfig, ReplayCancelled, ReplayProgress, StreamingReplayError,
88};
89pub use strategy::{
90    AnalysisBoundary, AnalysisBoundaryOutput, AnalysisContext, AnalysisError, AnalysisPipeline,
91    AnnotationError, AnnotationId, AnnotationLimits, AnnotationTimeline, AnnotationUse,
92    BacktestConfiguredStrategyAdapter, BarSeriesSpec, BarWindow, CalendarAdmissionLimits,
93    CalendarBar, CalendarError, CalendarFeatureKind, CalendarFeatureProjector, CalendarInputSpec,
94    CalendarTimeBasis, ClosedBar, ConfiguredCalendarFeatureProjector, ConfiguredCalendarInput,
95    ConfiguredEntryProfileError, ConfiguredHistoricalBindings, ConfiguredNamedInputBinding,
96    ConfiguredSourceBinding, ConfiguredStrategyAdapterBuildError, ConfiguredStrategyAdapterError,
97    ConfiguredStrategyAdapterPreflightError, ConfiguredTradingCalendar, ConfirmedPivotAnalyzer,
98    ConfirmedSwingFactKind, ConfirmedSwingFactProjector, DEFAULT_CALENDAR_SESSION_ID,
99    FixedUtcSessionError, FixedUtcSessionProjector, HistoricalAnalyzer,
100    HistoricalNamedInputProjector, HistoricalObservationView, HistoricalSeriesView,
101    HistoricalStrategy, HistoricalVolumeProjection, IanaTradingCalendar, JournalKind,
102    LocalMarketIntervalSpec, MAX_ANALYZERS, MAX_ANNOTATION_ID_BYTES, MAX_ANNOTATION_NOTE_BYTES,
103    MAX_ANNOTATIONS, MAX_CHART_REF_BYTES, MAX_DECISION_LATENCY_MS, MAX_DECISION_RECORDS,
104    MAX_EXPERIMENT_LABEL_BYTES, MAX_INSTRUMENT_BYTES, MAX_JOURNAL_PER_CALLBACK,
105    MAX_JOURNAL_REASON_BYTES, MAX_JOURNAL_RECORDS, MAX_JOURNAL_VALUE_KEY_BYTES, MAX_JOURNAL_VALUES,
106    MAX_OBSERVATION_SOURCE_SERIES, MAX_OBSERVATIONS_PER_BOUNDARY, MAX_PIVOT_SIDE_BARS,
107    MAX_REASON_BYTES, MAX_RETAINED_BARS, MAX_RETAINED_OBSERVATIONS, MAX_SERIES_ID_BYTES,
108    MAX_SESSION_WINDOWS, MAX_SIGNALS_PER_CALLBACK, MAX_STRATEGY_ID_BYTES,
109    MAX_STRATEGY_REVISION_BYTES, MAX_STRATEGY_TITLE_BYTES, MAX_TRADE_ID_BYTES, MAX_WARMUP_BARS,
110    MAX_ZONE_ID_BYTES, MarketScheduleSpec, MissingIntervalPolicy, MomentumState,
111    MultiTimeframeSeries, NamedInputProjectionContext, NamedInputProjectionError, NamedSessionSpec,
112    ObservationOrigin, ObservationSelection, ObservationStore, ObservationStoreLimits,
113    ObservationWindow, OpeningRange, PivotConfig, PriceBasis, PriceZone, ProjectedNamedInput,
114    RejectionPattern, ResolvedSession, ResolvedSessionOccurrence, ResolvedTradingDay, SeriesError,
115    SeriesGeometry, SeriesGeometryError, SeriesId, SeriesRequirement, SeriesViewError,
116    SeriesWarmupState, SessionOccurrenceId, SessionScheduleSpec, SessionSpanSpec,
117    SourceBarFactKind, SourceBarFactProjector, Strategy, StrategyAnnotation,
118    StrategyBacktestResult, StrategyComparisonMetrics, StrategyComparisonSnapshot,
119    StrategyConfigError, StrategyContext, StrategyDecisionDraft, StrategyDecisionKind,
120    StrategyDecisionOutput, StrategyDecisionRecord, StrategyDecisionRecorder,
121    StrategyDecisionRetention, StrategyDescriptor, StrategyDomainError, StrategyEvent,
122    StrategyExperimentComparison, StrategyExperimentError, StrategyFeedback, StrategyFeedbackEvent,
123    StrategyId, StrategyJournalDraft, StrategyJournalError, StrategyJournalOutput,
124    StrategyJournalRecord, StrategyJournalRecorder, StrategyJournalRetention, StrategyObservation,
125    StrategyObservationDraft, StrategyObservationValue, StrategyOutput, StrategyReplayError,
126    StrategyReplayInputError, StrategyRequirements, StrategyResearchLimits, StrategyResearchOutput,
127    StrategyRetentionLimits, StrategyRuntimeError, SwingKind, SwingPoint, Timeframe,
128    TradingCalendarSpec, WarmupRequirement, WeeklyMarketIntervalSpec, ZoneId, ZoneSide, ZoneSource,
129    ZoneState,
130};
131pub use strategy::{
132    ConfiguredInstance, DirectPortfolioInstance, INSTANCE_POSITION_TAG, MAX_PORTFOLIO_INSTANCES,
133    MixedPortfolioBacktestResult, MixedPortfolioReplayError, PortfolioBacktestResult,
134    PortfolioInstanceOutput, PortfolioReplayError, SupervisorEvent, SupervisorHaltAction,
135    SupervisorOutput,
136};