pybroker.context module

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

class BaseContext(config: StrategyConfig, portfolio: Portfolio, col_scope: ColumnScope, ind_scope: IndicatorScope, input_scope: ModelInputScope, pred_scope: PredictionScope, pending_order_scope: PendingOrderScope, models: Mapping[ModelSymbol, TrainedModel], sym_end_index: Mapping[str, int])[source]

Bases: object

Base context class.

config

pybroker.config.StrategyConfig.

calc_target_shares(target_size: float, price: float, 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 cash 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 cash.

  • price – Share price used to calculate the number of shares.

  • cash – Cash used to calculate the number of shares. If None, then the pybroker.portfolio.Portfolio equity is used to calculate the number of shares.

Returns:

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

property cash: Decimal

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

indicator(name: str, symbol: str) ndarray[Any, dtype[float64]][source]

Returns indicator data.

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

  • symbol – Ticker symbol that was used to generate the indicator data.

Returns:

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

input(model_name: str, symbol: str) 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.

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.

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.

model(name: str, symbol: str) 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.

Returns:

Instance of the trained model.

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) ndarray[Any, dtype[_ScalarType_co]][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.

Returns:

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

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.

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 win_rate: Decimal

Running win rate of trades.

class ExecContext(symbol: str, config: StrategyConfig, portfolio: Portfolio, col_scope: ColumnScope, ind_scope: IndicatorScope, input_scope: ModelInputScope, pred_scope: PredictionScope, pending_order_scope: PendingOrderScope, models: Mapping[ModelSymbol, TrainedModel], sym_end_index: Mapping[str, int], session: MutableMapping)[source]

Bases: BaseContext

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.

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.

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.

hold_bars

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

score

Score used to rank symbol when ranking buy and sell signals. Orders are placed for symbols with the highest scores, where the number of positions held at any time in the pybroker.portfolio.Portfolio is specified by pybroker.config.StrategyConfig.max_long_positions and pybroker.config.StrategyConfig.max_short_positions respectively. Long and short signals are ranked separately by score.

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.

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 cash 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 cash.

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

  • cash – Cash used to calculate the number of number of shares. If None, then the pybroker.portfolio.Portfolio equity is used to calculate the number of shares.

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 close: ndarray[Any, dtype[float64]]

Current bar’s close price.

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[Any, dtype[_ScalarType_co]] | 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.

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

Current bar’s high price.

indicator(name: str, symbol: str | None = None) ndarray[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.

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.

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

Current bar’s low price.

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 open: ndarray[Any, dtype[float64]]

Current bar’s open price.

preds(model_name: str, symbol: str | None = None) ndarray[Any, dtype[_ScalarType_co]][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.

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.

to_result() ExecResult | None[source]

Creates an ExecResult from the data set on ExecContext.

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

Current bar’s volume.

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

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

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, hold_bars: int | None, buy_shares: Decimal | None, buy_limit_price: Decimal | None, sell_shares: Decimal | None, sell_limit_price: Decimal | None, long_stops: frozenset[Stop] | None, short_stops: frozenset[Stop] | None, cover: bool = False, pending_order_id: int | 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]

score

Score used to rank symbol when ranking long and short signals. Orders are placed for symbols with the highest scores, where the number of positions held at any time in the pybroker.portfolio.Portfolio is specified by pybroker.config.StrategyConfig.max_long_positions and pybroker.config.StrategyConfig.max_short_positions respectively. Buy and sell signals are ranked separately by score.

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

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

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

cover: bool = False
long_stops: frozenset[Stop] | None
pending_order_id: int | None = None
short_stops: frozenset[Stop] | None
class ExecSignal(id: int, symbol: str, shares: int | float | Decimal, score: float | None, bar_data: BarData, type: Literal['buy', 'sell'])[source]

Bases: NamedTuple

Holds data of a buy/sell signal.

id

Unique ID.

Type:

int

symbol

Ticker symbol.

Type:

str

shares

Number of shares that was set by the pybroker.strategy.Strategy execution.

Type:

int | float | decimal.Decimal

score

Score that was set by the pybroker.strategy.Strategy execution.

Type:

float | None

bar_data

pybroker.common.BarData for symbol.

Type:

pybroker.common.BarData

type

buy or sell signal type.

Type:

Literal[‘buy’, ‘sell’]

class PosSizeContext(config: StrategyConfig, portfolio: Portfolio, col_scope: ColumnScope, ind_scope: IndicatorScope, input_scope: ModelInputScope, pred_scope: PredictionScope, pending_order_scope: PendingOrderScope, models: Mapping[ModelSymbol, TrainedModel], sessions: Mapping[str, Mapping], sym_end_index: Mapping[str, int])[source]

Bases: BaseContext

Holds data for a position size handler set with pybroker.Strategy.set_pos_size_handler(). Used to set position sizes when placing orders from buy and sell signals.

sessions

dict used to store custom data for all symbols.

set_shares(signal: ExecSignal, shares: int | float | Decimal)[source]

Sets the number of shares of an order for the buy or sell signal.

signals(signal_type: Literal['buy', 'sell'] | None = None) Iterator[ExecSignal][source]

Returns Iterator of ExecSignals containing data for buy and sell signals.

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

Sets data on an ExecContext instance.

Parameters:
set_pos_size_ctx_data(ctx: PosSizeContext, buy_results: list[ExecResult] | None, sell_results: list[ExecResult] | None)[source]

Sets data on a PosSizeContext instance.

Parameters: