Financial trading with bt

Financial Trading in Python

Chelsea Yang

Data Science Instructor

The bt package

A flexible framework for defining and backtesting trading strategies

  • Strategy: a method of buying and selling financial assets based on predefined rules
  • Strategy backtesting: a way to assess the effectiveness of a strategy by testing it on historical data
import bt
Financial Trading in Python

The bt process

  • Step 1: Get the historical price data
  • Step 2: Define the strategy
  • Step 3: Backtest the strategy with the data
  • Step 4: Evaluate the result
Financial Trading in Python

Get the data

# 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
Financial Trading in Python

Define the strategy

# 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
Financial Trading in Python

Backtest

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

# Run the backtest bt_res = bt.run(bt_test)
Financial Trading in Python

Evaluate the result

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

Plot of the backtest result

# Get trade details
bt_res.get_transactions()

Display a list of transactions

Financial Trading in Python

Let's practice!

Financial Trading in Python

Preparing Video For Download...