Strategy optimization and benchmarking

Financial Trading in Python

Chelsea Yang

Data Science Instructor

How to decide the values of input parameters?

  • Question:

    • Which is a better SMA lookback period to use in the signal "Price > SMA"?
  • Solution: strategy optimization

    • Try a range of input parameter values in backtesting and compare the results
Financial Trading in Python

Strategy optimization example

def signal_strategy(ticker, period, name, start='2018-4-1', end='2020-11-1'):

# Get the data and calculate SMA price_data = bt.get(ticker, start=start, end=end) sma = price_data.rolling(period).mean()
# Define the signal-based strategy bt_strategy = bt.Strategy(name, [bt.algos.SelectWhere(price_data>sma), bt.algos.WeighEqually(), bt.algos.Rebalance()])
# Return the backtest return bt.Backtest(bt_strategy, price_data)
1 www.datacamp.com/courses/writing-functions-in-python
Financial Trading in Python

Strategy optimization example

ticker = 'aapl'
sma20 = signal_strategy(ticker, 
                        period=20, name='SMA20')
sma50 = signal_strategy(ticker, 
                        period=50, name='SMA50')
sma100 = signal_strategy(ticker, 
                        period=100, name='SMA100')

# Run backtests and compare results bt_results = bt.run(sma20, sma50, sma100) bt_results.plot(title='Strategy optimization')

A plot of the optimization result

Financial Trading in Python

What is a benchmark?

A standard or point of reference against which a strategy can be compared or assessed.

  • Example:
    • A strategy that uses signals to actively trade stocks can use a passive buy and hold strategy as a benchmark.
    • The S&P 500 index is often used as a benchmark for equities.
    • U.S. Treasuries are used for measuring bond risks and returns.
Financial Trading in Python

Benchmarking example

def buy_and_hold(ticker, name, start='2018-11-1', end='2020-12-1'):

# Get the data price_data = bt.get(ticker, start=start_date, end=end_date)
# Define the benchmark strategy bt_strategy = bt.Strategy(name, [bt.algos.RunOnce(), bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance()])
# Return the backtest return bt.Backtest(bt_strategy, price_data)
Financial Trading in Python

Benchmarking example

benchmark = buy_and_hold(ticker, name='benchmark')

# Run all backtests and plot the resutls bt_results = bt.run(sma20, sma50, sma100, benchmark) bt_results.plot(title='Strategy benchmarking')

Benchmarking result

Financial Trading in Python

Let's practice!

Financial Trading in Python

Preparing Video For Download...