Catching Market Reversals in Python

How to Create a Simple Contrarian Trading Strategy in Python

Sofien Kaabar, CFA
9 min readOct 12, 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.

Medium is a hub to interesting reads. I read a lot of articles before I decided to start writing. Consider joining Medium using my referral link (at NO additional cost to you).

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)
Data = np.append(Data, new_col, axis = 1)

return Data
# The function to delete a number of columns starting from an index
def deleter(Data, index, times):

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

Data =…



Sofien Kaabar, CFA

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