#### Discover more from All About Trading!

Contrarian trading can also be done through moving averages whenever the market approaches them. This is another way of finding dynamic support and resistance levels. Understanding market mechanics is extremely important in knowing which moving average to choose.

As of now, the trading results will no longer be published due to it being a function of costs, slippage, the nature of the algorithms, risk management, and a plethora of other variables. This can mislead the reader and therefore, I will only provide the functions for the indicators, their signals, and how to calculate returns as well as analyze them. The only spoon-feeding here will be presenting the indicator’s code and how to calculate the performance.

I have just published a new book after the success of my previous one “*New Technical Indicators in Python*”. It features a more complete description and addition of structured trading strategies with a **Github **page dedicated to the continuously updated code. If you feel that this interests you, feel free to visit the below link, or if you prefer to buy the PDF version, you could contact me on LinkedIn.

**The Book of Trading Strategies***Amazon.com: The Book of Trading Strategies: 9798532885707: Kaabar, Sofien: Books*www.amazon.com

# The Concept of Moving Averages

Moving averages help us confirm and ride the trend. They are the most known technical indicator and this is because of their simplicity and their proven track record of adding value to the analyses. We can use them to find support and resistance levels, stops and targets, and to understand the underlying trend. This versatility makes them an indispensable tool in our trading arsenal.

As the name suggests, this is your plain simple mean that is used everywhere in statistics and basically any other part in our lives. It is simply the total values of the observations divided by the number of observations. Mathematically speaking, it can be written down as:

To code the simple moving average, we can follow this syntax in Python while making sure we have defined the primal manipulation functions also seen below:

**# The function to add a certain number of columns**
def adder(Data, times):
for i in range(1, times + 1):
z = np.zeros((len(Data), 1), dtype = float)
Data = np.append(Data, z, axis = 1)
return Data
**
# The function to deleter a certain number of columns**
def deleter(Data, index, times):
for i in range(1, times + 1):
Data = np.delete(Data, index, axis = 1)
return Data
**# The function to delete a certain number of rows from the beginning**
def jump(Data, jump):
Data = Data[jump:, ]
return Data
def ma(Data, lookback, close, where):
Data = adder(Data, 1)
for i in range(len(Data)):
try:
Data[i, where] = (Data[i - lookback + 1:i + 1, close].mean())
except IndexError:
pass
** # Cleaning**
Data = jump(Data, lookback)
return Data

Now, it is time to code the simple K’s Envelopes and create the signal function to understand the triggers generated through them.

# The K’s Envelopes Trading Strategy

I will admit it, this is the simplest indicator I have found and I cannot even say developed because it is simply two simple moving averages, one applied to the highs and one applied to the lows. The idea is to form support and resistance zones so that we find good entry points. The K’s Envelopes is the essence of most of my entry points when I trade and send out the trading signals.

The Envelopes after having optimized them, are composed of two 800-period moving averages:

**One applied to the highs.****One applied to the lows.**

The two will form a moving support and resistance zone depending on the position of the price relative to the envelope.

We can use the below function to form the K’s Envelopes.

```
def k_envelopes(Data, high, low, lookback, where):
```**
# Adding columns**
Data = adder(Data, 2)
Data = ma(Data, lookback, high, where)
Data = ma(Data, lookback, low, where + 1)
return Data
**# The Data variable refers to the OHLC array
# The lookback variable should be 800
# The high variable refers to the column harboring the high
# The low variable refers to the column harboring the low
# The where variable refers to the column where you want to place your newly calculated moving average**

As with any proper research method, the aim is to test the strategy and to be able to see for ourselves whether it is worth having as an add-on to our pre-existing trading framework or not. The first step is creating the trading rules. When will the system buy and when will it go short? In other words, when is the signal given that tells the system that the current market will go up or down?

The trading conditions we can choose are:

**Go long (Buy) whenever the market enters the Envelopes from the above.****Go short (Sell) whenever the market enters the Envelopes from the below.**

The above chart shows the signals generated from the system. We have to keep in mind the frequency of the signals when we are developing a trading algorithm. The signal function used to generate the triggers based on the conditions mentioned above can be found in this snippet:

```
def signal(Data, close, lower_k_envelope, upper_k_envelope, buy, sell):
for i in range(len(Data)):
if Data[i, close] > Data[i, lower_k_envelope] and Data[i, close] < Data[i, upper_k_envelope] and Data[i - 1, close] > Data[i - 1, upper_k_envelope] and Data[i - 3, close] > Data[i - 3, upper_k_envelope]:
Data[i, buy] = 1
if Data[i, close] > Data[i, lower_k_envelope] and Data[i, close] < Data[i, upper_k_envelope] and Data[i - 1, close] < Data[i - 1, lower_k_envelope] and Data[i - 3, close] < Data[i - 3, lower_k_envelope]:
Data[i, sell] = -1
return Data
```

# Conclusion & Important Disclaimer

Remember to always do your back-tests. You should always believe that other people are **wrong**. My indicators and style of trading may work for me but maybe not for you.

I am a firm believer of not spoon-feeding. I have learnt by doing and not by copying. You should get the idea, the function, the intuition, the conditions of the strategy, and then elaborate (an even better) one yourself so that you back-test and improve it before deciding to take it live or to eliminate it. My choice of not providing Back-testing results should lead the reader to explore more herself the strategy and work on it more. That way you can share with me your better strategy and we will get rich together.

To sum up, are the strategies I provide realistic? *Yes*, but only by optimizing the environment (robust algorithm, low costs, honest broker, proper risk management, and order management). Are the strategies provided only for the sole use of trading? **No**, it is to stimulate brainstorming and getting more trading ideas as we are **all sick of hearing about an oversold RSI as a reason to go short or a resistance being surpassed as a reason to go long. I am trying to introduce a new field called Objective Technical Analysis where we use hard data to judge our techniques rather than rely on outdated classical methods.**