pybroker.context module

Contains context related classes. A context provides data during the execution of a pybroker.strategy.Strategy.

class ExecContext(symbol: str, config: StrategyConfig, portfolio: Portfolio, col_scope: ColumnScope, ind_scope: IndicatorScope, interval_scope: IntervalScope, declared_intervals: frozenset[int | Literal['daily', 'weekly', 'monthly', 'quarterly', 'yearly'] | str], input_scope: ModelInputScope, pred_scope: PredictionScope, pending_order_scope: PendingOrderScope, models: Mapping[ModelSymbol, TrainedModel], sym_end_index: Mapping[str, int], session: MutableMapping, run_hyperparams: Mapping[str, Any] | None = None, allowed_hyperparam_names: frozenset[str] = frozenset({}), rotation_enabled: bool = False)[source]

Bases: object

Contains context data during the execution of a pybroker.strategy.Strategy. Includes data about the current bar, portfolio positions, and other relevant context. This class is also used to set buy and sell signals for placing orders.

The data contained in this class is for the latest bar that has already completed. Placing an order will be executed on a future bar specified by pybroker.config.StrategyConfig.buy_delay and pybroker.config.StrategyConfig.sell_delay.

config

pybroker.config.StrategyConfig.

symbol

Current ticker symbol of the execution.

buy_fill_price

Fill price to use for a buy (long) order of symbol.

buy_shares

Number of shares to buy of symbol.

buy_limit_price

Limit price to use for a buy (long) order of symbol.

buy_timeout_bars

Number of bars to retry an unfilled buy limit order after the first attempt. None for a single attempt, -1 for indefinite persistence, or a positive integer for a limited number of retry bars.

sell_fill_price

Fill price to use for a sell (short) order of symbol.

sell_shares

Number of shares to sell of symbol.

sell_limit_price

Limit price to use for a sell (short) order of symbol.

sell_timeout_bars

Number of bars to retry an unfilled sell limit order after the first attempt. None for a single attempt, -1 for indefinite persistence, or a positive integer for a limited number of retry bars.

hold_bars

Number of bars to hold a long or short position for, after which the position is automatically liquidated.

long_score

Score used to rank symbol when ranking buy and cover signals. Orders are placed for symbols with the highest long_score values, where the number of long positions held at any time in the pybroker.portfolio.Portfolio is specified by pybroker.strategy.Strategy.set_max_long_positions(). When rotation is enabled with pybroker.strategy.Strategy.enable_rotation(), long_score drives long rotation and orders set during an pybroker.strategy.Execution are ignored.

short_score

Score used to rank symbol when ranking sell signals. Orders are placed for symbols with the highest short_score values, where the number of short positions held at any time in the pybroker.portfolio.Portfolio is specified by pybroker.strategy.Strategy.set_max_short_positions(). When rotation is enabled with pybroker.strategy.Strategy.enable_rotation(), short_score drives short rotation and orders set during an pybroker.strategy.Execution are ignored.

session

dict used to store custom data that persists for each bar during the pybroker.strategy.Strategy‘s execution.

stop_loss

Sets stop loss on a new pybroker.portfolio.Entry, where value is measured in points from entry price.

stop_loss_pct

Sets stop loss on a new pybroker.portfolio.Entry, where value is measured in percentage from entry price.

stop_loss_limit

Limit price to use for the stop loss.

stop_loss_exit_price

Exit pybroker.common.PriceType to use for the stop loss exit. If set, the stop is checked against the exit_price and exits at the exit_price when triggered.

stop_profit

Sets profit stop on a new pybroker.portfolio.Entry, where value is measured in points from entry price.

stop_profit_pct

Sets profit stop on a new pybroker.portfolio.Entry, where value is measured in percentage from entry price.

stop_profit_limit

Limit price to use for the profit stop.

stop_profit_exit_price

Exit pybroker.common.PriceType to use for the profit stop exit. If set, the stop is checked against the exit_price and exits at the exit_price when triggered.

stop_trailing

Sets a trailing stop loss on a new pybroker.portfolio.Entry, where value is measured in points from entry price.

stop_trailing_pct

Sets a trailing stop loss on a new pybroker.portfolio.Entry, where value is measured in percentage from entry price.

stop_trailing_limit

Limit price to use for the trailing stop loss.

stop_trailing_exit_price

