Skip to main content

AllassoTradeMachine

The engine that runs strategies against their trading environments. Parameters

AllassoTradeMachine.sequential

classmethod
Create ATM for sequential strategy execution.

AllassoTradeMachine.run

Run the strategy(ies) against the given environments.

EnvironmentBuilder

Builder for creating trading environments with sensible defaults. Record the ids and starting equity; every component stays unset until build(). Parameters

EnvironmentBuilder.with_datafeed

Use datafeed instead of the default local one. build() then requires a matching resolver from with_resolver.

EnvironmentBuilder.with_resolver

Use resolver instead of the default local resolver registry.

EnvironmentBuilder.with_broker

Use broker instead of the default SimulationBroker.

EnvironmentBuilder.with_portfolio

Use portfolio instead of one built from initial_equity. Its own fee calculator stands: with_fee_calculator is then ignored.

EnvironmentBuilder.with_pulse_index

Use pulse_index as the clock, in preference to any calendar. build() still derives the underlyings’ common settlements when with_datetimes is absent; only the resulting value goes unused.

EnvironmentBuilder.with_datetimes

Pulse on datetimes instead of on the underlyings’ common settlements. Copied, and ignored if with_pulse_index supplies a clock of its own. Mutually exclusive with with_date_range: an explicit calendar is already bounded.

EnvironmentBuilder.with_date_range

Bound the derived calendar, inclusive at both ends. The bounds go to pdc’s available_settlements, so the calendar is bisected rather than derived whole and trimmed. Mutually exclusive with with_datetimes, and ignored if with_pulse_index supplies a clock of its own. Parameters

EnvironmentBuilder.with_fee_calculator

Apply fee_calculator to the default Portfolio built by build(). Ignored if a portfolio was already supplied via with_portfolio.

EnvironmentBuilder.build

Build the trading environment with defaults for missing components.

ExecutionResult

dataclass
Result of a strategy execution.

TradingEnvironment

dataclass
Container for all trading components.

TradingEnvironment.attach_to_strategy

Attach all components to a strategy.

Broker

Bases: ABC Broker class that serves as a base for different broker implementations. Brokers are responsible for managing orders and executing them into trades. Pulse method should return the trades that were executed during the pulse.

Broker.open_orders

property
Returns the list of open orders.

Broker.orders

property
Returns the list of all orders.

Broker.pulse

abstractmethod
Pulsing the broker will fill all open orders and return the trades.

Broker.create_order

abstractmethod
Create a market order. The order is queued and filled when the broker is next pulsed. With the default SimulationBroker that happens during the broker step of the same pulse, at that pulse’s market data (no execution delay and no slippage). Parameters

SimulationBroker

Bases: Broker Backtest broker that fills every open order in full on the pulse it is stepped on. Orders are filled at that pulse’s market data, so there is no execution delay, no partial fill and no slippage: a trade’s open_datetime is the pulse its order was placed on. Only market orders exist; pass fill_price to create_order to model a haircut.

SimulationBroker.create_order

Queue a market order, filled in full the next time the broker is pulsed. Parameters Raises

SimulationBroker.pulse

Pulsing the broker will fill all open orders and return the trades.

TradesSummary

dataclass
A point-in-time roll-up of a group of trades: their sizes, notionals, PnL and greeks. Built by Strategy.calculate_trades_summary, which is how a strategy reads a multi-leg structure as one position. The greeks and iv default to None and are filled from the legs that carry them, so a futures or spot leg contributes 0 to a greek total and drops out of the iv average. Attributes

Order

Represents an order in the trading system. Currently only market orders are supported. Parameters Initialize an Order object. Raises

Order.id

property
Get the unique identifier for the order. Returns

Order.instrument

property
Get the instrument associated with the order. Returns

Order.quantity

property
Get the quantity of the instrument to trade. Returns

Order.open_datetime

property
Get the datetime when the order was opened. Returns

Order.execution_datetime

property
Get the datetime when the order was executed. Returns

Order.tags

property
Get the tag(s) associated with the order. Returns

Order.fill_price

property
Get the fill price of the order. Returns

Order.is_lots

