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
Calculates the number of shares given a
target_size
allocation and shareprice
.- Parameters:
target_size – Proportion of cash used to calculate the number of shares, where the max
target_size
is1
. For example, atarget_size
of0.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 thepybroker.portfolio.Portfolio
equity is used to calculate the number of shares.
- Returns:
Number of shares given
target_size
and shareprice
. Ifpybroker.config.StrategyConfig.enable_fractional_shares
isTrue
, 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 toNone
.- Returns:
Iterator
of currently held longpybroker.portfolio.Position
s.
- 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 allpybroker.portfolio.Order
s that have been placed and filled.
- pos(symbol: str, pos_type: Literal['long', 'short']) Position | None [source]
Retrieves a current long or short
pybroker.portfolio.Position
for asymbol
.- Parameters:
symbol – Ticker symbol of the position to return.
pos_type – Specifies whether to return a
long
orshort
position.
- Returns:
pybroker.portfolio.Position
if one exists, otherwiseNone
.
- 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 toNone
.pos_type – Type of positions to return. If
None
, bothlong
andshort
positions are returned.
- Returns:
Iterator
of currently heldpybroker.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 toNone
.- Returns:
Iterator
of currently held shortpybroker.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 allpybroker.portfolio.Trade
s that have been completed.
- 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
andpybroker.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
.
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
.
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 thepybroker.portfolio.Portfolio
is specified bypybroker.config.StrategyConfig.max_long_positions
andpybroker.config.StrategyConfig.max_short_positions
respectively. Long and short signals are ranked separately byscore
.
- session
dict
used to store custom data that persists for each bar during thepybroker.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 theexit_price
and exits at theexit_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 theexit_price
and exits at theexit_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 theexit_price
and exits at theexit_price
when triggered.
Calculates the number of shares given a
target_size
allocation and shareprice
.- Parameters:
target_size – Proportion of cash used to calculate the number of shares, where the max
target_size
is1
. For example, atarget_size
of0.1
would represent 10% of cash.price – Share price used to calculate the number of shares. If
None
, the share price of theExecContext
‘ssymbol
is used.cash – Cash used to calculate the number of number of shares. If
None
, then thepybroker.portfolio.Portfolio
equity is used to calculate the number of shares.
- Returns:
Number of shares given
target_size
and shareprice
. Ifpybroker.config.StrategyConfig.enable_fractional_shares
isTrue
, then a Decimal is returned.
- cancel_all_pending_orders(symbol: str | None = None)[source]
Cancels all
pybroker.scope.PendingOrder
s forsymbol
. Whensymbol
isNone
, all pending orders are canceled.
- cancel_pending_order(order_id: int) bool [source]
Cancels a
pybroker.scope.PendingOrder
withorder_id
.
- cancel_stop(stop_id: int) bool [source]
Cancels a
pybroker.portfolio.Stop
withstop_id
.
- cancel_stops(val: str | Position | Entry, stop_type: StopType | None = None)[source]
Cancels
pybroker.portfolio.Stop
s.- Parameters:
val – Ticker symbol,
pybroker.portfolio.Position
, orpybroker.portfolio.Entry
for which to cancel stops.stop_type –
pybroker.common.StopType
.
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.
Alias for
buy_shares
. When set, this causes the buy order to be placed before any sell orders.
- 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 inpybroker.common.BarData
.
- Returns:
If
col
isNone
, apybroker.common.BarData
instance containing data of all bars up to the current one. Otherwise, annumpy.ndarray
containing values of the columncol
.
- 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
, theExecContext
‘ssymbol
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
, theExecContext
‘ssymbol
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 asymbol
.- Parameters:
symbol – Ticker symbol of the position to return. If
None
, theExecContext
‘ssymbol
is used. Defaults toNone
.- Returns:
pybroker.portfolio.Position
if one exists, otherwiseNone
.
- 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
, theExecContext
‘ssymbol
is used.
- Returns:
Instance of the trained model.
- 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
, theExecContext
‘ssymbol
is used.
- Returns:
numpy.ndarray
containing the sequence of model predictions up to the current bar. Sorted in ascending chronological order.
Sells all long shares of
ExecContext.symbol
.
- short_pos(symbol: str | None = None) Position | None [source]
Retrieves a current short
pybroker.portfolio.Position
for asymbol
.- Parameters:
symbol – Ticker symbol of the position to return. If
None
, theExecContext
‘ssymbol
is used. Defaults toNone
.- Returns:
pybroker.portfolio.Position
if one exists, otherwiseNone
.
- to_result() ExecResult | None [source]
Creates an
ExecResult
from the data set onExecContext
.
- 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
.- date
Timestamp of the bar that was used for the execution.
- Type:
- 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 thepybroker.portfolio.Portfolio
is specified bypybroker.config.StrategyConfig.max_long_positions
andpybroker.config.StrategyConfig.max_short_positions
respectively. Buy and sell signals are ranked separately byscore
.- 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
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
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.Entry
s.- Type:
frozenset[pybroker.portfolio.Stop] | None
- short_stops
Stops for short
pybroker.portfolio.Entry
s.- Type:
frozenset[pybroker.portfolio.Stop] | None
- cover
Whether
buy_shares
are used to cover a short position. IfTrue
, the resulting buy order will be placed before sell orders.- Type:
- pending_order_id
ID of
pybroker.scope.PendingOrder
that was created.- Type:
int | 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.
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
forsymbol
.- Type:
- type
buy
orsell
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.
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
ofExecSignal
s containing data for buy and sell signals.
- set_exec_ctx_data(ctx: ExecContext, date: datetime64)[source]
Sets data on an
ExecContext
instance.- Parameters:
ctx –
ExecContext
.date – Current bar’s date.
- 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:
ctx –
PosSizeContext
.buy_results –
ExecResult
s of buy signals.sell_results –
ExecResult
s of sell signals.