03. Add Technical Indicators

Technical Indicators do not analyze any part of the fundamental business; like earnings, revenue and profit margins. It is a mathematical calculation based on historic price and volume. Technical Indicators aim to forecast financial market directions.

Moving averages, relative strength index, MACD (Moving Average Convergence and Divergence), and stochastic oscillators are examples of technical indicators.

Following is an example of MACD indicator:

MACD is all about the convergence and divergence of the two moving averages. Convergence occurs when the two moving averages move towards each other, and divergence occurs when the moving averages move away.

A standard MACD is calculated using a 12 day EMA (Exponential Moving Average) and a 26 day EMA. Please note, both the EMA’s are based on the closing prices. We subtract the 26 EMA from the 12 day EMA, to estimate the convergence and divergence (CD) value. A simple line graph is created which is referred to as the ‘MACD Line’.

For adding indicators, we import ta library and the type of indicator eg: trend, then you import the indicator that you want to add. Example code:

from ta.trend import macd

Let's look at the calculation:

  1. To calculate the 12 day EMA, we will leave the first 12 data points.

  2. To calculate the 26 day EMA, we then leave the first 26 data points.

  3. Once we have both 12 and 26 day EMA running parallel to each other, we calculate the MACD value.

  4. MACD value = [12 day EMA – 26 day EMA].

def setup_strategy(self):    
    self.primary_df["12 day EMA"] = self.primary_df["close"].ewm(span=12, min_periods=12).mean()    
    self.primary_df["26 day EMA"] = self.primary_df["close"].ewm(span=26, min_periods=26).mean()    
    self.primary_df["MACD"] = self.primary_df["12 day EMA"] - df["26 day EMA"]    
    print("Current DF is:\n", self.primary_df.head(10))

Last updated