PyBroker为机器学习构建的算法交易框架

联合创作 · 2023-09-26 06:55

PyBroker 是一个 Python 框架旨在开发算法交易策略,重点是使用机器学习的策略。借助 PyBroker,你可以轻松创建和微调交易规则,构建强大的模型,并获得对策略绩效的宝贵见解。

特性:

  • 内置NumPy并使用Numba加速的超快速回测引擎。
  • 轻松创建和执行跨多种工具的交易规则和模型的能力。
  • 从Alpaca和Yahoo Finance或你自己的数据提供商处访问历史数据。
  • 使用Walkforward Analysis训练和回测模型的选项,模拟策略在实际交易中的表现。
  • 更可靠的交易指标使用随机引导来提供更准确的结果。
  • 缓存下载的数据、指标和模型,以加快你的开发过程。
  • 并行计算可实现更快的性能。

使用 PyBroker,你将拥有创建由数据和机器学习支持的成功交易策略所需的所有工具。

示例:

基于规则的策略:

   from pybroker import Strategy, YFinance, highest

   def exec_fn(ctx):
      # Require at least 20 days of data.
      if ctx.bars < 20:
         return
      # 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))
   result = strategy.backtest()

基于模型的策略:

   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)
浏览 10
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报