Trend-following strategies

Financial Trading in Python

Chelsea Yang

Data Science Instructor

Two types of trading strategies

Trend-following

  • Bet the price trend will continue in the same direction
  • Use trend indicators such as moving averages, ADX, etc to construct trading signals

Mean reversion

  • Bet the price tends to reverse back towards the mean
  • Use indicators such as RSI, Bollinger Bands, etc, to construct trading signals
Financial Trading in Python

MA crossover strategy

The trend is your friend.

 

  • Two EMA crossover:
    • Long signal: the short-term EMA crosses above the long-term EMA
    • Short signal: the short-term EMA crosses below the long-term EMA
Financial Trading in Python

Calculate the indicators

import talib
# Calculate the indicators
EMA_short = talib.EMA(price_data['Close'],
                      timeperiod=10).to_frame()
EMA_long = talib.EMA(price_data['Close'], 
                     timeperiod=40).to_frame()
Financial Trading in Python

Construct the signal

# Create the signal DataFrame
signal = EMA_long.copy()
signal[EMA_long.isnull()] = 0

# Construct the signal signal[EMA_short > EMA_long] = 1
signal[EMA_short < EMA_long] = -1
Financial Trading in Python

Plot the signal

# Plot the signal, price and MAs
combined_df = bt.merge(signal, price_data, EMA_short, EMA_long)
combined_df.columns = ['Signal', 'Price', 'EMA_short', 'EMA_long']

combined_df.plot(secondary_y=['Signal'])

EMA_crossover signal plot

Financial Trading in Python

Define the strategy with the signal

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

[bt.algos.WeighTarget(signal), bt.algos.Rebalance()])
Financial Trading in Python

Backtest the signal based strategy

# Create the backtest and run it
bt_backtest = bt.Backtest(bt_strategy, price_data)
bt_result = bt.run(bt_backtest)
Financial Trading in Python

Plot backtest results

# Plot the backtest result
bt_result.plot(title='Backtest result')

MA_crossover backtest result

Financial Trading in Python

Let's practice!

Financial Trading in Python

Preparing Video For Download...