python PyPI Apache 2.0 with Commons Clause Documentation Status Package status Downloads
Github stars Twitter

利用 Python 和机器学习助力算法交易

你是否希望借助 Python 和机器学习的力量来提升你的交易策略?PyBroker 是一个专为开发算法交易策略而设计的 Python 框架,尤其专注于使用机器学习的策略。借助 PyBroker,你可以轻松创建和微调交易规则,构建强大的模型,并深入了解你的策略表现。

重要特性

  • 一个基于 NumPy 并通过 Numba 加速的超快回测引擎。

  • 能轻松地在多个金融工具上创建和执行交易规则和模型。

  • 多个时间区间 整合交易信号,涵盖日线、周线和月线。

  • 可以轻松从 Alpaca, Yahoo Finance, AKShare, 或者从 自定义的数据源 来获取历史数据。

  • 可以使用 Walkforward Analysis, 来训练和回测模型,该方法模拟了策略在实际交易中的表现。

  • 使用随机 bootstrapping 来提供更准确的策略回测结果。

  • 通过 参数优化Optuna 选择最佳策略参数。

  • 缓存 已下载的数据、指标和模型,以加速你的开发过程。

  • 并行化 计算和训练,获得更高的性能。

  • 智能体技能,帮助 AI 智能体使用 PyBroker 编写交易策略和回测。

PyBroker 为你提供构建、测试和评估基于机器学习的算法交易策略所需的全部工具。

安装指导

PyBroker 支持基于 Windows、Mac 和 Linux 的 Python 3.11 及以上版本,你可以通过 pip 来安装 PyBroker:

pip install -U lib-pybroker

或者你可以通过克隆源代码来进行安装:

git clone https://github.com/edtechre/pybroker

快速开始示例

让我们一起来看下利用 PyBroker 来进行策略回测的代码示例

基于规则的策略

from pybroker import Strategy, YFinance, highest

def exec_fn(ctx):
   # Get the rolling 10 day high.
   high_10d = ctx.indicator('high_10d')
   # Buy on a new 10 day high.
   if not ctx.long_pos() and high_10d[-1] > high_10d[-2]:
      ctx.buy_shares = 100
      # Hold the position for 5 days.
      ctx.hold_bars = 5
      # Set a stop loss of 2%.
      ctx.stop_loss_pct = 2

strategy = Strategy(YFinance(), start_date='1/1/2025', end_date='8/1/2026')
strategy.add_execution(
   exec_fn, ['AAPL', 'MSFT'], indicators=highest('high_10d', 'close', period=10))
# Run the backtest after 20 days have passed.
result = strategy.backtest(warmup=20)

基于模型的策略

import pybroker
from pybroker import Alpaca, Strategy

def train_fn(symbol, train_data, test_data):
   # Train the model using indicators stored in train_data.
   ...
   return trained_model

# Register the model and its training function with PyBroker.
my_model = pybroker.model('my_model', train_fn, indicators=[...])

def exec_fn(ctx):
   preds = ctx.preds('my_model')
   if not ctx.long_pos() and preds[-1] > buy_threshold:
      ctx.buy_shares = 100
   elif ctx.long_pos() and preds[-1] < sell_threshold:
      ctx.sell_all_shares()

alpaca = Alpaca(api_key=..., api_secret=...)
strategy = Strategy(alpaca, start_date='1/1/2025', end_date='8/1/2026')
strategy.add_execution(exec_fn, ['AAPL', 'MSFT'], models=my_model)
# Run Walkforward Analysis on 1 minute data using 5 windows with 50/50 train/test data.
result = strategy.walkforward(timeframe='1m', windows=5, train_size=0.5)

如果想学习更多 PyBroker 的使用方式,请参考 用户指南

上述的教程也可以在 GitHub 上找到

AI 智能体技能

PyBroker v2 现已包含面向编程智能体的 AI 智能体技能

PyBroker 对标准指标进行了重新实现,加入了波动率归一化和稳健的非线性重缩放,使其值在不同股票代码和不同市场状态下都具有可比性。

联系我们

_images/email-image.png