pybroker.strategy module
Contains implementation for backtesting trading strategies.
- class BacktestMixin[源代码]
基类:
object
Mixin implementing backtesting functionality.
- backtest_executions(config: StrategyConfig, executions: set[Execution], before_exec_fn: Callable[[Mapping[str, ExecContext]], None] | None, after_exec_fn: Callable[[Mapping[str, ExecContext]], None] | None, sessions: Mapping[str, MutableMapping], models: Mapping[ModelSymbol, TrainedModel], indicator_data: Mapping[IndicatorSymbol, Series], test_data: DataFrame, portfolio: Portfolio, pos_size_handler: Callable[[PosSizeContext], None] | None, exit_dates: Mapping[str, datetime64], train_only: bool = False, slippage_model: SlippageModel | None = None, enable_fractional_shares: bool = False, round_fill_price: bool = True, warmup: int | None = None) dict[str, DataFrame] [源代码]
Backtests a
set
ofExecution
s that implement trading logic.- 参数:
config --
pybroker.config.StrategyConfig
.executions --
Execution
s to run.sessions --
Mapping
of symbols toMapping
of custom data that persists for every bar during theExecution
.models --
Mapping
ofpybroker.common.ModelSymbol
pairs topybroker.common.TrainedModel
s.indicator_data --
Mapping
ofpybroker.common.IndicatorSymbol
pairs topandas.Series
ofpybroker.indicator.Indicator
values.test_data --
pandas.DataFrame
of test data.portfolio --
pybroker.portfolio.Portfolio
.pos_size_handler --
Callable
that sets position sizes when placing orders for buy and sell signals.exit_dates --
Mapping
of symbols to exit dates.train_only -- Whether the backtest is run with trading rules or only trains models.
enable_fractional_shares -- Whether to enable trading fractional shares.
round_fill_price -- Whether to round fill prices to the nearest cent.
warmup -- Number of bars that need to pass before running the executions.
- 返回:
Dictionary of
pandas.DataFrame
s containing bar data, indicator data, and model predictions for each symbol whenpybroker.config.StrategyConfig.return_signals
isTrue
.
- class Execution(id: int, symbols: frozenset[str], fn: Callable[[ExecContext], None] | None, model_names: frozenset[str], indicator_names: frozenset[str])[源代码]
基类:
NamedTuple
Represents an execution of a
Strategy
. Holds a reference to aCallable
that implements trading logic.- fn
Implements trading logic.
- Type:
Callable[[pybroker.context.ExecContext], None] | None
- model_names
Names of
pybroker.model.ModelSource
s used for execution offn
.
- indicator_names
Names of
pybroker.indicator.Indicator
s used for execution offn
.
- class Strategy(data_source: DataSource | DataFrame, start_date: str | datetime, end_date: str | datetime, config: StrategyConfig | None = None)[源代码]
基类:
BacktestMixin
,EvaluateMixin
,IndicatorsMixin
,ModelsMixin
,WalkforwardMixin
Class representing a trading strategy to backtest.
- 参数:
data_source --
pybroker.data.DataSource
orpandas.DataFrame
of backtesting data.start_date -- Starting date of the data to fetch from
data_source
(inclusive).end_date -- Ending date of the data to fetch from
data_source
(inclusive).config --
Optional
pybroker.config.StrategyConfig
.
- add_execution(fn: Callable[[ExecContext], None] | None, symbols: str | Iterable[str], models: ModelSource | Iterable[ModelSource] | None = None, indicators: Indicator | Iterable[Indicator] | None = None)[源代码]
Adds an execution to backtest.
- 参数:
fn --
Callable
invoked on every bar of data during the backtest and passed anpybroker.context.ExecContext
for each ticker symbol insymbols
.symbols -- Ticker symbols used to run
fn
, wherefn
is called separately for each symbol.models --
Iterable
ofpybroker.model.ModelSource
s to train/load for backtesting.indicators --
Iterable
ofpybroker.indicator.Indicator
s to compute for backtesting.
- backtest(start_date: str | datetime | None = None, end_date: str | datetime | None = None, timeframe: str = '', between_time: tuple[str, str] | None = None, days: str | Day | Iterable[str | Day] | None = None, lookahead: int = 1, train_size: int = 0, shuffle: bool = False, calc_bootstrap: bool = False, disable_parallel: bool = False, warmup: int | None = None, portfolio: Portfolio | None = None, adjust: Any | None = None) TestResult [源代码]
Backtests the trading strategy by running executions that were added with
add_execution()
.- 参数:
start_date -- Starting date of the backtest (inclusive). Must be within
start_date
andend_date
range that was passed to__init__()
.end_date -- Ending date of the backtest (inclusive). Must be within
start_date
andend_date
range that was passed to__init__()
.timeframe --
Formatted string that specifies the timeframe resolution of the backtesting data. The timeframe string supports 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
.between_time --
tuple[str, str]
of times of day e.g. ('9:30', '16:00') used to filter the backtesting data (inclusive).days -- Days (e.g.
"mon"
,"tues"
etc.) used to filter the backtesting data.lookahead -- Number of bars in the future of the target prediction. For example, predicting returns for the next bar would have a
lookahead
of1
. This quantity is needed to prevent training data from leaking into the test boundary.train_size -- Amount of
pybroker.data.DataSource
data to use for training, where the maxtrain_size
is1
. For example, atrain_size
of0.9
would result in 90% of data being used for training and the remaining 10% of data being used for testing.shuffle -- Whether to randomly shuffle the data used for training. Defaults to
False
. Disabled when model caching is enabled viapybroker.cache.enable_model_cache()
.calc_bootstrap -- Whether to compute randomized bootstrap evaluation metrics. Defaults to
False
.disable_parallel -- If
True
,pybroker.indicator.Indicator
data is computed serially. IfFalse
,pybroker.indicator.Indicator
data is computed in parallel using multiple processes. Defaults toFalse
.warmup -- Number of bars that need to pass before running the executions.
portfolio -- Custom
pybroker.portfolio.Portfolio
to use for backtests.adjust -- The type of adjustment to make to the
pybroker.data.DataSource
.
- 返回:
TestResult
containing portfolio balances, order history, and evaluation metrics.
- clear_executions()[源代码]
Clears executions that were added with
add_execution()
.
- set_after_exec(fn: Callable[[Mapping[str, ExecContext]], None] | None)[源代码]
Callable[[Mapping[str, ExecContext]]
that runs after all execution functions.- 参数:
fn --
Callable
that takes aMapping
of all ticker symbols toExecContext
s.
- set_before_exec(fn: Callable[[Mapping[str, ExecContext]], None] | None)[源代码]
Callable[[Mapping[str, ExecContext]]
that runs before all execution functions.- 参数:
fn --
Callable
that takes aMapping
of all ticker symbols toExecContext
s.
- set_pos_size_handler(fn: Callable[[PosSizeContext], None] | None)[源代码]
Sets a
Callable
that determines position sizes to use for buy and sell signals.- 参数:
fn --
Callable
invoked before placing orders for buy and sell signals, and is passed apybroker.context.PosSizeContext
.
- set_slippage_model(slippage_model: SlippageModel | None)[源代码]
- walkforward(windows: int, lookahead: int = 1, start_date: str | datetime | None = None, end_date: str | datetime | None = None, timeframe: str = '', between_time: tuple[str, str] | None = None, days: str | Day | Iterable[str | Day] | None = None, train_size: float = 0.5, shuffle: bool = False, calc_bootstrap: bool = False, disable_parallel: bool = False, warmup: int | None = None, portfolio: Portfolio | None = None, adjust: Any | None = None) TestResult [源代码]
Backtests the trading strategy using Walkforward Analysis. Backtesting data supplied by the
pybroker.data.DataSource
is divided intowindows
number of equal sized time windows, with each window split into train and test data as specified bytrain_size
. The backtest "walks forward" in time through each window, running executions that were added withadd_execution()
.- 参数:
windows -- Number of walkforward time windows.
start_date -- Starting date of the Walkforward Analysis (inclusive). Must be within
start_date
andend_date
range that was passed to__init__()
.end_date -- Ending date of the Walkforward Analysis (inclusive). Must be within
start_date
andend_date
range that was passed to__init__()
.timeframe --
Formatted string that specifies the timeframe resolution of the backtesting data. The timeframe string supports 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
.between_time --
tuple[str, str]
of times of day e.g. ('9:30', '16:00') used to filter the backtesting data (inclusive).days -- Days (e.g.
"mon"
,"tues"
etc.) used to filter the backtesting data.lookahead -- Number of bars in the future of the target prediction. For example, predicting returns for the next bar would have a
lookahead
of1
. This quantity is needed to prevent training data from leaking into the test boundary.train_size -- Amount of
pybroker.data.DataSource
data to use for training, where the maxtrain_size
is1
. For example, atrain_size
of0.9
would result in 90% of data being used for training and the remaining 10% of data being used for testing.shuffle -- Whether to randomly shuffle the data used for training. Defaults to
False
. Disabled when model caching is enabled viapybroker.cache.enable_model_cache()
.calc_bootstrap -- Whether to compute randomized bootstrap evaluation metrics. Defaults to
False
.disable_parallel -- If
True
,pybroker.indicator.Indicator
data is computed serially. IfFalse
,pybroker.indicator.Indicator
data is computed in parallel using multiple processes. Defaults toFalse
.warmup -- Number of bars that need to pass before running the executions.
portfolio -- Custom
pybroker.portfolio.Portfolio
to use for backtests.adjust -- The type of adjustment to make to the
pybroker.data.DataSource
.
- 返回:
TestResult
containing portfolio balances, order history, and evaluation metrics.
- class TestResult(start_date: datetime, end_date: datetime, portfolio: DataFrame, positions: DataFrame, orders: DataFrame, trades: DataFrame, metrics: EvalMetrics, metrics_df: DataFrame, bootstrap: BootstrapResult | None, signals: dict[str, DataFrame] | None, stops: DataFrame | None)[源代码]
基类:
object
Contains the results of backtesting a
Strategy
.- start_date
Starting date of backtest.
- Type:
- end_date
Ending date of backtest.
- Type:
- portfolio
pandas.DataFrame
ofpybroker.portfolio.Portfolio
balances for every bar.
- positions
pandas.DataFrame
ofpybroker.portfolio.Position
balances for every bar.
- orders
pandas.DataFrame
of all orders that were placed.
- trades
pandas.DataFrame
of all trades that were made.
- metrics
Evaluation metrics.
- metrics_df
pandas.DataFrame
of evaluation metrics.
- bootstrap
Randomized bootstrap evaluation metrics.
- Type:
- signals
Dictionary of
pandas.DataFrame
s containing bar data, indicator data, and model predictions for each symbol whenpybroker.config.StrategyConfig.return_signals
isTrue
.- Type:
dict[str, pandas.core.frame.DataFrame] | None
- stops
pandas.DataFrame
containing stop data per-bar whenpybroker.config.StrategyConfig.return_stops
isTrue
.- Type:
pandas.core.frame.DataFrame | None
- class WalkforwardMixin[源代码]
基类:
object
Mixin implementing logic for Walkforward Analysis.
- walkforward_split(df: DataFrame, windows: int, lookahead: int, train_size: float = 0.9, shuffle: bool = False) Iterator[WalkforwardWindow] [源代码]
Splits a
pandas.DataFrame
containing data for multiple ticker symbols into anIterator
of train/test time windows for Walkforward Analysis.- 参数:
df --
pandas.DataFrame
of data to split into train/test windows for Walkforward Analysis.windows -- Number of walkforward time windows.
lookahead -- Number of bars in the future of the target prediction. For example, predicting returns for the next bar would have a
lookahead
of1
. This quantity is needed to prevent training data from leaking into the test boundary.train_size -- Amount of data in
df
to use for training, where the maxtrain_size
is1
. For example, atrain_size
of0.9
would result in 90% of data indf
being used for training and the remaining 10% of data being used for testing.shuffle -- Whether to randomly shuffle the data used for training. Defaults to
False
.
- 返回:
Iterator
ofWalkforwardWindow
s containing train and test data.
- class WalkforwardWindow(train_data: ndarray[tuple[int, ...], dtype[int64]], test_data: ndarray[tuple[int, ...], dtype[int64]])[源代码]
基类:
NamedTuple
Contains
train_data
andtest_data
of a time window used for Walkforward Analysis.- train_data
Train data.
- Type:
numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.int64]]
- test_data
Test data.
- Type:
numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.int64]]