Trading signals

Financial Trading in Python

Chelsea Yang

Data Science Instructor

What are trading signals?

  • Triggers to long or short financial assets based on predetermined criteria
  • Can be constructed using:

    • One technical indicator
    • Multiple technical indicators
    • A combination of market data and indicators
  • Commonly used in algorithmic trading

Financial Trading in Python

A signal example

  • Signal: Price > SMA (long when the price rises above the SMA)

A plot of a signal that suggests trade entries.

Financial Trading in Python

How to implement signals in bt

  1. Get the data and calculate indicators
  2. Define the signal-based strategy
    • bt.algos.SelectWhere()
    • bt.algos.WeighTarget()
  3. Create and run a backtest
  4. Review the backtest result
Financial Trading in Python

Construct the signal

# Get price data by the stock ticker
price_data = bt.get('aapl', start='2019-11-1', end='2020-12-1')
# Calculate SMA
sma = price_data.rolling(20).mean()

Alternatively, use talib to calculate the indicator:

# Calculate SMA
import talib
sma =  talib.SMA(price_data['Close'], timeperiod=20)
Financial Trading in Python

Define a signal-based strategy

# Define the signal-based strategy
bt_strategy = bt.Strategy('AboveEMA',
                          [bt.algos.SelectWhere(price_data > sma),
                           bt.algos.WeighEqually(),
                           bt.algos.Rebalance()])
  • For simplicity, we assume:
    • Trade one asset at a time
    • No slippage or commissions
      • Slipage: the difference between the expected price of a trade and the price at which the trade is executed
      • Commission: fees charged by brokers when executing a trade
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 the backtest result

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

Plot of the backtest result

Financial Trading in Python

Let's practice!

Financial Trading in Python

Preparing Video For Download...