Financial Trading in Python
Chelsea Yang
Data Science Instructor
A flexible framework for defining and backtesting trading strategies
import bt
# 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
# 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
# Create a backtest bt_test = bt.Backtest(bt_strategy, bt_data)
# Run the backtest bt_res = bt.run(bt_test)
# Plot the result
bt_res.plot(title="Backtest result")
# Get trade details
bt_res.get_transactions()
Financial Trading in Python