property
Check if the order quantity is in lots. Returns

Order.source_id

property
Get the originating strategy / sleeve id, if any. Returns

Portfolio

The book of a backtest: its trades, open positions, per-pulse PnL, equity curve and fees. init_stats seeds the history lists and must run before the first pulse, which marks the open trades, queues their fee events, closes what is due and nets the pulse’s fees against equity. The portfolio keeps no greek aggregate: book exposure is the sum of Trade.delta_contract over open_trades, computed where it is needed. Parameters Attributes

Portfolio.trades

property
Get the list of all trades in the portfolio. Returns

Portfolio.open_trades

property
Get the list of open trades in the portfolio. Returns

Portfolio.pulse_total_pnl

property
Get the per-pulse total profit and loss (PnL) of the portfolio. Sum of pulse_abs_pnl across all open trades for the most recent pulse. Returns

Portfolio.pulse_total_pnl_history

property
Get the history of per-pulse total PnL of the portfolio. Length matches datetimes (one entry per pulse). Returns

Portfolio.daily_datetimes

property
Unique calendar dates the portfolio has been pulsed, in chronological order.

Portfolio.daily_total_pnl_history

property
Per-calendar-date total PnL (sum of per-pulse values within each date). Returns

Portfolio.equity_history

property
Get the history of equity values of the portfolio. Returns

Portfolio.datetimes

property
Get the list of datetimes for which the portfolio has been updated. Returns

Portfolio.current_equity

property
Get the current equity of the portfolio. Returns

Portfolio.initial_equity

property
Get the portfolio’s starting capital (a stable sizing denominator). Returns

Portfolio.equity_pct_change

property
Get the percentage change in equity since the last update. Returns

Portfolio.equity_pct_change_history

property
Get the history of percentage changes in equity. Returns

Portfolio.pulse_fees

property
Total fees charged on the most recent pulse (entry + rebalance + exit). Read off the history rather than off an accumulator: pulse() used to zero the accumulator on its way out, so this could only ever answer 0.0 however much was charged.

Portfolio.pulse_fees_history

property
Per-pulse fees. Length matches datetimes (one entry per pulse).

Portfolio.total_fees

property
Cumulative fees charged since init_stats.

Portfolio.init_stats

Initialize the portfolio with the given pulse index and initial equity.

Portfolio.add_trade

Add a trade to the portfolio and initialize its statistics. Parameters

Portfolio.pulse

Pulse the portfolio to update all open trades and calculate the current equity. Parameters

Portfolio.close_all

Sets a flag to close all trades after the pulse.

Portfolio.__charge_exit_fee

Queue an exit event for a freshly-closed trade. trade._close_price is guaranteed to be set by _instant_trade_close immediately prior. The event is drained alongside entries/rebalances at end of pulse().

Portfolio.__close_trades

Close all trades that have set flag _close_on_pulse_end. Parameters

InstrumentDictSerializer

Bases: Serializer Serializer for Instrument objects.

InstrumentDictSerializer.serialize

staticmethod
Serialize an Instrument object to a dictionary.

InstrumentDictSerializer.deserialize

staticmethod
Deserialize a dictionary to the concrete Option/Future object.

OrderDictSerializer

Bases: Serializer Serializer for Order objects.

OrderDictSerializer.serialize

staticmethod
Serialize an Order object to a dictionary.

OrderDictSerializer.deserialize

staticmethod
Deserialize a dictionary to an Order object.

PortfolioDictSerializer

Bases: Serializer Serializer for Portfolio objects.

PortfolioDictSerializer.serialize

staticmethod
Serialize a Portfolio object to a dictionary.

PortfolioDictSerializer.deserialize

staticmethod
Deserialize a dictionary to a Portfolio object. Parameters

PulseIndexDictSerializer

Bases: Serializer Serializer for PulseIndex objects.

PulseIndexDictSerializer.serialize

staticmethod
Serialize a PulseIndex object to a dictionary.

PulseIndexDictSerializer.deserialize

staticmethod
Deserialize a dictionary to a PulseIndex object.

SimulationBrokerBrokerDictSerializer

