Catching Market Reversals in Python.

How to Create a Simple Contrarian Trading Strategy in Python.

Sofien Kaabar, CFA
10 min readFeb 18, 2022


Combining indicators is the first key to finding good strategies. In this article an indicator based on moving averages will be combined with the well-known Relative Strength Index to find interesting trading signals.

I have just released a new book after the success of the previous book. It features advanced trend following indicators and strategies with a GitHub page dedicated to the continuously updated code. Also, this book features the original colors after having optimized for printing costs. If you feel that this interests you, feel free to visit the below Amazon link, or if you prefer to buy the PDF version, you could contact me on LinkedIn.

The Moving Average Distance Index

This is a plain simple indicator where we analyze the distance of the market’s price relative to its moving average. Here are the steps to do so:

  • Calculate a 20-period moving average on the market’s price.
  • Subtract each closing price from the 20-period moving average.
  • Calculate a 60-period standard deviation of the result from step 2.
  • Calculate a 60-period moving average of the result from step 2.
  • Calculate the bounds using the Bollinger Band’s intuition.
USDCAD in the first panel with the Moving Average Distance Index in the second panel.

The above chart shows hourly values on the USDCAD with the Moving Average Distance Index — MADI in the second panel, we have chosen a 20-lookback period of the moving average with a 60-period volatility bands and a 3 standard-deviation factor.

# The function to add a number of columns inside an array
def adder(Data, times):

for i in range(1, times + 1):

new_col = np.zeros((len(Data), 1), dtype = float)…



Sofien Kaabar, CFA

Top writer in Finance, Investing, Business | Trader & Author