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:
objectContains 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_delayandpybroker.config.StrategyConfig.sell_delay.- config
- 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.
- buy_timeout_bars
Number of bars to retry an unfilled buy limit order after the first attempt.
Nonefor a single attempt,-1for 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.
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.
Nonefor a single attempt,-1for 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
symbolwhen ranking buy and cover signals. Orders are placed for symbols with the highestlong_scorevalues, where the number of long positions held at any time in thepybroker.portfolio.Portfoliois specified bypybroker.strategy.Strategy.set_max_long_positions(). When rotation is enabled withpybroker.strategy.Strategy.enable_rotation(),long_scoredrives long rotation and orders set during anpybroker.strategy.Executionare ignored.
- short_score
Score used to rank
symbolwhen ranking sell signals. Orders are placed for symbols with the highestshort_scorevalues, where the number of short positions held at any time in thepybroker.portfolio.Portfoliois specified bypybroker.strategy.Strategy.set_max_short_positions(). When rotation is enabled withpybroker.strategy.Strategy.enable_rotation(),short_scoredrives short rotation and orders set during anpybroker.strategy.Executionare ignored.
- session
dictused 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.PriceTypeto use for the stop loss exit. If set, the stop is checked against theexit_priceand exits at theexit_pricewhen 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.PriceTypeto use for the profit stop exit. If set, the stop is checked against theexit_priceand exits at theexit_pricewhen 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.PriceTypeto use for the trailing stop exit. If set, the stop is checked against theexit_priceand exits at theexit_pricewhen triggered.
- property buying_power: Decimal
Available buying power for long and short orders given
pybroker.config.StrategyConfig.leverage.This is what the
pybroker.portfolio.Portfolioclamps 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.
Calculates the number of shares given a
target_sizeallocation and shareprice.- Parameters:
target_size – Proportion of deployable capital used to calculate the number of shares, where the max
target_sizeis1. For example, atarget_sizeof0.1would represent 10% of deployable capital.price – Share price used to calculate the number of shares. If
None, the share price of theExecContext‘ssymbolis used.cash – Capital used to calculate the number of shares. If
None, deployable capital is used, defined as portfolio equity multiplied bypybroker.config.StrategyConfig.leverage. The resulting order is still capped bybuying_powerwhen it is placed.
- Returns:
Number of shares given
target_sizeand shareprice. Ifpybroker.config.StrategyConfig.enable_fractional_sharesisTrue, then a Decimal is returned.
- cancel_all_pending_orders(symbol: str | None = None)[source]
Cancels all
pybroker.scope.PendingOrders forsymbol. WhensymbolisNone, all pending orders are canceled.
- cancel_pending_order(order_id: int) bool[source]
Cancels a
pybroker.scope.PendingOrderwithorder_id.
- cancel_stop(stop_id: int) bool[source]
Cancels a
pybroker.portfolio.Stopwithstop_id.
- cancel_stops(val: str | Position | Entry, stop_type: StopType | None = None)[source]
Cancels
pybroker.portfolio.Stops.- Parameters:
val – Ticker symbol,
pybroker.portfolio.Position, orpybroker.portfolio.Entryfor which to cancel stops.stop_type –
pybroker.common.StopType.
- property cash: Decimal
Total cash currently held in the
pybroker.portfolio.Portfolio.
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[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 inpybroker.common.BarData.
- Returns:
If
colisNone, apybroker.common.BarDatainstance containing data of all bars up to the current one. Otherwise, annumpy.ndarraycontaining values of the columncol.
- hyperparam(name: str) Any[source]
Returns a hyperparameter value for this execution.
The name must have been attached via
hyperparams=[...]onpybroker.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, theExecContext‘ssymbolis used.
- Returns:
numpy.ndarrayof 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‘ssymbolis used.
- Returns:
pandas.DataFramecontaining 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.intervalmust match a value this execution declared withintervalsinpybroker.strategy.Strategy.add_execution(), or an interval bound to one of the execution’s models or indicators withpybroker.model.ModelSource.intervals()/pybroker.indicator.Indicator.intervals(). Intervals are scoped per execution: reading an interval that another execution declared raisesValueError, the same wayhyperparam()is gated by the execution’shyperparams. The sameTimeframeIntervalforms 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.IntervalContextexposing 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.Positionfor asymbol.- Parameters:
symbol – Ticker symbol of the position to return. If
None, theExecContext‘ssymbolis used. Defaults toNone.- Returns:
pybroker.portfolio.Positionif one exists, otherwiseNone.
- 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:
Iteratorof currently held longpybroker.portfolio.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, theExecContext‘ssymbolis used.
- Returns:
Instance of the trained model.
- orders() Iterator[Order][source]
Iteratorof allpybroker.portfolio.Orders 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.Positionfor asymbol.- Parameters:
symbol – Ticker symbol of the position to return.
pos_type – Specifies whether to return a
longorshortposition.
- Returns:
pybroker.portfolio.Positionif 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, bothlongandshortpositions are returned.
- Returns:
Iteratorof currently heldpybroker.portfolio.Positions.
- 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, theExecContext‘ssymbolis used.
- Returns:
numpy.ndarraycontaining the sequence of model predictions up to the current bar. Sorted in ascending chronological order.
Sells all long shares of
ExecContext.symbol.
Sets orders to reach a target allocation for long or short exposure.
Calculates the number of shares needed to reach
targetusingcalc_target_shares().- Parameters:
target – Target allocation as a fraction of deployable capital, defined as portfolio equity multiplied by
pybroker.config.StrategyConfig.leverage. The maxtargetis1.dir – Exposure direction to rebalance.
"long"setsbuy_sharesorsell_shares."short"setssell_sharesto increase short exposure orcover_sharesto decrease it.
- short_pos(symbol: str | None = None) Position | None[source]
Retrieves a current short
pybroker.portfolio.Positionfor asymbol.- Parameters:
symbol – Ticker symbol of the position to return. If
None, theExecContext‘ssymbolis used. Defaults toNone.- Returns:
pybroker.portfolio.Positionif one exists, otherwiseNone.
- 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:
Iteratorof currently held shortpybroker.portfolio.Positions.
- to_result() ExecResult | None[source]
Creates an
ExecResultfrom the data set onExecContext.
- 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]
Iteratorof allpybroker.portfolio.Trades that have been completed.
- 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:
objectHolds 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]
- long_score
Score used to rank
symbolwhen ranking buy and cover signals. Orders are placed for symbols with the highestlong_scorevalues, where the number of long positions held at any time in thepybroker.portfolio.Portfoliois specified bypybroker.strategy.Strategy.set_max_long_positions(). When rotation is enabled withpybroker.strategy.Strategy.enable_rotation(),long_scoredrives long rotation and orders set during anpybroker.strategy.Executionare ignored.- Type:
float | None
- short_score
Score used to rank
symbolwhen ranking sell signals. Orders are placed for symbols with the highestshort_scorevalues, where the number of short positions held at any time in thepybroker.portfolio.Portfoliois specified bypybroker.strategy.Strategy.set_max_short_positions(). When rotation is enabled withpybroker.strategy.Strategy.enable_rotation(),short_scoredrives short rotation and orders set during anpybroker.strategy.Executionare 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
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.
Nonefor a single attempt,-1for indefinite persistence, or a positive integer for a limited number of retry bars.- Type:
int | 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
- sell_timeout_bars
Number of bars to retry an unfilled sell limit order after the first attempt.
Nonefor a single attempt,-1for 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_sharesare 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.PendingOrderthat was created.- Type:
int | None
- exit_pos_type
Type of the
pybroker.portfolio.Positionthis order exits, eitherlongorshort, orNonewhen the order is not an exit. Set byExecContext.sell_all_shares(),ExecContext.cover_all_shares(), andExecContext.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:
objectRead-only view of compressed bar data for a coarser interval.
- indicator(name: str) ndarray[tuple[Any, ...], dtype[float64]][source]
Returns indicator values on the compressed interval.
- class RotationContext(ctxs: Mapping[str, ExecContext], portfolio: Portfolio, long_ranks: Mapping[str, int], short_ranks: Mapping[str, int], config: StrategyConfig)[source]
Bases:
objectContext passed to a rotation sizer set with
pybroker.strategy.Strategy.enable_rotation().- ctxs
Mappingof all ticker symbols toExecContexts.- Type:
Mapping[str, pybroker.context.ExecContext]
- portfolio
- long_ranks
Rankings computed from rankable
ExecContext.long_scorevalues, where1is the highest score.
- short_ranks
Rankings computed from rankable
ExecContext.short_scorevalues, where1is the highest score.
- set_exec_ctx_data(ctx: ExecContext, date: datetime64)[source]
Sets data on an
ExecContextinstance.- Parameters:
ctx –
ExecContext.date – Current bar’s date.