Bases: Serializer Serializer for Broker objects.

SimulationBrokerBrokerDictSerializer.serialize

staticmethod
Serialize a Broker object to a dictionary.

SimulationBrokerBrokerDictSerializer.deserialize

staticmethod
Deserialize a dictionary to a SimulationBroker object.

StatsDictSerializer

Bases: Serializer Serializer for Stats objects.

StatsDictSerializer.serialize

staticmethod
Serialize a Stats object to a dictionary, datetimes rendered as ISO strings. Scalar metrics routed through _finite have None, NaN and inf coerced to 0.0. The equity totals and the date strings pass through untouched; return_table and the legacy flat trade fields are still coerced, to {} and 0, by their own or fallbacks.

StatsDictSerializer.deserialize

staticmethod
Deserialize a dictionary to a Stats object.

StrategyDictSerializer

Bases: Serializer Serializer for Strategy objects.

StrategyDictSerializer.serialize

staticmethod
Serialize a Strategy object to a dictionary.

StrategyDictSerializer.deserialize

staticmethod
Deserialize a dictionary to a Strategy object.

TradeDictSerializer

Bases: Serializer Serializer for Trade objects.

TradeDictSerializer.serialize

staticmethod
Serialize a Trade object to a dictionary.

TradeDictSerializer.deserialize

staticmethod
Deserialize a dictionary to a Trade object.

TradeListPandasSerializer

Bases: Serializer Serializer for a list of Trade objects, as a DataFrame with one row per trade.

TradeListPandasSerializer.serialize

staticmethod
Serialize a list of Trade objects to a DataFrame, one row per trade. For a non-empty list the columns are the keys of TradeDictSerializer.serialize, so nested values (the instrument, the tag list, the per-pulse histories) stay as objects in their cell. An empty list gives an empty frame with no columns at all.

TradeListPandasSerializer.deserialize

staticmethod
Deserialize a DataFrame of trade rows back into Trade objects, in row order.

Strategy

A backtest strategy: subclass it, implement on_update() and trade through self. on_update() runs once per pulse, after the clock has advanced and before the broker fills that pulse’s orders. The collaborators it reaches for (datafeed, resolver, broker, portfolio, pulse_index) are attached by the TradingEnvironment when the run starts, which is why they are not constructor arguments. Initialize the Strategy with its underlying id(s), a name and a description. Parameters

Strategy.id

property
Get the unique identifier of the strategy.

Strategy.underlying_id

property
Get the underlying ID(s) of the strategy.

Strategy.pulse_index

property
Get the pulse index of the strategy.

Strategy.last_pulse

property
Get the last pulse time of the strategy.

Strategy.open_trades

property
Get the list of open trades in the portfolio.

Strategy.has_open_trades

property
Check if there are any open trades in the portfolio.

Strategy.trades

property
Get the list of all trades in the portfolio.

Strategy.broker

property
Get the broker associated with the strategy.

Strategy.portfolio

property
Get the portfolio associated with the strategy.

Strategy.current_equity

property
Get the current equity of the portfolio.

Strategy.initial_equity

property
Get the strategy’s starting capital.

Strategy.pnl

property
Cumulative net PnL of the strategy. current_equity - initial_equity. Includes the impact of fees (because both terms are post-fee).

Strategy.pnl_pct

property
Cumulative PnL as a fraction of the account equity right now. pnl / abs(current_equity). The denominator is the current portfolio equity, so this is the live, sizing-aware return of the whole strategy. Same basis as TradesSummary.pnl_pct; differs from Trade.pnl_pct, which is fixed to each trade’s equity-at-open snapshot. abs keeps the sign coming from pnl. Returns 0.0 if current_equity is 0.

Strategy.pnl_pct_of_initial_equity

property
Cumulative PnL as a fraction of the strategy’s starting capital. pnl / abs(initial_equity). Stable denominator across the entire run, mirroring Trade.pnl_pct_of_initial_equity and TradesSummary.pnl_pct_of_initial_equity. Returns 0.0 if initial_equity is 0.

Strategy.datafeed

property
Get the datafeed associated with the strategy.

Strategy.resolver

