PyBroker Documentation
repository·master·Indexed 25 days ago
https://github.com/edtechre/pybrokerPyBroker is a Python framework for developing algorithmic trading strategies with a focus on machine learning integration. It features a high-performance backtesting engine, Walkforward Analysis, and support for multiple data sources including Alpaca, Yahoo Finance, and AKShare. The framework allows for the implementation of rule-based and model-based strategies, custom technical indicators, and rotational trading logic via pre-execution ranking.
What's inside PyBroker
- To implement portfolio-wide logic, refer to the rebalancing guide. This covers equal position sizing and portfolio optimization, including before/after execution hooks.
Write custom or built-in indicators
masterTo create technical indicators, refer to the indicators guide. This covers using built-in indicators, using TA-Lib, writing custom indicators, using vectorized helpers, and computing multiple indicators simultaneously.Evaluate strategies with bootstrap metrics
masterTo perform advanced performance evaluation, use bootstrap metrics. This includes calculating confidence intervals and analyzing Maximum Drawdown.Initialize PyBroker and Data Source Caching
masterTo begin using PyBroker, import the core modules. You can enable data source caching using
pybroker.enable_data_source_cache(name)to avoid redundant downloads of market data during backtests.import pybroker from pybroker import Strategy, StrategyConfig, YFinance pybroker.enable_data_source_cache('my_strategy')Install PyBroker from source
masterYou can install PyBroker by cloning the Git repository directly.
git clone https://github.com/edtechre/pybrokerCreate a custom DataSource
masterTo use non-standard data (like CSVs or specific Pandas DataFrames), refer to the custom data source guide. This explains how to extend theDataSourceclass.Enable caching for PyBroker components
masterYou can enable disk caching for
DataSource,Indicator, and trained models by callingpybroker.enable_caches(). This is useful for persisting data and models across sessions.Pass a string identifier to
pybroker.enable_caches()to name your cache.pybroker.enable_caches('walkforward_strategy')Install and setup asv for benchmarking
masterPyBroker uses
asv(Airspeed Velocity) to track backtest performance across commits. To set up the benchmarking environment, installasvvia pip and initialize the machine configuration.pip install asv asv machine --yes # one-time per machineCache DataSource queries
masterTo speed up data retrieval, enable caching for a specific DataSource using
pybroker.enable_data_source_cache('name'). Subsequent calls toquerywith the same ticker symbols and date range will return data from the disk cache.Use
pybroker.clear_data_source_cache()to clear the cache orpybroker.disable_data_source_cache()to disable it entirely. Note that these management functions should be called after enabling the cache.Implement ranking and position sizing
masterTo manage how much capital is allocated to specific assets, refer to the ranking and position sizing guide. This covers ranking ticker symbols and setting specific position sizes.Workflow for creating a PyBroker strategy
masterTo build a robust PyBroker strategy, follow these steps:
- Define the Strategy Specification: Identify the universe, data source, date range, timeframe, long/short permissions, entry/exit rules, sizing, stops, ranking, rebalancing cadence, and model training requirements.
- Configure the Strategy: Use
StrategyConfigwhen managing cash, fees, position limits, delays, exits, or returned signals/stops. - Define Indicators: Use built-in functions like
highest,lowest,returns, or theindicatormethod. - Define Model Sources: Use
pybroker.modelspecifically for training or loading predictions. - Implement Execution Logic:
- Use completed-bar arrays (e.g.,
ctx.close[-1]) to prevent lookahead leakage. - Guard lookbacks using
ctx.barsorwarmup. - Ensure at most one order side per symbol per bar.
- Add executions using
Strategy.add_execution.
- Use completed-bar arrays (e.g.,
- Run the Backtest: Use
backtestfor single train/test passes orwalkforwardfor model/walk-forward evaluation.
Set Limit Prices for Stop Orders
masterYou can combine stop orders with limit prices to ensure execution only occurs at specific levels. Use
stop_trailing_limitandstop_profit_limitto define these levels on the execution context (ctx).def buy_with_trailing_stop_loss_and_profit(ctx): if not ctx.long_pos(): ctx.buy_shares = ctx.calc_target_shares(1) ctx.stop_trailing_pct = 20 ctx.stop_trailing_limit = ctx.close[-1] + 1 ctx.stop_profit_pct = 10 ctx.stop_profit_limit = ctx.close[-1] - 1 strategy.clear_executions() strategy.add_execution(buy_with_trailing_stop_loss_and_profit, ['TSLA']) result = strategy.backtest()