利用 Python 和机器学习助力算法交易
你是否希望借助 Python 和机器学习的力量来提升你的交易策略?PyBroker 是一个专为开发算法交易策略而设计的 Python 框架,尤其专注于使用机器学习的策略。借助 PyBroker,你可以轻松创建和微调交易规则,构建强大的模型,并深入了解你的策略表现。
重要特性
能轻松地在多个金融工具上创建和执行交易规则和模型。
跨 多个时间区间 整合交易信号,涵盖日线、周线和月线。
可以轻松从 Alpaca, Yahoo Finance, AKShare, 或者从 自定义的数据源 来获取历史数据。
可以使用 Walkforward Analysis, 来训练和回测模型,该方法模拟了策略在实际交易中的表现。
使用随机 bootstrapping 来提供更准确的策略回测结果。
缓存 已下载的数据、指标和模型,以加速你的开发过程。
并行化 计算和训练,获得更高的性能。
智能体技能,帮助 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 的使用方式,请参考 用户指南:
用户指南
AI 智能体技能
PyBroker v2 现已包含面向编程智能体的 AI 智能体技能:
参考
- 配置选项
StrategyConfiginitial_cashfee_modefee_amountenable_fractional_sharesround_fill_priceposition_modebuy_delaysell_delaybootstrap_samplesexit_on_last_barexit_cover_fill_priceexit_sell_fill_pricebars_per_yearreturn_signalsreturn_stopsround_test_resultleverageinterest_raterecord_portfolio_barsrecord_position_bars
PyBroker 对标准指标进行了重新实现,加入了波动率归一化和稳健的非线性重缩放,使其值在不同股票代码和不同市场状态下都具有可比性。
- 指标
adx()aroon_diff()aroon_down()aroon_up()atr()close_minus_ma()cubic_deviation()cubic_trend()delta_on_balance_volume()detrended_rsi()highest()intraday_intensity()laguerre_rsi()linear_deviation()linear_trend()lowest()macd()money_flow()normalized_negative_volume_index()normalized_on_balance_volume()normalized_positive_volume_index()price_change_oscillator()price_intensity()price_volume_fit()quadratic_deviation()quadratic_trend()reactivity()returns()stochastic()stochastic_rsi()volume_momentum()volume_weighted_ma_ratio()
- 模块
- pybroker 包
- 子模块
- pybroker.cache 模块
- pybroker.common 模块
- pybroker.config 模块
- pybroker.context 模块
- pybroker.data 模块
- pybroker.eval 模块
- pybroker.ext.data 模块
- pybroker.indicator 模块
- pybroker.interval 模块
- pybroker.log 模块
- pybroker.model 模块
- pybroker.optimize 模块
- pybroker.parallel 模块
- pybroker.portfolio 模块
- pybroker.scope 模块
- pybroker.slippage 模块
- pybroker.strategy 模块
- pybroker.vect 模块
- 子模块
- pybroker 包
推荐阅读
下面一系列书籍可以提供很多关于量化金融和算法交易的知识:
Lingjie Ma, Quantitative Investing: From Theory to Industry
Timothy Masters, Testing and Tuning Market Trading Systems: Algorithms in C++
Stefan Jansen, Machine Learning for Algorithmic Trading, 2nd Edition
联系我们