property
Get the resolver associated with the strategy.

Strategy.stats

property
Get the statistics for the strategy.

Strategy.set_datafeed

Set the datafeed for the strategy. Parameters

Strategy.set_resolver

Set the resolver for the strategy. Parameters

Strategy.set_broker

Set the broker for the strategy. Parameters

Strategy.set_portfolio

Set the portfolio for the strategy. Parameters

Strategy.set_pulse_index

Set the pulse index for the strategy. Parameters

Strategy.on_update

This method should be implemented in the Strategy subclass to define the strategy’s logic.

Strategy.pulse

Pulse the strategy, executing trades.

Strategy.create_order

Place a market order. It is filled on the same pulse, at the current pulse’s market data. This is just a wrapper around the broker’s create_order method. You can also use::
Parameters

Strategy.buy

Buy an instrument. The order is filled on the same pulse, at the current pulse’s market data. Parameters

Strategy.sell

Sell an instrument. The order is filled on the same pulse, at the current pulse’s market data. Parameters

Strategy.close_all

Close all open trades in the portfolio. Raises

Strategy.calculate_stats

Get the statistics for the strategy. Parameters Returns

Strategy.get_trades_by_tags

Get all trades with specific tags. Parameters Returns

Strategy.close_trades_by_tags

Close all open trades with specific tags. Parameters

Strategy.calculate_trades_summary

Aggregate a group of trades into one TradesSummary, marked at the current pulse. Parameters Returns Raises

Strategy.get_trades_summary_by_tags

Get a summary of trades with specific tags. Parameters Returns

PulseIndex

PulseIndex is a class that manages a list of datetimes and allows pulsing through them. It keeps every component in sync with the current datetime index. Initialize the PulseIndex with a list of datetimes. Parameters

PulseIndex.datetimes

property
Get the list of datetimes in the pulse index. Returns

PulseIndex.last_pulse

property
Get the last pulse time. Returns

PulseIndex.pulses_per_year

cached property
Cadence rate as periods-per-calendar-year. Used to annualize per-pulse return metrics (Sharpe, Sortino, etc.). Formula: len(datetimes) * 365 / span_calendar_days. Examples: SPX daily backtest (~252 datetimes spanning ~365 days) -> ~252. BTC hourly 24/7 (~8760 over 365 days) -> ~8760. SPX hourly 6.5h sessions (~1638 over 365 days) -> ~1638. Cached on first access. Invalidated by append.

PulseIndex.index

property
Get the current index in the pulse index. Returns: int: Current index in the pulse index.

PulseIndex.__clear_cache

Drop the cached pulses_per_year so the next access recomputes over the new calendar. functools.cached_property stores its value in the instance __dict__ under the property’s own name (shadowing the descriptor); popping it re-exposes the getter. No-op when the property was never accessed.

PulseIndex.append

Append a new datetime to the pulse index. Parameters

PulseIndex.extend

Append the datetimes past the current last one (backtest continuation). Tail-only: entries at or before the current last datetime are ignored, so passing a full re-derived calendar and passing just the new datetimes both work. datetimes is assumed sorted. The cursor stays where it is, so a finished run resumes on the first new datetime. Parameters

PulseIndex.pulse

Advance the pulse index to the next datetime.

PulseIndex.has_next

Check if there is a next pulse. Returns

PulseIndex.peek_next

The datetime the next pulse would land on, or None at the end. Lets callers test “is this the next pulse” without reaching into the index arithmetic. Returns

PulseIndex.advance_to

Fast-forward the cursor to the latest datetime <= target (assumes sorted datetimes). A one-shot seek used to skip a leading span without pulsing through it step by step. When target precedes the first datetime the cursor stays at index 0; when it is at or past the last, it lands on the last. Parameters

PulseIndex.pulse_history

Get the pulse history at a specific index. Parameters Returns

Trade

One filled position in one instrument: what the broker turns an Order into. Construction is two-phase. __init__ records what was filled; Portfolio.add_trade then calls init_stats, which reads the opening mark off the datafeed and sets the prices, greeks, notional and history lists. Until it has run the trade cannot be pulsed and none of that marked state can be read. pulse marks the trade once per pulse thereafter, skipping the pulse it opened on. Parameters

