PyBroker Documentation

repository·master·Indexed 25 days ago

https://github.com/edtechre/pybroker

PyBroker 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.

Tokens
39.4K
Snippets
86
Records
219
Agent score
85%

What's inside PyBroker

  1. Cache DataSource queries

    master

    To speed up data retrieval, enable caching for a specific DataSource using pybroker.enable_data_source_cache('name'). Subsequent calls to query with the same ticker symbols and date range will return data from the disk cache.

    Use pybroker.clear_data_source_cache() to clear the cache or pybroker.disable_data_source_cache() to disable it entirely. Note that these management functions should be called after enabling the cache.

  2. Workflow for creating a PyBroker strategy

    master

    To build a robust PyBroker strategy, follow these steps:

    1. 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.
    2. Configure the Strategy: Use StrategyConfig when managing cash, fees, position limits, delays, exits, or returned signals/stops.
    3. Define Indicators: Use built-in functions like highest, lowest, returns, or the indicator method.
    4. Define Model Sources: Use pybroker.model specifically for training or loading predictions.
    5. Implement Execution Logic:
      • Use completed-bar arrays (e.g., ctx.close[-1]) to prevent lookahead leakage.
      • Guard lookbacks using ctx.bars or warmup.
      • Ensure at most one order side per symbol per bar.
      • Add executions using Strategy.add_execution.
    6. Run the Backtest: Use backtest for single train/test passes or walkforward for model/walk-forward evaluation.
  3. Set Limit Prices for Stop Orders

    master

    You can combine stop orders with limit prices to ensure execution only occurs at specific levels. Use stop_trailing_limit and stop_profit_limit to 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()