Exit pybroker.common.PriceType to use for the trailing stop exit. If set, the stop is checked against the exit_price and exits at the exit_price when triggered.

property bars: int

Number of bars of data that have completed.

property buying_power: Decimal

Available buying power for long and short orders given pybroker.config.StrategyConfig.leverage.

This is what the pybroker.portfolio.Portfolio clamps orders against at fill time. calc_target_shares() sizes off deployable capital (equity multiplied by leverage) instead, so the two can differ once positions are open.

calc_target_shares(target_size: float, price: float | None = None, cash: float | None = None) Decimal | int[source]

Calculates the number of shares given a target_size allocation and share price.

Parameters:
  • target_size – Proportion of deployable capital used to calculate the number of shares, where the max target_size is 1. For example, a target_size of 0.1 would represent 10% of deployable capital.

  • price – Share price used to calculate the number of shares. If None, the share price of the ExecContext‘s symbol is used.

  • cash – Capital used to calculate the number of shares. If None, deployable capital is used, defined as portfolio equity multiplied by pybroker.config.StrategyConfig.leverage. The resulting order is still capped by buying_power when it is placed.

Returns:

Number of shares given target_size and share price. If pybroker.config.StrategyConfig.enable_fractional_shares is True, then a Decimal is returned.

cancel_all_pending_orders(symbol: str | None = None)[source]

Cancels all pybroker.scope.PendingOrders for symbol. When symbol is None, all pending orders are canceled.

cancel_pending_order(order_id: int) bool[source]

Cancels a pybroker.scope.PendingOrder with order_id.

cancel_stop(stop_id: int) bool[source]

Cancels a pybroker.portfolio.Stop with stop_id.

cancel_stops(val: str | Position | Entry, stop_type: StopType | None = None)[source]

Cancels pybroker.portfolio.Stops.

Parameters:
property cash: Decimal

Total cash currently held in the pybroker.portfolio.Portfolio.

property close: ndarray[tuple[Any, ...], dtype[float64]]

Current bar’s close price.

property close_price: float

Current bar’s close price as a scalar.

cover_all_shares()[source]

Covers all short shares of ExecContext.symbol.

property cover_fill_price: int | float | floating | Decimal | PriceType | Callable[[str, BarData], int | float | Decimal] | None

Alias for buy_fill_price. When set, this causes the buy order to be placed before any sell orders.

property cover_limit_price: int | float | Decimal | None

Alias for buy_limit_price. When set, this causes the buy order to be placed before any sell orders.

property cover_shares: int | float | Decimal | None

Alias for buy_shares. When set, this causes the buy order to be placed before any sell orders.

property dt: datetime

Current bar’s date expressed as a datetime.

foreign(symbol: str, col: str | None = None) BarData | ndarray[tuple[Any, ...], dtype[_ScalarT]] | None[source]

Retrieves bar data for another ticker symbol.

Parameters:
  • symbol – Ticker symbol of the bar data.

  • col – Name of the data column to retrieve. If None, all data columns are returned in pybroker.common.BarData.

Returns:

If col is None, a pybroker.common.BarData instance containing data of all bars up to the current one. Otherwise, an numpy.ndarray containing values of the column col.

has_long_positions() bool[source]

Returns whether any long positions are currently open.

has_short_positions() bool[source]

Returns whether any short positions are currently open.

property high: ndarray[tuple[Any, ...], dtype[float64]]

Current bar’s high price.

property high_price: float

Current bar’s high price as a scalar.

hyperparam(name: str) Any[source]

Returns a hyperparameter value for this execution.

The name must have been attached via hyperparams=[...] on pybroker.strategy.Strategy.add_execution().

indicator(name: str, symbol: str | None = None) ndarray[tuple[Any, ...], dtype[float64]][source]

Returns indicator data.

Parameters:
  • name – Name used to identify the indicator, registered with pybroker.indicator.indicator().

  • symbol – Ticker symbol that was used to generate the indicator data. If None, the ExecContext‘s symbol is used.

Returns:

numpy.ndarray of indicator values for all bars up to the current one, sorted in ascending chronological order.

input(model_name: str, symbol: str | None = None) DataFrame[source]

Returns model input data for making predictions.

Parameters:
  • model_name – Name of the model for the input data.

  • symbol – Ticker symbol of the model for the input data. If None, the ExecContext‘s symbol is used.

