使用 bt 进行金融交易

Python 中的金融交易

Chelsea Yang

Data Science Instructor

bt 包

用于定义与回测交易策略的灵活框架

  • 策略:基于预设规则买卖资产的方法
  • 策略回测:用历史数据评估策略有效性的方法
import bt
Python 中的金融交易

bt 流程

  • 步骤 1:获取历史价格数据
  • 步骤 2:定义策略
  • 步骤 3:用数据回测策略
  • 步骤 4:评估结果
Python 中的金融交易

获取数据

# Download historical prices
bt_data = bt.get('goog, amzn, tsla', 
                 start='2020-6-1', end='2020-12-1')

print(bt_data.head())
                   goog         amzn        tsla
Date                                            
2020-06-01  1431.819946  2471.040039  179.619995
2020-06-02  1439.219971  2472.409912  176.311996
2020-06-03  1436.380005  2478.399902  176.591995
2020-06-04  1412.180054  2460.600098  172.876007
2020-06-05  1438.390015  2483.000000  177.132004
Python 中的金融交易

定义策略

# Define the strategy
bt_strategy = bt.Strategy('Trade_Weekly',

[bt.algos.RunWeekly(), # Run weekly
bt.algos.SelectAll(), # Use all data
bt.algos.WeighEqually(), # Maintain equal weights
bt.algos.Rebalance()]) # Rebalance
Python 中的金融交易

回测

# Create a backtest
bt_test = bt.Backtest(bt_strategy, bt_data)

# Run the backtest bt_res = bt.run(bt_test)
Python 中的金融交易

评估结果

# Plot the result
bt_res.plot(title="Backtest result")

回测结果图

# Get trade details
bt_res.get_transactions()

交易明细列表

Python 中的金融交易

开始练习!

Python 中的金融交易

Preparing Video For Download...