Backtest
The backtest subpackage groups components relating to backtesting.
This module provides a data client for backtesting.
class BacktestDataClient
Bases: DataClient
BacktestDataClient(ClientId client_id, MessageBus msgbus, Cache cache, Clock clock, config: NautilusConfig | None = None)
Provides an implementation of DataClient for backtesting.
- Parameters:
- client_id (ClientId) – The data client ID.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (Clock) – The clock for the client.
- config (NautilusConfig , optional) – The configuration for the instance.
degrade(self)
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component
will remain in a DEGRADING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
dispose(self)
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component
will remain in a DISPOSING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
fault(self)
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component
will remain in a FAULTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
classmethod fully_qualified_name(cls)
Return the fully qualified name for the components class.
- Return type: str
id
The components ID.
- Returns: ComponentId
is_connected
If the client is connected.
- Returns: bool
is_degraded
bool
Return whether the current component state is DEGRADED
.
- Return type: bool
- Type: Component.is_degraded
is_disposed
bool
Return whether the current component state is DISPOSED
.
- Return type: bool
- Type: Component.is_disposed
is_faulted
bool
Return whether the current component state is FAULTED
.
- Return type: bool
- Type: Component.is_faulted
is_initialized
bool
Return whether the component has been initialized (component.state >= INITIALIZED
).
- Return type: bool
- Type: Component.is_initialized
is_running
bool
Return whether the current component state is RUNNING
.
- Return type: bool
- Type: Component.is_running
is_stopped
bool
Return whether the current component state is STOPPED
.
- Return type: bool
- Type: Component.is_stopped
request(self, DataType data_type, UUID4 correlation_id)
reset(self)
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component
will remain in a RESETTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
resume(self)
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component
will remain in a RESUMING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
start(self)
Start the component.
While executing on_start() any exception will be logged and reraised, then the component
will remain in a STARTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
state
ComponentState
Return the components current state.
- Return type: ComponentState
- Type: Component.state
stop(self)
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component
will remain in a STOPPING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
subscribe(self, DataType data_type)
subscribed_custom_data(self)
Return the custom data types subscribed to.
- Return type: list[DataType]
trader_id
The trader ID associated with the component.
- Returns: TraderId
type
The components type.
- Returns: type
unsubscribe(self, DataType data_type)
venue
The clients venue ID (if applicable).
- Returns:
Venue or
None
class BacktestMarketDataClient
Bases: MarketDataClient
BacktestMarketDataClient(ClientId client_id, MessageBus msgbus, Cache cache, Clock clock)
Provides an implementation of MarketDataClient for backtesting.
- Parameters:
- client_id (ClientId) – The data client ID.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (Clock) – The clock for the client.
degrade(self)
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component
will remain in a DEGRADING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
dispose(self)
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component
will remain in a DISPOSING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
fault(self)
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component
will remain in a FAULTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
classmethod fully_qualified_name(cls)
Return the fully qualified name for the components class.
- Return type: str
id
The components ID.
- Returns: ComponentId
is_connected
If the client is connected.
- Returns: bool
is_degraded
bool
Return whether the current component state is DEGRADED
.
- Return type: bool
- Type: Component.is_degraded
is_disposed
bool
Return whether the current component state is DISPOSED
.
- Return type: bool
- Type: Component.is_disposed
is_faulted
bool
Return whether the current component state is FAULTED
.
- Return type: bool
- Type: Component.is_faulted
is_initialized
bool
Return whether the component has been initialized (component.state >= INITIALIZED
).
- Return type: bool
- Type: Component.is_initialized
is_running
bool
Return whether the current component state is RUNNING
.
- Return type: bool
- Type: Component.is_running
is_stopped
bool
Return whether the current component state is STOPPED
.
- Return type: bool
- Type: Component.is_stopped
request(self, DataType data_type, UUID4 correlation_id)
Request data for the given data type.
- Parameters:
request_bars(self, BarType bar_type, int limit, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)
request_instrument(self, InstrumentId instrument_id, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)
request_instruments(self, Venue venue, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)
request_order_book_snapshot(self, InstrumentId instrument_id, int limit, UUID4 correlation_id)
request_quote_ticks(self, InstrumentId instrument_id, int limit, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)
request_trade_ticks(self, InstrumentId instrument_id, int limit, UUID4 correlation_id, datetime start: datetime | None = None, datetime end: datetime | None = None)
reset(self)
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component
will remain in a RESETTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
resume(self)
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component
will remain in a RESUMING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
start(self)
Start the component.
While executing on_start() any exception will be logged and reraised, then the component
will remain in a STARTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
state
ComponentState
Return the components current state.
- Return type: ComponentState
- Type: Component.state
stop(self)
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component
will remain in a STOPPING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
subscribe(self, DataType data_type)
Subscribe to data for the given data type.
- Parameters: data_type (DataType) – The data type for the subscription.
subscribe_bars(self, BarType bar_type)
subscribe_instrument(self, InstrumentId instrument_id)
subscribe_instrument_close(self, InstrumentId instrument_id)
subscribe_instrument_status(self, InstrumentId instrument_id)
subscribe_instruments(self)
subscribe_order_book_deltas(self, InstrumentId instrument_id, BookType book_type, int depth=0, dict kwargs=None)
subscribe_order_book_snapshots(self, InstrumentId instrument_id, BookType book_type, int depth=0, dict kwargs=None)
subscribe_quote_ticks(self, InstrumentId instrument_id)
subscribe_trade_ticks(self, InstrumentId instrument_id)
subscribe_venue_status(self, Venue venue)
subscribed_bars(self)
Return the bar types subscribed to.
- Return type: list[BarType]
subscribed_custom_data(self)
Return the custom data types subscribed to.
- Return type: list[DataType]
subscribed_instrument_close(self)
Return the instrument closes subscribed to.
- Return type: list[InstrumentId]
subscribed_instrument_status(self)
Return the status update instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_instruments(self)
Return the instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_order_book_deltas(self)
Return the order book delta instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_order_book_snapshots(self)
Return the order book snapshot instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_quote_ticks(self)
Return the quote tick instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_trade_ticks(self)
Return the trade tick instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_venue_status(self)
Return the status update instruments subscribed to.
- Return type: list[InstrumentId]
trader_id
The trader ID associated with the component.
- Returns: TraderId
type
The components type.
- Returns: type
unsubscribe(self, DataType data_type)
Unsubscribe from data for the given data type.
- Parameters: data_type (DataType) – The data type for the subscription.
unsubscribe_bars(self, BarType bar_type)
unsubscribe_instrument(self, InstrumentId instrument_id)
unsubscribe_instrument_close(self, InstrumentId instrument_id)
unsubscribe_instrument_status(self, InstrumentId instrument_id)
unsubscribe_instruments(self)
unsubscribe_order_book_deltas(self, InstrumentId instrument_id)
unsubscribe_order_book_snapshots(self, InstrumentId instrument_id)
unsubscribe_quote_ticks(self, InstrumentId instrument_id)
unsubscribe_trade_ticks(self, InstrumentId instrument_id)
unsubscribe_venue_status(self, Venue venue)
venue
The clients venue ID (if applicable).
- Returns:
Venue or
None
class BacktestEngine
Bases: object
BacktestEngine(config: BacktestEngineConfig | None = None) -> None
Provides a backtest engine to run a portfolio of strategies over historical data.
- Parameters: config (BacktestEngineConfig , optional) – The configuration for the instance.
- Raises: TypeError – If config is not of type BacktestEngineConfig.
add_actor(self, Actor actor: Actor)
Add the given actor to the backtest engine.
- Parameters: actor (Actor) – The actor to add.
add_actors(self, list actors: list[Actor])
Add the given list of actors to the backtest engine.
- Parameters: actors (list [Actor ]) – The actors to add.
add_data(self, list data, ClientId client_id=None, bool validate=True, bool sort=True)
Add the given custom data to the backtest engine.
- Parameters:
- data (list *[*Data ]) – The data to add.
- client_id (ClientId , optional) – The data client ID to associate with custom data.
- validate (bool , default True) – If data should be validated (recommended when adding data directly to the engine).
- sort (bool , default True) – If data should be sorted by ts_init with the rest of the stream after adding (recommended when adding data directly to the engine).
- Raises:
- ValueError – If data is empty.
- ValueError – If data contains objects which are not a type of Data.
- ValueError – If instrument_id for the data is not found in the cache.
- ValueError – If data elements do not have an instrument_id and client_id is
None
. - TypeError – If data is a type provided by Rust pyo3 (cannot add directly to engine yet).
WARNING
Assumes all data elements are of the same type. Adding lists of varying data types could result in incorrect backtest logic.
Caution if adding data without sort being True, as this could lead to running backtests on a stream which does not have monotonically increasing timestamps.
add_exec_algorithm(self, ExecAlgorithm exec_algorithm: ExecAlgorithm)
Add the given execution algorithm to the backtest engine.
- Parameters: exec_algorithm (ExecAlgorithm) – The execution algorithm to add.
add_exec_algorithms(self, list exec_algorithms: list[ExecAlgorithm])
Add the given list of execution algorithms to the backtest engine.
- Parameters: exec_algorithms (list [ExecAlgorithm ]) – The execution algorithms to add.
add_instrument(self, Instrument instrument)
Add the instrument to the backtest engine.
The instrument must be valid for its associated venue. For instance,
derivative instruments which would trade on margin cannot be added to
a venue with a CASH
account.
- Parameters: instrument (Instrument) – The instrument to add.
- Raises:
- InvalidConfiguration – If the venue for the instrument has not been added to the engine.
- InvalidConfiguration – If instrument is not valid for its associated venue.
add_strategies(self, list strategies: list[Strategy])
Add the given list of strategies to the backtest engine.
- Parameters: strategies (list [Strategy ]) – The strategies to add.
add_strategy(self, Strategy strategy: Strategy)
Add the given strategy to the backtest engine.
- Parameters: strategy (Strategy) – The strategy to add.
add_venue(self, Venue venue: Venue, OmsType oms_type: OmsType, AccountType account_type: AccountType, list starting_balances: list[Money], base_currency: Currency | None = None, default_leverage: Decimal | None = None, leverages: dict[InstrumentId, Decimal] | None = None, modules: list[SimulationModule] | None = None, fill_model: FillModel | None = None, fee_model: FeeModel | None = None, latency_model: LatencyModel | None = None, BookType book_type: BookType = BookType.L1_MBP, routing: bool = False, frozen_account: bool = False, bar_execution: bool = True, reject_stop_orders: bool = True, support_gtd_orders: bool = True, support_contingent_orders: bool = True, use_position_ids: bool = True, use_random_ids: bool = False, use_reduce_only: bool = True)
Add a SimulatedExchange with the given parameters to the backtest engine.
- Parameters:
- venue (Venue) – The venue ID.
- oms_type (OmsType {
HEDGING
,NETTING
}) – The order management system type for the exchange. IfHEDGING
will generate new position IDs. - account_type (AccountType) – The account type for the client.
- starting_balances (list [Money ]) – The starting account balances (specify one for a single asset account).
- base_currency (Currency , optional) – The account base currency for the client. Use
None
for multi-currency accounts. - default_leverage (Decimal , optional) – The account default leverage (for margin accounts).
- leverages (dict [InstrumentId , Decimal ] , optional) – The instrument specific leverage configuration (for margin accounts).
- modules (list [SimulationModule ] , optional) – The simulation modules to load into the exchange.
- fill_model (FillModel , optional) – The fill model for the exchange.
- fee_model (FeeModel , optional) – The fee model for the venue.
- latency_model (LatencyModel , optional) – The latency model for the exchange.
- book_type (BookType, default
BookType.L1_MBP
) – The default order book type for fill modelling. - routing (bool , default False) – If multi-venue routing should be enabled for the execution client.
- frozen_account (bool , default False) – If the account for this exchange is frozen (balances will not change).
- bar_execution (bool , default True) – If bars should be processed by the matching engine(s) (and move the market).
- reject_stop_orders (bool , default True) – If stop orders are rejected on submission if trigger price is in the market.
- support_gtd_orders (bool , default True) – If orders with GTD time in force will be supported by the venue.
- support_contingent_orders (bool , default True) – If contingent orders will be supported/respected by the venue. If False then its expected the strategy will be managing any contingent orders.
- use_position_ids (bool , default True) – If venue position IDs will be generated on order fills.
- use_random_ids (bool , default False) – If all venue generated identifiers will be random UUID4’s.
- use_reduce_only (bool , default True) – If the reduce_only execution instruction on orders will be honored.
- Raises: ValueError – If venue is already registered with the engine.
backtest_end
datetime | None
Return the last backtest run time range end (if run).
- Return type:
datetime or
None
- Type: BacktestEngine.backtest_end
backtest_start
datetime | None
Return the last backtest run time range start (if run).
- Return type:
datetime or
None
- Type: BacktestEngine.backtest_start
cache
CacheFacade
Return the engines internal read-only cache.
- Return type: CacheFacade
- Type: BacktestEngine.cache
change_fill_model(self, Venue venue, FillModel model)
Change the fill model for the exchange of the given venue.
- Parameters:
clear_actors(self)
Clear all actors from the engines internal trader.
clear_data(self)
Clear the engines internal data stream.
Does not clear added instruments.
clear_exec_algorithms(self)
Clear all execution algorithms from the engines internal trader.
clear_strategies(self)
Clear all trading strategies from the engines internal trader.
data
list[Data]
Return the engines internal data stream.
- Return type: list[Data]
- Type: BacktestEngine.data
dispose(self)
Dispose of the backtest engine by disposing the trader and releasing system resources.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
dump_pickled_data(self)
Return the internal data stream pickled.
- Return type: bytes
end(self)
Manually end the backtest.
get_result(self)
Return the backtest result from the last run.
- Return type: BacktestResult
instance_id
UUID4
Return the engines instance ID.
This is a unique identifier per initialized engine.
- Return type: UUID4
- Type: BacktestEngine.instance_id
iteration
int
Return the backtest engine iteration count.
- Return type: int
- Type: BacktestEngine.iteration
kernel
NautilusKernel
Return the internal kernel for the engine.
- Return type: NautilusKernel
- Type: BacktestEngine.kernel
list_venues(self)
Return the venues contained within the engine.
- Return type: list[Venue]
load_pickled_data(self, bytes data)
Load the given pickled data directly into the internal data stream.
It is highly advised to only pass data to this method which was obtained through a call to .dump_pickled_data().
WARNING
This low-level direct access method makes the following assumptions: : - The data contains valid Nautilus objects only, which inherit from Data.
- The data was successfully pickled from a call to pickle.dumps().
- The data was sorted prior to pickling.
- All required instruments have been added to the engine.
logger
Logger
Return the internal logger for the engine.
- Return type: Logger
- Type: BacktestEngine.logger
machine_id
str
Return the engines machine ID.
- Return type: str
- Type: BacktestEngine.machine_id
portfolio
PortfolioFacade
Return the engines internal read-only portfolio.
- Return type: PortfolioFacade
- Type: BacktestEngine.portfolio
reset(self)
Reset the backtest engine.
All stateful fields are reset to their initial value.
Note: instruments and data are not dropped/reset, this can be done through a separate call to .clear_data() if desired.
run(self, start: datetime | str | int | None = None, end: datetime | str | int | None = None, run_config_id: str | None = None, streaming: bool = False)
Run a backtest.
At the end of the run the trader and strategies will be stopped, then post-run analysis performed.
If more data than can fit in memory is to be run through the backtest engine, then streaming mode can be utilized. The expected sequence is as follows:
- Add initial data batch and strategies.
- Call run(streaming=True).
- Call clear_data().
- Add next batch of data stream.
- Call either run(streaming=False) or end(). When there is no more data to run on.
- Parameters:
- start (datetime or str or int , optional) – The start datetime (UTC) for the backtest run.
If
None
engine runs from the start of the data. - end (datetime or str or int , optional) – The end datetime (UTC) for the backtest run.
If
None
engine runs to the end of the data. - run_config_id (str , optional) – The tokenized BacktestRunConfig ID.
- streaming (bool , default False) – If running in streaming mode. If False then will end the backtest following the run iterations.
- start (datetime or str or int , optional) – The start datetime (UTC) for the backtest run.
If
- Raises:
- ValueError – If no data has been added to the engine.
- ValueError – If the start is >= the end datetime.
run_config_id
str
Return the last backtest engine run config ID.
- Return type:
str or
None
- Type: BacktestEngine.run_config_id
run_finished
datetime | None
Return when the last backtest run finished (if run).
- Return type:
datetime or
None
- Type: BacktestEngine.run_finished
run_id
UUID4
Return the last backtest engine run ID (if run).
- Return type:
UUID4 or
None
- Type: BacktestEngine.run_id
run_started
datetime | None
Return when the last backtest run started (if run).
- Return type:
datetime or
None
- Type: BacktestEngine.run_started
trader
Trader
Return the engines internal trader.
- Return type: Trader
- Type: BacktestEngine.trader
trader_id
TraderId
Return the engines trader ID.
- Return type: TraderId
- Type: BacktestEngine.trader_id
class SimulatedExchange
Bases: object
SimulatedExchange(Venue venue, OmsType oms_type, AccountType account_type, list starting_balances, Currency base_currency: Currency | None, default_leverage: Decimal, dict leverages: dict[InstrumentId, Decimal], list modules, PortfolioFacade portfolio, MessageBus msgbus, CacheFacade cache, TestClock clock, FillModel fill_model, FeeModel fee_model, LatencyModel latency_model=None, BookType book_type=BookType.L1_MBP, bool frozen_account=False, bool bar_execution=True, bool reject_stop_orders=True, bool support_gtd_orders=True, bool support_contingent_orders=True, bool use_position_ids=True, bool use_random_ids=False, bool use_reduce_only=True, bool use_message_queue=True) -> None
Provides a simulated exchange venue.
- Parameters:
- venue (Venue) – The venue to simulate.
- oms_type (OmsType {
HEDGING
,NETTING
}) – The order management system type used by the exchange. - account_type (AccountType) – The account type for the client.
- starting_balances (list [Money ]) – The starting balances for the exchange.
- base_currency (Currency , optional) – The account base currency for the client. Use
None
for multi-currency accounts. - default_leverage (Decimal) – The account default leverage (for margin accounts).
- leverages (dict [InstrumentId , Decimal ]) – The instrument specific leverage configuration (for margin accounts).
- modules (list *[*SimulatedModule ]) – The simulation modules for the exchange.
- portfolio (PortfolioFacade) – The read-only portfolio for the exchange.
- msgbus (MessageBus) – The message bus for the exchange.
- cache (CacheFacade) – The read-only cache for the exchange.
- clock (TestClock) – The clock for the exchange.
- fill_model (FillModel) – The fill model for the exchange.
- fee_model (FeeModel) – The fee model for the exchange.
- latency_model (LatencyModel , optional) – The latency model for the exchange.
- book_type (BookType) – The order book type for the exchange.
- frozen_account (bool , default False) – If the account for this exchange is frozen (balances will not change).
- bar_execution (bool , default True) – If bars should be processed by the matching engine(s) (and move the market).
- reject_stop_orders (bool , default True) – If stop orders are rejected on submission if in the market.
- support_gtd_orders (bool , default True) – If orders with GTD time in force will be supported by the exchange.
- support_contingent_orders (bool , default True) – If contingent orders will be supported/respected by the exchange. If False then its expected the strategy will be managing any contingent orders.
- use_position_ids (bool , default True) – If venue position IDs will be generated on order fills.
- use_random_ids (bool , default False) – If all exchange generated identifiers will be random UUID4’s.
- use_reduce_only (bool , default True) – If the reduce_only execution instruction on orders will be honored.
- use_message_queue (bool , default True) – If an internal message queue should be used to process trading commands in sequence after they have initially arrived. Setting this to False would be appropriate for real-time sandbox environments, where we don’t want to introduce additional latency of waiting for the next data event before processing the trading command.
- Raises:
- ValueError – If instruments is empty.
- ValueError – If instruments contains a type other than Instrument.
- ValueError – If starting_balances is empty.
- ValueError – If starting_balances contains a type other than Money.
- ValueError – If base_currency and multiple starting balances.
- ValueError – If modules contains a type other than SimulationModule.
account_type
The account base currency.
- Returns: AccountType