Beginner’s Guide to Technical Analysis in Python for Algorithmic Trading

Lakshmi Ajay
Geek Culture
Published in
10 min readJan 15, 2022

Identifying candlestick patterns & applying technical strategies to build a trading algorithm in Python

CANDLESTICK PATTERNS & TECHNICAL ANALYSIS (Image Source: Unsplash)

There are two major approaches to analyse any stock — fundamental analysis & technical analysis.

Fundamental analysis studies the company’s past & present performance by looking at various factors that can impact the stock price like the company’s profit & loss statements, cash flow, balance sheet, management process etc. On the other hand, technical analysis uses only the past price & volume movements to identify patterns/trends in the stock.

This article focuses on introducing some of the simple yet powerful techniques applied during the technical analysis. All the concepts explained here can be applied on any trading instrument (like stock, currency, options, indices or crypto).

In practice, applying each of these techniques individually may not give good results. Analysts normally apply a combination of these techniques before arriving at a BUY/SELL/HOLD decision. With a programmatic approach, the first level of analysis can be automated.

DISCLAIMER

Considering the topic in scope, let us start with the disclaimer.

The article is intended only for educational purpose. Please use it at your own discretion for any real-world use case.

WHAT’S IN IT FOR YOU?

When you reach the end of the article, you would have (hopefully) learnt the following tricks of the trade:

  • How to fetch the stock data
  • How to implement & analyse some of the basic candlestick patterns
    - Single candlestick patterns: Marubozu Candle, Doji Candle
    - Multiple candlestick patterns: Engulfing, Morning/Evening Star Pattern
  • How to apply few popular trading indicators/strategies using Python
    - Moving Average Strategies
    - Relative Strength Index (RSI) Indicator
    - Moving Average Convergence Divergence (MACD) Indicator
    - Bollinger Bands
  • How to implement a simple trading algorithm in Python

FETCHING DATA

Here we will be focusing on using the data fetched from the Indian stock exchange, National Stock Exchange (NSE) in particular. Data can be fetched from any other exchanges as well, the only criteria is that the data should have the OHLC (Open-High-Low-Close) information in it.

In this example we fetch the HDFC AMC stock data for the year 2021 using the nsepy Python package.

HDFCAMC — 2021 data peek (Image by Author)

The stock data is available for the 248 market days in 2021. In this article, we will only use OHLC data to perform the technical analysis.

CANDLESTICKS & CANDLESTICK CHART

The open, high, low, close (OHLC) price of a stock can be represented as a candlestick. Here is a quick summary of a candlestick representation:

  • Green candle: the stock’s closing price is greater than its opening price
  • Red candle: the stock’s closing price is lower than its opening price
  • Shaded portion: the region between open and close (Green/Red)
  • Candle wick: day’s high (top wick) & low (bottom wick)
Candlestick — source wiki

The candlestick chart is plotted using the graph_objects from the plotly package. Since we have downloaded the daily data, each candle in the chart represents the OHLC values for a day.

Candlestick Chart — 2021 (Image by Author)
Candlestick Chart — Dec 2021 (Image by Author)

CANDLESTICK PATTERNS

Key insights on the trading pattern can be derived from the candlesticks. The number of candles used for an analysis varies from a single candlestick to multiple candlesticks.

Here we will use the TA-Lib library to identify the candlestick patterns.

Marubozu Candle

  • Single candlestick where either one wick is missing or both the wicks are missing
  • It indicates the strength (green) or weakness of a stock
  • It does not indicate a trend-reversal

Marubozu candles in the sample dataset:

Doji Candle

  • Single candlestick with a very small body (opens and closes at almost the same price)
  • Indicates indecisiveness — there are both buyers & sellers for the stock
  • It normally indicates a sideways movement

Engulfing Candlestick Pattern

  • Multiple candlestick pattern — considers 2 candles where the second candle is slightly longer than the first candle and engulfs it.
  • Bullish Engulfing Pattern → Red Candle, Green Candle → BUY signal
  • Bearish Engulfing Pattern → Green Candle, Red Candle → SELL signal

Morning Star/Evening Star Pattern

  • Multiple candlestick pattern — considers 3 candlesticks
  • These patterns indicate a trend reversal
  • Morning Star → Red Candle, Doji, Green Candle → BUY signal
  • Evening Star → Green Candle, Doji, Red Candle → SELL signal

Example: DMART stock

Refer to this link to explore on the several other pattern identifiers available in the TA-Lib package: TA-Lib Pattern Recognition

TRADING STRATEGIES/INDICATORS

Apart from the candlestick analysis, there are various other techniques/strategies that can be applied. Some of these strategies are explained below.

MOVING AVERAGE STRATEGIES

Simple moving average (sma in short) is the average stock price in the last ’n’ days. Programmatically, this can be calculated with a single line of code.

20-day SMA (Image by Author)
20-day Simple Moving Average (Image by Author)

Moving Average Comparison Strategy

One of the trading strategies is to compare the current stock price with its previous n-days moving averages. Typically a 20-day, 50-day and 200-day moving average is used.

If,
Current close < 20-day sma < 50-day sma < 200-day sma → BUY signal
Current close > 20-day sma > 50-day sma > 200-day sma → SELL signal

Moving Average Crossover Strategy

Another strategy known as the moving average crossover strategy is to plot a long-term moving average (eg: 200-day sma) against a short-term moving average (eg: 20-day sma).

In general,
If the short-term sma crosses the long-term sma from below → BUY signal
If the short-term sma crosses the long-term sma from above → SELL signal