Trade.trade_id

property
Get the unique identifier for the trade.

Trade.order_id

property
Get the unique identifier for the order associated with this trade.

Trade.open_price

property
Get the price at which the trade was opened at.

Trade.open_quantity

property
Get the open quantity of a trade.

Trade.fill_price

property
Get the fill price of the trade.

Trade.settlement_price_at_open

property
Get the settlement price at which the trade was opened at.

Trade.close_price

property
Get the price at which the trade was closed at.

Trade.instrument

property
Get the instrument associated with the trade.

Trade.quantity

property
Get the quantity of the instrument traded.

Trade.is_lots

property
Check if the trade quantity is in lots.

Trade.contract_size

property
Units per lot of the traded contract, read from the reference data at open.

Trade.price_format_multiplier

property
Factor turning the data layer’s raw price into the marking price, read at open.

Trade.units

property
Signed quantity in the instrument’s own units (lots scaled by contract_size).

Trade.sign

property
Get the sign of the trade quantity.

Trade.open_datetime

property
Get the datetime when the trade was opened.

Trade.close_datetime

property
Get the datetime when the trade was closed.

Trade.is_open

property
Check if the trade is still open.

Trade.tags

property
Get the tags associated with the trade.

Trade.source_id

property
Get the originating strategy / sleeve id, if any. Carried from the pulse.core.order.Order that filled into this trade. None for trades not attributed to a sleeve (e.g. classic single-strategy use).

Trade.pnl

property
Get the cumulative profit and loss of the trade. Returns the pnl of the trade in dollars.

Trade.pnl_pct

property
Cumulative PnL as a fraction of the account equity at trade open. pnl / abs(equity_at_open). Sizing-aware - tells you how this trade moved the account at the moment it was taken. Denominator is wrapped in abs so a gain on a negative-equity account still reads positive. Returns 0.0 if equity_at_open is 0.

Trade.initial_equity

property
Strategy starting capital, captured at trade open by Portfolio.add_trade.

Trade.equity_at_open

property
Portfolio current_equity at the pulse this trade opens on, captured by Portfolio.add_trade.

Trade.pnl_pct_of_initial_equity

property
Cumulative PnL as a fraction of the strategy’s starting capital. pnl / abs(initial_equity). Stable denominator across the run - directly comparable across trades. Returns 0.0 if initial_equity is 0.

Trade.pulse_abs_pnl

property
Get the last per-pulse absolute profit and loss of the trade.

Trade.pulse_pct_pnl

property
Get the last per-pulse percentage profit and loss of the trade.

Trade.datetimes

property
Get the historical datetimes of the trade.

Trade.abs_pnl_history

property
Get the historical cumulative profit and loss of the trade in currency.

Trade.pct_pnl_history

property
Get the historical cumulative profit and loss of the trade in percentage.

Trade.pulse_abs_pnl_history

property
Get the historical per-pulse profit and loss of the trade in currency. Length matches datetimes (one entry per pulse).

Trade.pulse_pct_pnl_history

property
Get the historical per-pulse profit and loss of the trade in percentage. Length matches datetimes (one entry per pulse).

Trade.daily_datetimes

property
Unique calendar dates the trade has been live, in chronological order.

Trade.daily_abs_pnl_history

property
Per-calendar-date absolute P&L (sum of pulse values within each date).

Trade.daily_pct_pnl_history

property
Per-calendar-date percentage P&L (compounded pulse pct returns within each date).

Trade.daily_abs_pnl

property
Today’s running absolute P&L tally (today = datetimes[-1].date()). For daily cadence this equals pulse_abs_pnl.

Trade.daily_pct_pnl

property
Today’s running compound percentage P&L.

Trade.quantity_history

property
Get the historical quantity of the trade.

Trade.price_history

property
Get the historical prices of the trade.

Trade.notional_history

property
Get the historical notional values of the trade.

Trade.delta

property
Get the per-unit delta of the trade. For futures this is 1.0.

Trade.gamma

