quantlab.execution.rules#

The Execution rules: what the market does with a bar’s orders, as a public module.

A cross-sectional backtest turns target weights into orders and executes them bar by bar. This module states how. A weight decided at bar t fills at bar t + FILL_DELAY_BARS at that bar’s fill price, the last known one when the bar has none. An order whose raw fill price, or whose sizing price, is missing is rejected and its holding kept, and a NaN weight sends no order at all. A holding delisted on bar b is settled on b + 1 at its last valuation whatever its weight asks, with no fee or slippage, and for nothing at a last valuation of 0.

Each weight is sized as weight * book / price - shares, the book valued at the prices of the sizing basis: the order prices ("fill") or the signal bar’s valuation prices ("valuation"). A bar’s orders run in ascending order of value, so sells come before buys, and a buy whose cost and fee exceed the cash left is cut to what the cash pays for. Slippage moves the fill price against the trade and the fee is a fraction of the traded value.

These are vectorbt 1.1’s Portfolio.from_orders with target-percent sizes, direction="both", shared cash and call_seq="auto", down to its closeness tolerances, so replay holds what the vectorbt engine executes to floating-point rounding. The engine plans its orders with plan_orders. ExecutionBook keeps the same book one bar at a time, for a driver that learns each rebalance’s weights only once it has decided them.

The module imports only numpy: no quantlab layer and no simulation engine.

Examples#

Half the book in AAA, decided on bar 0, fills on bar 1 at 10:

>>> import numpy as np
>>> weights = np.array([[0.5], [np.nan], [np.nan]])
>>> prices = np.array([[8.0], [10.0], [11.0]])
>>> result = replay(weights, prices, prices, np.zeros((3, 1), dtype=bool))
>>> result.shares[:, 0].tolist(), result.cash.tolist()
([0.0, 0.05, 0.05], [1.0, 0.5, 0.5])

Classes

BarExecution

What happened to one bar's orders, as booleans on [S].

ExecutionBook

Shares and cash, traded one bar at a time under the Execution rules.

ExecutionReplay

The holdings after each bar's orders, and what happened to them.

ExecutionSettings

How orders are sized and charged.

OrderPlan

The orders the market accepts, one row per fill bar.

Functions

add

vectorbt's add_nb: a + b, exactly 0 when the two cancel up to tolerance.

is_close

vectorbt's is_close_nb: equal up to its relative and absolute tolerance.

plan_orders

Return the orders the market accepts for weights decided on each bar.

replay

Replay weights decided on each bar and return the holdings after every bar.