pybroker.common module
Contains common classes and utilities.
- class BarData(date: ndarray[tuple[Any, ...], dtype[datetime64]], open: ndarray[tuple[Any, ...], dtype[float64]], high: ndarray[tuple[Any, ...], dtype[float64]], low: ndarray[tuple[Any, ...], dtype[float64]], close: ndarray[tuple[Any, ...], dtype[float64]], volume: ndarray[tuple[Any, ...], dtype[float64]] | None, vwap: ndarray[tuple[Any, ...], dtype[float64]] | None, **kwargs)[source]
Bases:
objectContains data for a series of bars. Each field is a
numpy.ndarraythat contains bar values in the series. The values are sorted in ascending chronological order.- Parameters:
date – Timestamps of each bar.
open – Open prices.
high – High prices.
low – Low prices.
close – Close prices.
volume – Trading volumes.
vwap – Volume-weighted average prices (VWAP).
**kwargs – Custom data fields.
- class DataCol(*values)[source]
Bases:
EnumDefault data column names.
- DATE = 'date'
- SYMBOL = 'symbol'
- VOLUME = 'volume'
- VWAP = 'vwap'
- class Day(*values)[source]
Bases:
EnumEnumeration of days.
- FRI = 4
- MON = 0
- SAT = 5
- SUN = 6
- THURS = 3
- TUES = 1
- WEDS = 2
- class FeeInfo(symbol: str, shares: Decimal, fill_price: Decimal, order_type: Literal['buy', 'sell'])[source]
Bases:
NamedTupleContains info for custom fee calculations.
Number of shares in order.
- Type:
- fill_price
Fill price of order.
- Type:
- order_type
Type of order, either “buy” or “sell”.
- Type:
Literal[‘buy’, ‘sell’]
- class FeeMode(*values)[source]
Bases:
EnumBrokerage fee mode to use for backtesting.
- ORDER_PERCENT
Fee is a percentage of order amount, where order amount is fill_price * shares.
- PER_ORDER
Fee is a constant amount per order.
- PER_SHARE
Fee is a constant amount per share in order.
- class IndicatorSymbol(ind_name: str, symbol: str)[source]
Bases:
NamedTuplepybroker.indicator.Indicator/symbol identifier.
- class ModelSymbol(model_name: str, symbol: str)[source]
Bases:
NamedTuplepybroker.model.ModelSource/symbol identifier.
- class OrderType(*values)[source]
Bases:
EnumOrder type classifications.
- MARKET
Market order.
- LIMIT
Limit order.
- STOP_BAR
Bar stop triggered order.
- STOP_LOSS
Stop loss triggered order.
- STOP_PROFIT
Take profit triggered order.
- STOP_TRAILING
Trailing stop triggered order.
- class PositionIntent(*values)[source]
Bases:
EnumPosition intent of an order.
- BUY_TO_OPEN
Buy to open a long position.
- BUY_TO_CLOSE
Buy to close a short position.
- SELL_TO_OPEN
Sell to open a short position.
- SELL_TO_CLOSE
Sell to close a long position.
- class PositionMode(*values)[source]
Bases:
EnumPosition mode for backtesting.
- DEFAULT
Long and short positions.
- LONG_ONLY
Long-only positions.
- SHORT_ONLY
Short-only positions.
- class PriceType(*values)[source]
Bases:
EnumEnumeration of price types used to specify fill price with
pybroker.context.ExecContext.- OPEN
Open price of the current bar.
- LOW
Low price of the current bar.
- HIGH
High price of the current bar.
- CLOSE
Close price of the current bar.
- MIDDLE
Midpoint between low price and high price of the current bar.
- AVERAGE
Average of open, low, high, and close prices of the current bar.
- class StopType(*values)[source]
Bases:
EnumStop types.
- BAR
Stop that triggers after n bars.
- LOSS
Stop loss.
- PROFIT
Take profit.
- TRAILING
Trailing stop loss.
- SymbolSelector
Chooses which ticker symbols an execution trades, per walkforward window.
Passed to
pybroker.strategy.Strategy.add_execution()in place of a fixed symbol list. Called once per walkforward window with the window’s trainingpandas.DataFrame— never with test data — and must return a non-empty sequence of unique symbols that the frame contains. Any sequence ofstris accepted, including alist,tuple,pandas.Index, ornumpy.ndarray, soranked.nlargest(10).indexworks as written.Notes
A training window is required.
pybroker.strategy.Strategy.backtest()andtrain_size=0raiseValueError, since selecting from test data would look ahead at the bars about to be traded.The candidate universe must come from a
pandas.DataFramedata source; apybroker.data.DataSourcecannot be used, because the symbols to query are not known until a window is split.shuffle=Truerandomizes the training frame’s row order, so a selector that depends on bars being in date order should not be combined with it.When a window drops a symbol that is still held, the position is closed at the first bar of the new test window using
pybroker.config.StrategyConfig.exit_sell_fill_priceandpybroker.config.StrategyConfig.exit_cover_fill_price. A symbol that has no bars left at all is closed at its final bar instead.
- class TrainedModel(name: str, instance: Any, predict_fn: Callable[[Any, DataFrame | ndarray[tuple[Any, ...], dtype[_ScalarT]]], ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None, input_cols: tuple[str] | None, per_bar: bool = False, lag_columns: tuple[str, ...] | None = None)[source]
Bases:
NamedTupleTrained model/symbol identifier.
- instance
Trained model instance.
- Type:
Any
- predict_fn
Callablethat overrides calling the model’s defaultpredictfunction. For models trained withlags, it is called with the lag feature matrix (numpy.ndarray) instead of apandas.DataFrame.- Type:
Callable[[Any, pandas.DataFrame | numpy.ndarray[tuple[Any, …], numpy.dtype[numpy._typing._array_like._ScalarT]]], numpy.ndarray[tuple[Any, …], numpy.dtype[numpy._typing._array_like._ScalarT]]] | None
- input_cols
Names of the columns to be used as input for the model when making predictions.
- bars_to_df(bar_data: BarData) DataFrame[source]
Converts a
BarDatainstance to apandas.DataFrame.- Parameters:
bar_data –
BarDatato convert.- Returns:
pandas.DataFramecontaining a column for every field inbar_data, including custom data fields. Thevolumeandvwapcolumns are included only when set.
- get_unique_sorted_dates(col: Series) Sequence[datetime64][source]
Returns sorted unique values from a DataFrame column of dates.
- get_unique_sorted_dates_array(dates: Series | ndarray[tuple[Any, ...], dtype[datetime64]] | Sequence[datetime64]) ndarray[tuple[Any, ...], dtype[datetime64]][source]
Returns sorted unique dates from a numpy date array or Series.
- parse_timeframe(timeframe: str) list[tuple[int, str]][source]
Parses timeframe string with the following units:
"s"/"sec": seconds"m"/"min": minutes"h"/"hour": hours"d"/"day": days"w"/"week": weeks
An example timeframe string is
1h 30m.- Returns:
listoftuple[int, str], where each tuple contains anintvalue andstrunit of one of the following:sec,min,hour,day,week.
- quantize(df: DataFrame, col: str, round: bool) Series[source]
Quantizes a
pandas.DataFramecolumn by rounding values to the nearest cent.- Returns:
The quantized column converted to
floatvalues.
- to_datetime(date: str | datetime | datetime64 | Timestamp) datetime[source]
Converts
datetodatetime.datetime.
- to_seconds(timeframe: str | None) int[source]
Converts a timeframe string to seconds, where
timeframesupports the following units:"s"/"sec": seconds"m"/"min": minutes"h"/"hour": hours"d"/"day": days"w"/"week": weeks
An example timeframe string is
1h 30m.- Returns:
The converted number of seconds.
- verify_data_source_columns(df: DataFrame)[source]
Verifies that a
pandas.DataFramecontains all of the columns required by apybroker.data.DataSource.