The below shows the code for a signal function that detects divergences. The function is very simple and further improvements can be made to make it smarter but at the moment, it is sufficient enough to detect what the eye sees.
def divergence(Data, indicator, lower_barrier, upper_barrier, width, buy, sell):for i in range(len(Data)):
try:
if Data[i, indicator] < lower_barrier:for a in range(i + 1, i + width):
# First trough
if Data[a, indicator] > lower_barrier:for r in range(a + 1, a + width):
if Data[r, indicator] < lower_barrier and Data[r, indicator] > Data[i, indicator] and Data[r, 3] < Data[i, 3]:
for s in range(r + 1, r + width):
# Second trough
if Data[s, indicator] > lower_barrier:
Data[s, buy] = 1
breakelse:
break
else:
break
else:
break
else:
breakexcept IndexError:
passfor i in range(len(Data)):
try:
if Data[i, indicator] > upper_barrier:for a in range(i + 1, i + width):
# First trough
if Data[a, indicator] < upper_barrier:
for r in range(a + 1, a + width):
if Data[r, indicator] > upper_barrier and Data[r, indicator] < Data[i, indicator] and Data[r, 3] > Data[i, 3]:
for s in range(r + 1, r + width):# Second trough
return Data# Using the function
if Data[s, indicator] < upper_barrier:
Data[s, sell] = -1
break
else:
break
else:
break
else:
break
else:
break
except IndexError:
pass
my_data = divergence(my_data, bollinger_percentage_column, 0, 1, 20, buy_column, sell_column)
Now, the time has come to try the strategy out. Of course, it is not intended to be a standalone strategy for the following reasons:
- Not many divergences occur and therefore, not much data to do performance evaluation.
- Divergences are not timing signals as they are simply an alert system for the near term. They are also ambiguous from time to time and they are not perfect as is the case with all strategies.
- A full trading strategy should not rely on one simple indicator as markets are very complex. To my knowledge, it is at least extremely difficult to make consistent profits using one Indicator.
- Not all markets are divergence-friendly. Some simple have too strong momentum to be stopped with a divergence.
The goal is to see the quality of signals through the signal charts and to see the results of a simple back-test.