Returns:

pandas.DataFrame containing the input data, where each row represents a bar in the sequence up to the current bar. The rows are sorted in ascending chronological order.

interval(interval: int | Literal['daily', 'weekly', 'monthly', 'quarterly', 'yearly'] | str) IntervalContext[source]

Returns a read-only view of compressed bar data for interval.

interval must match a value this execution declared with intervals in pybroker.strategy.Strategy.add_execution(), or an interval bound to one of the execution’s models or indicators with pybroker.model.ModelSource.intervals() / pybroker.indicator.Indicator.intervals(). Intervals are scoped per execution: reading an interval that another execution declared raises ValueError, the same way hyperparam() is gated by the execution’s hyperparams. The same TimeframeInterval forms are supported:

  • Every-n-bars (int): e.g. ctx.interval(5) for bars formed from every 5 base bars.

  • Duration (str): e.g. ctx.interval("5m") for fixed-duration bins (digits plus unit letter).

  • Calendar (str): e.g. ctx.interval("weekly") for calendar weekly bars. Weeks start on Monday, months on the first of the month, quarters in January, April, July, and October, and years on January 1.

For example:

strategy.add_execution(
    exec_fn,
    "SPY",
    indicators=[sma20.intervals("weekly")],
    intervals=["5m"],
)
strategy.walkforward(windows=1, timeframe="1m")

def exec_fn(ctx):
    weekly = ctx.interval("weekly")
    five_min = ctx.interval("5m")
    if len(weekly.close) > 0:
        wk_sma = weekly.indicator("sma20")
Parameters:

interval – Compression interval declared for this execution with pybroker.strategy.Strategy.add_execution(), or bound to one of its models or indicators.

Returns:

pybroker.context.IntervalContext exposing read-only OHLCV, indicators, and model outputs on the compressed bars.

long_pos(symbol: str | None = None) Position | None[source]

Retrieves a current long pybroker.portfolio.Position for a symbol.

Parameters:

symbol – Ticker symbol of the position to return. If None, the ExecContext‘s symbol is used. Defaults to None.

Returns:

pybroker.portfolio.Position if one exists, otherwise None.

long_positions(symbol: str | None = None) Iterator[Position][source]

Retrieves all current long positions.

Parameters:

symbol – Ticker symbol used to filter positions. If None, long positions for all symbols are returned. Defaults to None.

Returns:

Iterator of currently held long pybroker.portfolio.Position s.

property loss_rate: Decimal

Running loss rate of trades.

property low: ndarray[tuple[Any, ...], dtype[float64]]

Current bar’s low price.

property low_price: float

Current bar’s low price as a scalar.

property margin_loan: Decimal

Borrowed funds used for leveraged long and short positions.

model(name: str, symbol: str | None = None) Any[source]

Returns a trained model.

Parameters:
  • name – Name used to identify the model that was registered with pybroker.model.model().

  • symbol – Ticker symbol of the data that was used to train the model. If None, the ExecContext‘s symbol is used.

Returns:

Instance of the trained model.

property net_cash_balance: Decimal

Net cash balance (cash - margin_loan).

property open: ndarray[tuple[Any, ...], dtype[float64]]

Current bar’s open price.

property open_price: float

Current bar’s open price as a scalar.

orders() Iterator[Order][source]

Iterator of all pybroker.portfolio.Orders that have been placed and filled.

pending_orders(symbol: str | None = None) Iterator[PendingOrder][source]
pos(symbol: str, pos_type: Literal['long', 'short']) Position | None[source]

Retrieves a current long or short pybroker.portfolio.Position for a symbol.

Parameters:
  • symbol – Ticker symbol of the position to return.

  • pos_type – Specifies whether to return a long or short position.

Returns:

pybroker.portfolio.Position if one exists, otherwise None.

positions(symbol: str | None = None, pos_type: Literal['long', 'short'] | None = None) Iterator[Position][source]

Retrieves all current positions.

Parameters:
  • symbol – Ticker symbol used to filter positions. If None, positions for all symbols are returned. Defaults to None.

  • pos_type – Type of positions to return. If None, both long and short positions are returned.

Returns:

Iterator of currently held pybroker.portfolio.Position s.

preds(model_name: str, symbol: str | None = None) ndarray[tuple[Any, ...], dtype[_ScalarT]][source]

