PyBroker

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 来提供更准确的策略回测结果。

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

  • 用并行计算来获得更高的性能。

通过使用 PyBroker,你将拥有所有必要的工具来创建基于数据和机器学习支持的交易策略。从今天开始用 PyBroker,将你的交易提升到一个新的高度!

安装指导

PyBroker 支持基于 Windows、Mac 和 Linux 的 Python 3.9 及以上版本,你可以通过 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/2022', end_date='7/1/2022')
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(train_data, test_data, ticker):
   # 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')
   # Open a long position given my_model's latest prediction.
   if not ctx.long_pos() and preds[-1] > buy_threshold:
      ctx.buy_shares = 100
   # Close the long position given my_model's latest prediction.
   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/2022', end_date='7/1/2022')
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 上找到

联系我们

_static/email-image.png