pybroker.model module
Contains model related functionality.
- class CachedModel(model: Any, input_cols: tuple[str] | None, lag_columns: tuple[str, ...] | None = None)[source]
Bases:
NamedTupleStores cached model data.
- input_cols
Names of the columns to be used as input for the model when making predictions.
- lag_columns
Names of the columns that lag features were built from at training time, in feature block order.
Nonewhen the model was not trained withlags, and when loading a model cached before this field existed.
- class IntervalBoundModel(source: ModelSource, intervals: frozenset[TimeframeInterval])[source]
Bases:
NamedTupleA
ModelSourcebound to one or more compression intervals, returned byModelSource.intervals()and passed to themodelsparameter ofpybroker.strategy.Strategy.add_execution().- intervals: frozenset[int | Literal['daily', 'weekly', 'monthly', 'quarterly', 'yearly'] | str]
Normalized
TimeframeIntervals the model is trained on. May include the literal'base'for the base timeframe.
- source: ModelSource
The bound
ModelSource.
- class LagSeriesKey(symbol: str, column: str, lag: int, interval: str | None = None)[source]
Bases:
objectInternal cache key for a full-history lagged series.
- class ModelInput(columns: tuple[str, ...], arrays: dict[str, ndarray], dates: ndarray, lag_features: ndarray | None = None, lags: int | None = None, lag_columns: tuple[str, ...] | None = None)[source]
Bases:
objectInternal numpy-backed model input with optional lag feature metadata.
Not part of the public API. User-facing code receives
pandas.DataFrameinstances materialized viato_dataframe(), with any lag feature matrix passed explicitly as a separatenumpy.ndarrayargument.- drop_lag_warmup() ModelInput[source]
Drops the leading rows whose lag features are not yet defined.
Only each symbol’s warmup region is trimmed. Dropping every row with a NaN lag feature would also remove rows from the middle of the series whenever a lag column is sparse – an event column registered with
pybroker.scope.register_columns()is NaN except on the bars it fires, and an all-NaNvolumecolumn is routine for index, FX and CFD series. Either silently shrinks the training set, or empties it.Pooled input stacks one block per symbol, so each block carries its own warmup at its own offset. Trimming only the front of the matrix would leave every block after the first with its NaN rows intact, which
sklearn.fitrejects outright.
- lag_warmup_len() int[source]
Returns how many leading rows have undefined lag features.
These rows cannot be handed to an estimator: sklearn rejects NaN outright, and a NaN-tolerant predict_fn quietly produces a prediction from features that do not exist yet.
- select_columns(columns: tuple[str, ...]) ModelInput[source]
Returns a view restricted to
columns.
- slice(end_index: int | None = None) ModelInput[source]
Returns a row slice sharing backing array memory.
- class ModelLoader(name: str, load_fn: Callable[[...], Any | tuple[Any, Iterable[str]]], indicator_names: Iterable[str], input_data_fn: Callable[[DataFrame], DataFrame] | None, predict_fn: Callable[[Any, DataFrame | NDArray], NDArray] | None, pooled: bool, kwargs: dict[str, Any], lags: int | None = None, lag_cols: tuple[str, ...] = (), per_bar: bool = False)[source]
Bases:
ModelSourceLoads a pre-trained model.
- Parameters:
name – Name of model.
load_fn –
Callable[[symbol: str, train_start_date: datetime, train_end_date: datetime, ...], DataFrame]used to load and return a pre-trained model. This is expected to return either a trained model instance, or a tuple containing a trained model instance and aIterableof column names to to be used as input for the model when making predictions.indicator_names –
Iterableof names ofpybroker.indicator.Indicators used as features of the model.input_data_fn –
Callable[[DataFrame], DataFrame]for preprocessing input data passed to the model when making predictions. If set,input_data_fnwill be called with apandas.DataFramecontaining all test data.predict_fn –
Callable[[Model, DataFrame], ndarray]that overrides calling the model’s defaultpredictfunction. If set,predict_fnwill be called with the trained model and apandas.DataFramecontaining all test data. Whenlagsis set, it is instead called with the lag feature matrix (numpy.ndarray) in place of the DataFrame.pooled – If
True, the model is trained once per execution using combined multi-symbol data. Defaults toFalse.kwargs –
dictof kwargs to pass toload_fn.
- __call__(symbol: str, train_start_date: datetime, train_end_date: datetime) Any | tuple[Any, Iterable[str]][source]
Loads pre-trained model.
- Parameters:
symbol – Ticker symbol for loading the pre-trained model.
train_start_date – Start date of training window.
train_end_date – End date of training window.
- Returns:
Pre-trained model.
- class ModelSource(name: str, indicator_names: Iterable[str], input_data_fn: Callable[[DataFrame], DataFrame] | None, predict_fn: Callable[[Any, DataFrame | NDArray], NDArray] | None, pooled: bool, kwargs: dict[str, Any], lags: int | None = None, lag_cols: tuple[str, ...] = (), per_bar: bool = False)[source]
Bases:
objectBase class of a model source. A model source provides a model instance either by training one or by loading a pre-trained model.
- Parameters:
name – Name of model.
indicator_names –
Iterableof names ofpybroker.indicator.Indicators used as features of the model.input_data_fn –
Callable[[DataFrame], DataFrame]for preprocessing input data passed to the model when making predictions. If set,input_data_fnwill be called with apandas.DataFramecontaining all test data.predict_fn –
Callable[[Model, DataFrame], ndarray]that overrides calling the model’s defaultpredictfunction. If set,predict_fnwill be called with the trained model and apandas.DataFramecontaining all test data. Whenlagsis set, it is instead called with the lag feature matrix (numpy.ndarray) in place of the DataFrame.lags – Number of lagged values to include for each column in
lag_cols, producing a(n_rows, len(lag_cols) * (lags + 1))feature matrix that is passed totrain_fnaslag_train/lag_testand topredict_fnin place of the input DataFrame, rather than added as columns.lag_cols – Columns to compute lagged values for. Defaults to the data columns of the training data, excluding
dateandsymbol; indicators are lagged only when named here.per_bar – If
True,predict_fnis called once per bar with input truncated to rows up to and including the current bar.pooled – If
True, the model is trained once per execution using combined multi-symbol data. Defaults toFalse.kwargs –
dictof additional kwargs.
- intervals(*intervals: int | Literal['daily', 'weekly', 'monthly', 'quarterly', 'yearly'] | str) IntervalBoundModel[source]
Binds this model to one or more compression intervals for use with
pybroker.strategy.Strategy.add_execution().A bound model is trained on exactly the listed intervals’ compressed bars, together with any indicators registered on it. Binding replaces the default base-timeframe training; include the literal
'base'inintervalsto also train the model on the base timeframe. Per-interval predictions are read withpybroker.context.IntervalContext.preds(). Bound intervals are automatically made available throughpybroker.context.ExecContext.interval()without also declaring them in theintervalsparameter ofadd_execution():trend = pybroker.model("trend", train_fn, indicators=[sma_10]) strategy.add_execution( fn, "SPY", models=trend.intervals("base", "weekly") )
Only trainable models support interval binding. Calling this on a pretrained model (a
ModelLoader) raisesValueError.- Parameters:
intervals – One or more
TimeframeIntervals to train this model on, each strictly coarser than the base bar spacing of the backtest data, or the literal'base'for the base timeframe.- Returns:
IntervalBoundModelbinding this model tointervals.
- prepare_input_data(df: DataFrame) DataFrame[source]
Prepares a
pandas.DataFrameof input data for passing to a model when making predictions. If set, theinput_data_fnis used to preprocess the input data. IfFalse, then indicator columns indfare used as input features.
- class ModelTrainer(name: str, train_fn: Callable[[...], Any | tuple[Any, Iterable[str]]], indicator_names: Iterable[str], input_data_fn: Callable[[DataFrame], DataFrame] | None, predict_fn: Callable[[Any, DataFrame | NDArray], NDArray] | None, pooled: bool, kwargs: dict[str, Any], lags: int | None = None, lag_cols: tuple[str, ...] = (), per_bar: bool = False)[source]
Bases:
ModelSourceTrains a model.
- Parameters:
name – Name of model.
train_fn – When
pooledisFalse,Callable[[symbol: str, train_data: DataFrame, test_data: DataFrame, ...], DataFrame]. WhenpooledisTrue,Callable[[symbols: Sequence[str], train_data: DataFrame, test_data: DataFrame, ...], DataFrame]. Whenlagsis set,train_fnis additionally called withlag_train=andlag_test=keyword arguments holding the lag feature matrices aligned one row pertrain_data/test_datarow, and must accept both. This is expected to return either a trained model instance, or a tuple containing a trained model instance and aIterableof column names to to be used as input for the model when making predictions.indicator_names –
Iterableof names ofpybroker.indicator.Indicators used as features of the model.input_data_fn –
Callable[[DataFrame], DataFrame]for preprocessing input data passed to the model when making predictions. If set,input_data_fnwill be called with apandas.DataFramecontaining all test data.predict_fn –
Callable[[Model, DataFrame], ndarray]that overrides calling the model’s defaultpredictfunction. If set,predict_fnwill be called with the trained model and apandas.DataFramecontaining all test data. Whenlagsis set, it is instead called with the lag feature matrix (numpy.ndarray) in place of the DataFrame.pooled – If
True, the model is trained once per execution using combined multi-symbol data. Defaults toFalse.kwargs –
dictof kwargs to pass totrain_fn.
- __call__(symbol: str, train_data: DataFrame, test_data: DataFrame, *, lag_train: NDArray | None = None, lag_test: NDArray | None = None) Any | tuple[Any, Iterable[str]][source]
Trains model per symbol.
- Parameters:
symbol – Ticker symbol of model (models are trained per symbol).
train_data – Train data.
test_data – Test data.
lag_train – Lag feature matrix aligned one row per
train_datarow. Passed totrain_fnaslag_train=when the model is registered withlags.lag_test – Lag feature matrix aligned one row per
test_datarow. Passed totrain_fnaslag_test=when the model is registered withlags.
- Returns:
Trained model.
- train_pooled(symbols: Sequence[str], train_data: DataFrame, test_data: DataFrame, *, lag_train: NDArray | None = None, lag_test: NDArray | None = None) Any | tuple[Any, Iterable[str]][source]
Trains model using combined multi-symbol data.
- Parameters:
symbols – Ticker symbols of the pooled group, sorted in ascending order to match the order that symbol blocks appear in
train_dataandtest_data. A listed symbol can have no rows in a frame, such as whenlagsdrops all of its rows with the lag warmup.train_data – Train data containing a
symbolcolumn.test_data – Test data containing a
symbolcolumn.lag_train – Lag feature matrix aligned one row per
train_datarow. Passed totrain_fnaslag_train=when the model is registered withlags.lag_test – Lag feature matrix aligned one row per
test_datarow. Passed totrain_fnaslag_test=when the model is registered withlags.
- Returns:
Trained model.
- class ModelsMixin[source]
Bases:
objectMixin implementing model related functionality.
- train_models(model_syms: Iterable[ModelSymbol], train_data: DataFrame, test_data: DataFrame, indicator_data: Mapping[IndicatorSymbol, Series], cache_date_fields: CacheDateFields, parallel_models: bool = False, pooled_model_groups: Mapping[tuple[str, int], frozenset[str]] | None = None, interval_data: IntervalData | None = None, *, history_store: SymbolArrayStore | None = None, train_store: SymbolArrayStore | None = None, test_store: SymbolArrayStore | None = None, lookahead: int = 1) dict[ModelSymbol, TrainedModel][source]
Trains models for the provided
pybroker.common.ModelSymbolpairs.- Parameters:
model_syms –
Iterableofpybroker.common.ModelSymbolpairs of models to train.train_data –
pandas.DataFrameof training data.test_data –
pandas.DataFrameof test data.indicator_data –
Mappingofpybroker.common.IndicatorSymbolpairs topandas.Seriesofpybroker.indicator.Indicatorvalues.cache_date_fields – Date fields used to key cache data.
parallel_models – If
True,ModelTrainermodels are trained in parallel using multiple processes. Defaults toFalse.pooled_model_groups –
Mappingof(model_name, execution_id)pairs tofrozenset[str]of symbols for pooled training. Defaults toNone.lookahead – Number of bars in the future of the target prediction, expressed in the bars of the timeframe each model is fitted on: a model bound to an interval holds out
lookaheadcompressed bars between its train and test rows. Defaults to1.
- Returns:
dictmapping eachpybroker.common.ModelSymbolpair to apybroker.common.TrainedModel.
- apply_lags_to_model_input(model_input: ModelInput, lag_columns: tuple[str, ...], lags: int, lag_cache: dict[LagSeriesKey, ndarray], symbol: str, history_dates: ndarray, interval: str | None = None) ModelInput[source]
Attaches lag feature metadata to
model_input.
- apply_lags_to_model_input_pooled(model_input: ModelInput, lag_columns: tuple[str, ...], lags: int, lag_cache: dict[LagSeriesKey, ndarray], history_dates_by_symbol: dict[str, ndarray], symbols: Iterable[str], interval: str | None = None) ModelInput[source]
Attaches lag feature metadata to pooled
model_input.
- apply_prepare_input_data(model_input: ModelInput, prepare_fn: Callable[[DataFrame], DataFrame]) ModelInput[source]
Applies a DataFrame-only prepare function to
model_input.
- build_lag_feature_matrix(symbol: str, columns: tuple[str, ...], lags: int, row_dates: ndarray, history_dates: ndarray, lag_cache: dict[LagSeriesKey, ndarray], interval: str | None = None) ndarray[source]
Builds a lag-expanded feature matrix from numpy arrays.
Returns a matrix of shape
(len(row_dates), len(columns) * (lags + 1)), laid out as one contiguous block per column, each block holding the column’s current value followed by lags 1 throughlags.
- build_lag_feature_matrix_pooled(sym_col: ndarray, columns: tuple[str, ...], lags: int, row_dates: ndarray, history_dates_by_symbol: dict[str, ndarray], lag_cache: dict[LagSeriesKey, ndarray], symbols: Iterable[str], interval: str | None = None) ndarray[source]
Builds a lag-expanded feature matrix for pooled multi-symbol data.
- cached_stacked_lags(cache: dict[LagSeriesKey, ndarray], symbol: str, col: str, lags: int, interval: str | None = None) ndarray | None[source]
Returns a cached stacked array deep enough for
lags, elseNone.
- compute_lag_series_cache(df: DataFrame, symbols: Iterable[str], columns: tuple[str, ...], lags: int) dict[LagSeriesKey, ndarray][source]
Computes full-history lag arrays for daily/base bars.
- history_date_offset(history_dates: ndarray, row_dates: ndarray) int[source]
Returns the start index of
row_datesinsidehistory_dates.
- merge_interval_lag_series_cache(cache: dict[LagSeriesKey, ndarray], symbols: Iterable[str], columns: tuple[str, ...], lags: int, interval: str, bars_by_symbol, arrays_by_symbol=None) dict[LagSeriesKey, ndarray][source]
Adds full-history interval lag arrays into
cache.pybroker.interval.CompressedBarsholds data columns only, soarrays_by_symbolsupplies columns the bars cannot – indicator values in particular – and is consulted first when given.
- merge_lag_series_cache(cache: dict[LagSeriesKey, ndarray], history_df: DataFrame, symbols: Iterable[str], columns: tuple[str, ...], lags: int, history_dates: dict[str, ndarray] | None = None) dict[LagSeriesKey, ndarray][source]
Adds full-history lag arrays for
columnsintocache.
- merge_lag_series_cache_from_arrays(cache: dict[LagSeriesKey, ndarray], symbol: str, columns: tuple[str, ...], lags: int, history_dates: ndarray, column_arrays: Mapping[str, ndarray]) None[source]
Adds full-history lag arrays built from numpy column data.
- merge_lag_series_cache_from_store(cache: dict[LagSeriesKey, ndarray], store: SymbolArrayStore, symbols: Iterable[str], columns: tuple[str, ...], lags: int, history_dates: dict[str, ndarray] | None = None, indicators: tuple[str, ...] = (), indicator_data: Mapping[IndicatorSymbol, Series] | None = None) dict[LagSeriesKey, ndarray][source]
Adds full-history lag arrays from a
pybroker.scope.SymbolArrayStore.A
pybroker.scope.SymbolArrayStoreholds data columns only, so indicator values are aligned onto the store’s dates fromindicator_data, which covers each symbol’s full history. Lagging an indicator would otherwise fail even though it is a column of the model input.
- model(name: str, fn: Callable[[...], Any | tuple[Any, Iterable[str]]], indicators: Iterable[Indicator] | None = None, lags: int | None = None, lag_cols: Iterable[str | Indicator] | None = None, per_bar: bool = False, input_data_fn: Callable[[DataFrame], DataFrame] | None = None, predict_fn: Callable[[Any, DataFrame | NDArray], NDArray] | None = None, pretrained: bool = False, pooled: bool = False, **kwargs) ModelSource[source]
Creates a
ModelSourceinstance and registers it globally withname.- Parameters:
name – Name for referencing the model globally.
fn –
Callableused to either train or load a model instance. If for training withpooled=False, thenfnhas signatureCallable[[symbol: str, train_data: DataFrame, test_data: DataFrame, ...], DataFrame]. If for training withpooled=True, thenfnhas signatureCallable[[symbols: Sequence[str], train_data: DataFrame, test_data: DataFrame, ...], DataFrame]wheresymbolscontains the pooled symbols sorted in ascending order, and both frames contain asymbolcolumn with each symbol’s rows grouped together in that order. A listed symbol can have no rows in a frame, such as whenlagsdrops all of its rows with the lag warmup. If for loading, thenfnhas signatureCallable[[symbol: str, train_start_date: datetime, train_end_date: datetime, ...], DataFrame]. Whenlagsis set, a trainingfnis additionally called withlag_train=andlag_test=keyword arguments holding the prebuilt lag feature matrices, and must accept both. This is expected to return either a trained model instance, or a tuple containing a trained model instance and aIterableof column names to to be used as input for the model when making predictions. When only a model instance is returned, columns from the training DataFrame are used for prediction. For pooled models, thesymbolcolumn is omitted from inferred prediction columns.indicators –
Iterableofpybroker.indicator.Indicators used as features of the model.lags – Number of lagged values to include for each column in
lag_cols. The lagged values are built into a feature matrix of shape(n_rows, len(lag_cols) * (lags + 1)): one contiguous block per column inlag_colsdeclaration order, each block holding the column’s current value followed by lags1throughlags, where lag1is the value from the previous bar. The matrix is passed to a trainingfnas thelag_trainandlag_testkeyword arguments, aligned one row pertrain_data/test_datarow, and topredict_fn(or the model’s defaultpredict) in place of the input DataFrame. Because the current bar’s value is the first feature of each block, the intended prediction target is the next bar — using the current bar’s value as the target would leak it. Lag data is kept separate from model input rather than added as columns, so the inputpandas.DataFrameis never widened or copied. Lagged values are computed from each symbol’s full history, so rows at the start of a test window use real values carried over from the preceding train window instead ofNaN. Rows whose lags are undefined are dropped from training data only.lag_cols – Column names and/or
pybroker.indicator.Indicators to compute lagged values for.pybroker.indicator.Indicators passed here are added toindicators. Declaration order sets the order of the feature blocks. Defaults to the data columns of the training data, excludingdateandsymbol; indicators are lagged only when named here.per_bar – If
True,predict_fnis called once per bar with input truncated to rows up to and including the current bar, and must return a scalar prediction for that bar. Withlags, the input is the lag feature matrix truncated the same way, with the current bar as its last row. Use for models that are refit or updated every bar, such as GARCH or state space models. Note this makes one model call per bar per symbol, which is far slower than a single vectorizedpredict_fncall over the whole test window. Requirespredict_fnand is not supported withpooled=True.input_data_fn –
Callable[[DataFrame], DataFrame]for preprocessing input data passed to the model when making predictions. If set,input_data_fnwill be called with apandas.DataFramecontaining all test data, including whenper_bar=True. It must return one row per bar; adding or dropping rows would misalign predictions with bars and raises aValueError. For models registered withlags, it shapespybroker.context.ExecContext.input()only, since predictions are made from the lag feature matrix.predict_fn –
Callable[[Model, DataFrame], ndarray]that overrides calling the model’s defaultpredictfunction. If set,predict_fnwill be called with the trained model and apandas.DataFramecontaining all test data. Whenlagsis set, it is instead called with the lag feature matrix (numpy.ndarray) in place of the DataFrame. Whenper_bar=True,predict_fnreceives input rows up to and including the current bar and must return a scalar prediction.pretrained – If
True, thenfnis used to load and return a pre-trained model. IfFalse,fnis used to train and return a new model. Defaults toFalse.pooled – If
True, the model is trained once per execution using combined multi-symbol data. Defaults toFalse.**kwargs – Additional arguments to pass to
fn.
- Returns:
ModelSourceinstance.
- model_input_from_arrays(columns: tuple[str, ...], arrays: dict[str, ndarray], dates: ndarray) ModelInput[source]
Builds a
ModelInputfrom column arrays.
- model_input_from_frame(df: DataFrame, columns: tuple[str, ...] | None = None, dates: ndarray | None = None) ModelInput[source]
Builds a
ModelInputfrom a DataFrame without copying columns.