#### Discover more from All About Trading!

Heatmaps offer a quick and clear view of the current situation. In trading, we can use them with correlations but we can also use them to detect imminent reactions or to confirm the underlying trend. This article discusses the creation of the heatmap on the values of the RSI.

For a detailed and thorough collection of contrarian trading strategies, you can check out my book. The book features a huge number of classic and modern techniques as it dwelves into the realm of technical analysis with different trading strategies. The book comes with its own GitHub.

**Contrarian Trading Strategies in Python***Amazon.com: Contrarian Trading Strategies in Python: 9798434008075: Kaabar, Sofien: Books*amzn.to

### The MarketÂ Regime

The marketâ€™s regime is its current state and can be divided into:

**Bullish trend: The market has a tendency to make higher highs meaning that the aggregate direction is upwards.****Sideways: The market has a tendency to to range while remaining within established zones.****Bearish trend: The market has a tendency to make lower lows meaning that the aggregate direction is downwards.**

Many tools attempt to detect the trend and most of them do give the answer but we can not really say we can predict the next state. The best way to solve this issue is to assume that the current state will continue and trade any reactions, preferably in the direction of the trend. For example, if the EURUSD is above its moving average and shaping higher highs, then it makes sense to wait for dips before buying and assuming that the bullish state will continue, also known as a trend-following strategy.

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 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
```

### Detecting the Trend Using theÂ Heatmap

The concept of detecting the trend using the RSI is not very useful but is very easy to see. Whenever the RSI is showing a reading that is greater than 50, a bullish regime is in-progress and whenever it is showing a reading that is less than 50, a bearish regime is in-progress. Therefore, we can create the conditions below by tracing a vertical colored line accordingly. Here is how:

**A green vertical line is traced when the RSI is above 50.****A red vertical line is traced when the RSI is below 50.**

By zooming out, we will get a basic form of heatmap as shown in the below chart.

The full code for the plot is as follows:

```
def indicator_plot(data, second_panel, window = 250):
fig, ax = plt.subplots(2, figsize = (10, 5))
sample = data[-window:, ]
for i in range(len(sample)):
ax[0].vlines(x = i, ymin = sample[i, 2], ymax = sample[i, 1], color = 'black', linewidth = 1)
if sample[i, 3] > sample[i, 0]:
ax[0].vlines(x = i, ymin = sample[i, 0], ymax = sample[i, 3], color = 'black', linewidth = 1.5)
if sample[i, 3] < sample[i, 0]:
ax[0].vlines(x = i, ymin = sample[i, 3], ymax = sample[i, 0], color = 'black', linewidth = 1.5)
if sample[i, 3] == sample[i, 0]:
ax[0].vlines(x = i, ymin = sample[i, 3], ymax = sample[i, 0], color = 'black', linewidth = 1.5)
ax[0].grid()
for i in range(len(sample)):
if sample[i, second_panel] > 50:
ax[1].vlines(x = i, ymin = 0, ymax = 100, color = 'green', linewidth = 1.5)
if sample[i, second_panel] < 50:
ax[1].vlines(x = i, ymin = 0, ymax = 100, color = 'red', linewidth = 1.5)
ax[1].grid()
```

`indicator_plot(my_data, 4, window = 500)`

Remember to call the RSI function on the fifth column of your OHLC array. The fifth column is indexed at 4. The lookback parameters must be tweaked to reduce lag and false signals. Also, we can use other indicators and conditions.

### Summary

To sum 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 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.