Returns model predictions.

Parameters:
  • model_name – Name of the model that made the predictions.

  • symbol – Ticker symbol of the model that made the predictions. If None, the ExecContext‘s symbol is used.

Returns:

numpy.ndarray containing the sequence of model predictions up to the current bar. Sorted in ascending chronological order.

sell_all_shares()[source]

Sells all long shares of ExecContext.symbol.

set_target_shares(target: float, *, dir: Literal['long', 'short'])[source]

Sets orders to reach a target allocation for long or short exposure.

Calculates the number of shares needed to reach target using calc_target_shares().

Parameters:
short_pos(symbol: str | None = None) Position | None[source]

Retrieves a current short pybroker.portfolio.Position for a symbol.

Parameters:

symbol – Ticker symbol of the position to return. If None, the ExecContext‘s symbol is used. Defaults to None.

Returns:

pybroker.portfolio.Position if one exists, otherwise None.

short_positions(symbol: str | None = None) Iterator[Position][source]

Retrieves all current short positions.

Parameters:

symbol – Ticker symbol used to filter positions. If None, short positions for all symbols are returned. Defaults to None.

Returns:

Iterator of currently held short pybroker.portfolio.Position s.

to_result() ExecResult | None[source]

Creates an ExecResult from the data set on ExecContext.

property total_equity: Decimal

Total equity currently held in the pybroker.portfolio.Portfolio.

property total_margin: Decimal

Total amount of margin currently held in the pybroker.portfolio.Portfolio.

property total_market_value: Decimal

Total market value currently held in the pybroker.portfolio.Portfolio. The market value is defined as the amount of equity held in cash and long positions added together with the unrealized PnL of all open short positions.

trades() Iterator[Trade][source]

Iterator of all pybroker.portfolio.Trades that have been completed.

property volume: ndarray[tuple[Any, ...], dtype[float64]] | None

Current bar’s volume.

property volume_value: float | None

Current bar’s volume as a scalar.

property vwap: ndarray[tuple[Any, ...], dtype[float64]] | None

Current bar’s volume-weighted average price (VWAP).

property vwap_value: float | None

Current bar’s VWAP as a scalar.

property win_rate: Decimal

Running win rate of trades.

class ExecResult(symbol: str, date: datetime64, buy_fill_price: int | float | floating | Decimal | PriceType | Callable[[str, BarData], int | float | Decimal], sell_fill_price: int | float | floating | Decimal | PriceType | Callable[[str, BarData], int | float | Decimal], score: float | None, long_score: float | None, short_score: float | None, hold_bars: int | None, buy_shares: Decimal | None, buy_limit_price: Decimal | None, buy_timeout_bars: int | None, sell_shares: Decimal | None, sell_limit_price: Decimal | None, sell_timeout_bars: int | None, long_stops: frozenset[Stop] | None, short_stops: frozenset[Stop] | None, cover: bool = False, pending_order_id: int | None = None, exit_pos_type: Literal['long', 'short'] | None = None)[source]

Bases: object

Holds data that was set during the execution of a pybroker.strategy.Strategy.

symbol

Ticker symbol that was used for the execution.

Type:

str

date

Timestamp of the bar that was used for the execution.

Type:

numpy.datetime64

buy_fill_price

Fill price to use for a buy (long) order of symbol.

Type:

int | float | numpy.floating | decimal.Decimal | pybroker.common.PriceType | Callable[[str, pybroker.common.BarData], int | float | decimal.Decimal]

sell_fill_price

Fill price to use for a sell (short) order of symbol.

Type:

int | float | numpy.floating | decimal.Decimal | pybroker.common.PriceType | Callable[[str, pybroker.common.BarData], int | float | decimal.Decimal]

long_score

Score used to rank symbol when ranking buy and cover signals. Orders are placed for symbols with the highest long_score values, where the number of long positions held at any time in the pybroker.portfolio.Portfolio is specified by pybroker.strategy.Strategy.set_max_long_positions(). When rotation is enabled with pybroker.strategy.Strategy.enable_rotation(), long_score drives long rotation and orders set during an pybroker.strategy.Execution are ignored.

Type:

float | None

short_score