property
Get the per-unit gamma of the trade. For futures this is 0.0.

Trade.theta

property
Get the per-unit theta of the trade. For futures this is 0.0.

Trade.vega

property
Get the per-unit vega of the trade. For futures this is 0.0.

Trade.delta_contract

property
Get the size-multiplied delta (per-unit delta * units).

Trade.gamma_contract

property
Get the size-multiplied gamma (per-unit gamma * units).

Trade.theta_contract

property
Get the size-multiplied theta (per-unit theta * units).

Trade.vega_contract

property
Get the size-multiplied vega (per-unit vega * units).

Trade.delta_history

property
Get the historical per-unit delta of the trade. Length matches datetimes (one entry per pulse).

Trade.gamma_history

property
Get the historical per-unit gamma of the trade. Length matches datetimes (one entry per pulse).

Trade.theta_history

property
Get the historical per-unit theta of the trade. Length matches datetimes (one entry per pulse).

Trade.vega_history

property
Get the historical per-unit vega of the trade. Length matches datetimes (one entry per pulse).

Trade.delta_contract_history

property
Get the historical size-multiplied delta of the trade. Length matches datetimes (one entry per pulse).

Trade.gamma_contract_history

property
Get the historical size-multiplied gamma of the trade. Length matches datetimes (one entry per pulse).

Trade.theta_contract_history

property
Get the historical size-multiplied theta of the trade. Length matches datetimes (one entry per pulse).

Trade.vega_contract_history

property
Get the historical size-multiplied vega of the trade. Length matches datetimes (one entry per pulse).

Trade.underlying_price_history

property
Get the historical raw price the greeks were taken against: an option’s underlying, a future’s or spot’s own price, before price_format_multiplier. Length matches datetimes (one entry per pulse).

Trade.iv_history

property
Get the historical implied vol of an option (decimal), None for a future or spot. Length matches datetimes (one entry per pulse).

Trade.init_stats

Initialize trade statistics with the datafeed. Parameters

Trade.values_at

The data layer’s row for this contract, or the last one it returned when it is dark. The single read point for a trade, so marking (_mark) and summarising (Strategy.calculate_trades_summary) cannot disagree about what a data gap means. Because the carried value is the record the data layer actually returned, a dark futures or spot leg keeps its real shape: it has no delta attribute, exactly as on a healthy pulse, so it stays out of the greek aggregates instead of being pulled into them by a stand-in. strict=True re-raises instead, for a caller that needs a real row: opening a trade needs a real price, and the framework’s shadow repricer wants an unpriceable leg to surface. Only the data layer’s own LookupError counts as “this contract is absent”. KeyError and IndexError are subclasses of it raised by faults inside the reader (a missing column, a bisect off a truncated file), so those propagate rather than being carried forward as a flat mark for the rest of the run.

Trade.add_tag

Add a tag to the trade. Parameters

Trade.has_tag

Checks if Trade has tag or list of tags. Parameters Returns

Trade.rebalance

Rebalance the trade by adjusting the quantity. Parameters Raises

Trade.pulse

Update the trade with the latest price and calculate PnL. Raises

Trade.close

Close the trade

Stats

dataclass
Encapsulates the computed statistics for a trading strategy.

Stats.from_data

classmethod
Create a Stats instance from raw equity and datetime data. Parameters Returns

Stats.from_strategy

classmethod
Create a Stats instance from a Strategy object. Parameters Returns

Stats.calculate

Populate stats from a Strategy object (backward-compatible method). Prefer using Stats.from_strategy() for new code.

run_sequentially

Run strategies one after another, each in its own trading environment. One EnvironmentBuilder per strategy, built from that strategy’s own underlying_id, so a sweep is just a list of strategies here. Every strategy gets its own portfolio, broker and pulse index; the datafeed and resolver are shared, which is what makes the warmed readers worth paying for once. The pulse calendar is the underlyings’ common settlements, optionally bounded by start_datetime / end_datetime, which are handed to pdc’s available_settlements and are inclusive at both ends. datetimes replaces that calendar outright instead, so it cannot be combined with the bounds. Parameters Raises Returns
Last modified on November 4, 2026