Simple Moving Average — 20d, 50d, 200d (Image by Author)

For the HDFCAMC stock data, from 14–12–2021 onwards,
closing price > 20-d sma > 50-d sma > 200-d sma → BUY signal.

Similarly, on 16–11–2021,
the 50-day sma crosses the 200-day sma from top → SELL signal (also known as the death cross).

The no. of moving averages and the window period are configurable. Sometimes the exponential moving average (EMA) is considered instead of the simple moving average (SMA). EMA gives more weightage to the prices closer to the current date as compared to the older dates in the window period.

RELATIVE STRENGTH INDEX (RSI) INDICATOR

The RSI is a popular technical analysis indicator used by many traders. It is used to analyse the momentum of a stock. It compares the recent gains with the recent losses. It gives an indication on the oversold or overbought condition of a stock.

Mathematically, the RSI can be computed as below. Typically a window period of 14 is considered to compute the RS value.

RSI Formula (Image by Author)

The value of RSI ranges between 0 & 100.

General thumb rule,
RSI < 30 indicates a oversold condition → BUY signal
RSI > 70 indicates a overbought condition → SELL signal

Programmatically, the RSI can be computed using the above formula or by using the TA-Lib.

RSI Indicator (Image by Author)

Normally the RSI indicator is used in conjunction with other indicators like the moving average, MACD, volumes traded etc to arrive at a BUY/SELL decision.

MACD — MOVING AVERAGE CONVERGENCE DIVERGENCE

MACD is another simple and popular momentum indicator that gives useful insights based on the recent trend of the stock. It shows the relationship between two moving averages.

It mainly consists of 3 components (typical values mentioned here):

  • MACD Line: 12-day EMA — 26-day EMA
  • Signal Line: 9-day EMA of MACD line
  • Histogram: MACD Line — Signal Line

MACD line will move faster and is more sensitive to price changes. Signal line will react more slowly to the price changes and hence will be a smoother line. The size of the histogram can be used to determine the strength of the momentum.

Normally traders apply a 2-line crossover strategy between the MACD line and the signal line.

When the MACD line crosses the signal line from below → BUY signal
When the MACD line crosses the signal line from above → SELL signal

As seen, the parameters (12, 26 & 9) are configurable and can be varied.

Below is the price chart and the MACD chart for the Hindustan Unilever stock. Refer to the git repo for the complete code.

As seen here the crossover points can be considered as the BUY/SELL signals. Similar to other indicators, it is good to combine this with other strategies before making a buy/sell decision.

BOLLINGER BAND

Bollinger band helps in interpreting the volatility of a stock. A narrow band indicates a low volatility & a broad band indicates a high volatility in the stock price.

It consists of:

  • Upper Bollinger Band: Moving Average Line + 2 standard deviations
  • Moving Average Line: 20-day simple moving average
  • Lower Bollinger Band: Moving Average Line — 2 standard deviations

Here is the simple implementation to compute the bollinger band using the rolling window function from pandas. This can also be reduced to a single line of code using TA-Lib’s BBANDS function.

From the chart it can be observed that when the distance between the bands is high, the stock price fluctuates more (higher volatility) and when the band is narrow the fluctuations are lesser (low volatility).

With 2 standard deviations it is assumed that 95% of all the price fluctuations will occur within this band (similar to the 95% confidence level in a normal distribution).

BUILDING A SIMPLE TRADING ALGORITHM

Once we have understood how to apply the individual techniques on the data, we are ready to build a personalised trading algorithm.

As an example, let us build a trading algorithm that works on the following strategy:

1. Get the BUY/SELL/HOLD indicators: Moving Average, MACD, Engulfing Pattern
2. For a BUY/SELL signal, check the RSI value of the previous 3 sessions.
3. If the strategy indicates a BUY and RSI < lower_threshold (40) → ‘BUY’
4. If the strategy indicates a SELL and RSI > upper_threshold (60) → ‘SELL’

To reduce the code cluttering, only the high-level code flow is shown here. Refer to the git repo for the complete code.

Observations

  • With this basic algorithm, the results are decent where a BUY signal is raised at the local minimas and a SELL signal at the local maximas.
  • It could take few months before a SELL signal is made after a BUY. Patience is the key.
  • In some cases, like for Infosys, there is no BUY signal in the year 2021. This is due to the lower RSI threshold used.
  • Algorithm can be tuned further by changing the parameters or by adding more indicators to strengthen it.

Here are the results on running this algorithm on different NSE stocks.

NOTE: Orange line indicates a BUY indicator and the purple line indicates a SELL indicator

Code Repository

All the code used in this article is available in the following github repository: Basic Technical Analysis — Code

For the coding geeks out there, I hope this helps you to get started and build your own strategies around it.

Conclusion

There is no fixed strategy that can work across all stocks. All the mentioned strategies & pattern identifiers can only provide a directional guidance. There are several other non-technical aspects that can impact the stock prices which cannot be coded.

Implementing the technical pattern analysis through code gives the trader the flexibility to design their own algorithms and automate the process of performing the basic technical analysis on a stock.

What next?

Since most of the trading brokers provide APIs to perform the trading, we can create a trading bot that can run the algorithm and do the trade automatically. Note that this can be risky (unless the algorithm is sufficiently fool-proofed) and should be experimented only for educational purpose.

Another approach could be to use the machine learning algorithms where new features could be derived from the technical indicators explained here. Models can be trained with this data to make predictions for the future.

More on this later!! Until then, adios!!

--

--