Score used to rank symbol when ranking sell signals. Orders are placed for symbols with the highest short_score values, where the number of short positions held at any time in the pybroker.portfolio.Portfolio is specified by pybroker.strategy.Strategy.set_max_short_positions(). When rotation is enabled with pybroker.strategy.Strategy.enable_rotation(), short_score drives short rotation and orders set during an pybroker.strategy.Execution are ignored.

Type:

float | None

hold_bars

Number of bars to hold a long or short position for, after which the position is automatically liquidated.

Type:

int | None

buy_shares

Number of shares to buy of symbol.

Type:

decimal.Decimal | None

buy_limit_price

Limit price used for a buy (long) order of symbol.

Type:

decimal.Decimal | None

buy_timeout_bars

Number of bars to retry an unfilled buy limit order after the first attempt. None for a single attempt, -1 for indefinite persistence, or a positive integer for a limited number of retry bars.

Type:

int | None

sell_shares

Number of shares to sell of symbol.

Type:

decimal.Decimal | None

sell_limit_price

Limit price used for a sell (short) order of symbol.

Type:

decimal.Decimal | None

sell_timeout_bars

Number of bars to retry an unfilled sell limit order after the first attempt. None for a single attempt, -1 for indefinite persistence, or a positive integer for a limited number of retry bars.

Type:

int | None

long_stops

Stops for long pybroker.portfolio.Entrys.

Type:

frozenset[pybroker.portfolio.Stop] | None

short_stops

Stops for short pybroker.portfolio.Entrys.

Type:

frozenset[pybroker.portfolio.Stop] | None

cover

Whether buy_shares are used to cover a short position. If True, the resulting buy order will be placed before sell orders.

Type:

bool

pending_order_id

ID of pybroker.scope.PendingOrder that was created.

Type:

int | None

exit_pos_type

Type of the pybroker.portfolio.Position this order exits, either long or short, or None when the order is not an exit. Set by ExecContext.sell_all_shares(), ExecContext.cover_all_shares(), and ExecContext.set_target_shares() with a target of zero. An order carrying this is clamped at fill time to the shares still held, so it can only ever close a position and never flip one.

Type:

Literal[‘long’, ‘short’] | None

class IntervalContext(symbol: str, interval: int | Literal['daily', 'weekly', 'monthly', 'quarterly', 'yearly'] | str, interval_scope: IntervalScope, sym_end_index: Mapping[str, int], models: Mapping[ModelSymbol, TrainedModel])[source]

Bases: object

Read-only view of compressed bar data for a coarser interval.

property bars: int
property close: ndarray[tuple[Any, ...], dtype[float64]]
property dates: ndarray[tuple[Any, ...], dtype[datetime64]]
property high: ndarray[tuple[Any, ...], dtype[float64]]
indicator(name: str) ndarray[tuple[Any, ...], dtype[float64]][source]

Returns indicator values on the compressed interval.

input(model_name: str) DataFrame[source]

Returns model input data on the compressed interval.

property low: ndarray[tuple[Any, ...], dtype[float64]]
model(name: str) Any[source]

Returns a trained model on the compressed interval.

property open: ndarray[tuple[Any, ...], dtype[float64]]
preds(model_name: str) ndarray[tuple[Any, ...], dtype[_ScalarT]][source]

Returns model predictions on the compressed interval.

property volume: ndarray[tuple[Any, ...], dtype[float64]]
class RotationContext(ctxs: Mapping[str, ExecContext], portfolio: Portfolio, long_ranks: Mapping[str, int], short_ranks: Mapping[str, int], config: StrategyConfig)[source]

Bases: object

Context passed to a rotation sizer set with pybroker.strategy.Strategy.enable_rotation().

ctxs

Mapping of all ticker symbols to ExecContexts.

Type:

Mapping[str, pybroker.context.ExecContext]

portfolio

pybroker.portfolio.Portfolio.

Type:

pybroker.portfolio.Portfolio

long_ranks

Rankings computed from rankable ExecContext.long_score values, where 1 is the highest score.

Type:

Mapping[str, int]

short_ranks

Rankings computed from rankable ExecContext.short_score values, where 1 is the highest score.

Type:

Mapping[str, int]

config

pybroker.config.StrategyConfig.

Type:

pybroker.config.StrategyConfig

set_exec_ctx_data(ctx: ExecContext, date: datetime64)[source]

Sets data on an ExecContext instance.

Parameters: