I have released a new book after the success of my previous one “*Trend Following Strategies in Python*”. It features advanced contrarian indicators and strategies with a **GitHub **page dedicated to the continuously updated code. If you feel that this interests you, feel free to visit the below Amazon link (which contains a sample), or if you prefer to buy the PDF version, you could check the link at the end of the article.

**Contrarian Trading Strategies in Python***Amazon.com: Contrarian Trading Strategies in Python: 9798434008075: Kaabar, Sofien: Books*www.amazon.com

### The Relative Strength Index

First introduced by J. Welles Wilder Jr., the RSI is one of the most popular and versatile technical indicators. Mainly used as a contrarian indicator where extreme values signal a reaction that can be exploited. Typically, we use the following steps to calculate the default RSI:

Calculate the change in the closing prices from the previous ones.

Separate the positive net changes from the negative net changes.

Calculate a smoothed moving average on the positive net changes and on the absolute values of the negative net changes.

Divide the smoothed positive changes by the smoothed negative changes. We will refer to this calculation as the Relative Strength — RS.

Apply the normalization formula shown below for every time step to get the RSI.

The above chart shows the hourly values of the GBPUSD in black with the 13-period RSI. We can generally note that the RSI tends to bounce close to 25 while it tends to pause around 75. To code the RSI in Python, we need an OHLC array composed of four columns that cover open, high, low, and close prices.

```
def add_column(data, times):
for i in range(1, times + 1):
new = np.zeros((len(data), 1), dtype = float)
data = np.append(data, new, axis = 1)
```

` return data`

```
def delete_column(data, index, times):
for i in range(1, times + 1):
data = np.delete(data, index, axis = 1)
```

` return data`

```
def delete_row(data, number):
data = data[number:, ]
return data
```

```
def ma(data, lookback, close, position):
data = add_column(data, 1)
for i in range(len(data)):
try:
data[i, position] = (data[i - lookback + 1:i + 1, close].mean())
except IndexError:
pass
data = delete_row(data, lookback)
return data
```

```
def smoothed_ma(data, alpha, lookback, close, position):
lookback = (2 * lookback) - 1
alpha = alpha / (lookback + 1.0)
beta = 1 - alpha
data = ma(data, lookback, close, position)
```

` data[lookback + 1, position] = (data[lookback + 1, close] * alpha) + (data[lookback, position] * beta)`

```
for i in range(lookback + 2, len(data)):
try:
data[i, position] = (data[i, close] * alpha) + (data[i - 1, position] * beta)
except IndexError:
pass
return data
```

```
def rsi(data, lookback, close, position):
data = add_column(data, 5)
for i in range(len(data)):
data[i, position] = data[i, close] - data[i - 1, close]
for i in range(len(data)):
if data[i, position] > 0:
data[i, position + 1] = data[i, position]
elif data[i, position] < 0:
data[i, position + 2] = abs(data[i, position])
data = smoothed_ma(data, 2, lookback, position + 1, position + 3)
data = smoothed_ma(data, 2, lookback, position + 2, position + 4)
```

```
data[:, position + 5] = data[:, position + 3] / data[:, position + 4]
data[:, position + 6] = (100 - (100 / (1 + data[:, position + 5])))
```

```
data = delete_column(data, position, 6)
data = delete_row(data, lookback)
```

` return data`

### Bollinger Bands

Volatility bands are composed of a moving average on the price with standard deviations around it to envelop the market. The upper band represents a dynamic resistance while the lower band represents a dynamic support. Also, known as Bollinger bands, we can code them as follows:

```
def volatility(data, lookback, close, position):
data = add_column(data, 1)
for i in range(len(data)):
try:
data[i, position] = (data[i - lookback + 1:i + 1, close].std())
except IndexError:
pass
data = delete_row(data, lookback)
return data
```

```
def bollinger_bands(data, lookback, standard_deviation, close, position):
data = add_column(data, 2)
data = ma(data, lookback, close, position)
```

```
data = volatility(data, lookback, close, position + 1)
data[:, position + 2] = data[:, position] + (standard_deviation * data[:, position + 1])
data[:, position + 3] = data[:, position] - (standard_deviation * data[:, position + 1])
data = delete_row(data, lookback)
data = delete_column(data, position + 1, 1)
return data
```

Make sure to focus on the concepts and not the code. You can find the codes of most of my strategies in my books. The most important thing is to comprehend the techniques and strategies.

### The Double Bollinger-RSI Strategy

This strategy assumes a double confirmation factor from two types of Bollinger bands. Basically, to create the strategy, you need to do the following:

**Calculate a 20-period RSI on the market price.****Calculate a 20-period Bollinger bands (with 2x standard deviation) on the market price.****Calculate a 20-period Bollinger bands (with 2x standard deviation) on the RSI.**

The trading conditions of the strategy are as follows:

**A long (buy) signal is generated whenever the market price surpasses its lower Bollinger band after having been below it while simultaneously, the RSI surpasses its lower Bollinger band after having been below it.****A short (sell) signal is generated whenever the market price breaks its upper Bollinger band after having been above it while simultaneously, the RSI breaks its upper Bollinger band after having been above it.**

```
def signal(data,
close,
rsi_column,
upper_bollinger_column,
lower_bollinger_column,
upper_bollinger_rsi_column,
lower_bollinger_rsi_column,
buy_column,
sell_column):
```

```
data = add_column(data, 10)
for i in range(len(data)):
try:
# Bullish pattern
if data[i, close] > data[i, lower_bollinger_column] and \
data[i - 1, close] < data[i - 1, lower_bollinger_column] and \
data[i, rsi_column] > data[i, lower_bollinger_rsi_column] and \
data[i - 1, rsi_column] < data[i - 1, lower_bollinger_rsi_column]:
data[i + 1, buy_column] = 1
# Bearish pattern
elif data[i, close] < data[i, upper_bollinger_column] and \
data[i - 1, close] > data[i - 1, upper_bollinger_column] and \
data[i, rsi_column] < data[i, upper_bollinger_rsi_column] and \
data[i - 1, rsi_column] > data[i - 1, upper_bollinger_rsi_column]:
data[i + 1, sell_column] = -1
except IndexError:
pass
return data
```

Check out my weekly market sentiment report to understand the current positioning and to estimate the future direction of several major markets through complex and simple models working side by side. Find out more about the report through this link:

**Coalescence***A Weekly Report Covering FX & Equities Market Positioning Using Complex Models. Let me read it first This site requires…*coalescence.substack.com

### Summary

To summarize up, what I am trying to do is to simply contribute to the world of objective technical analysis which is promoting more transparent techniques and strategies that need to be back-tested before being implemented. This way, technical analysis will get rid of the bad reputation of being a subjective and scientifically unfounded.

I recommend you always follow the the below steps whenever you come across a trading technique or strategy:

Have a critical mindset and get rid of any emotions.

Back-test it using real life simulation and conditions.

If you find potential, try optimizing it and running a forward test.

Always include transaction costs and any slippage simulation in your tests.

Always include risk management and position sizing in your tests.

Finally, even after making sure of the above, stay careful and monitor the strategy because market dynamics may shift and make the strategy unprofitable.

For the PDF alternative, the price of the book is **9.99 EUR**. Please include your email in the note before paying so that you receive it on the right address. Also, once you receive it, make sure to download it through google drive.

**Pay Kaabar using PayPal.Me***If you accept cookies, we’ll use them to improve and customize your experience and enable our partners to show you…*www.paypal.com