Candlestick patterns deserve to be studied thoroughly and even though a strategy relying solely on them will be unstable and unprofitable, they can be a valuable addition into a full trading system that uses other techniques. In this article, we will see a full presentation and code of a three-candle reversal pattern.
Start your Free Trial now at O’Reilly and start reading the Early Release of my upcoming book “Mastering Financial Pattern Recognition” which covers everything you need to know about candlestick patterns and how to code them in Python! (Bonus points: You will discover new never-seen-before patterns). You will also find technical indicators, risk management, and even behavioral finance covered in the book!
Mastering Financial Pattern Recognition
Candlesticks have become a key component of platforms and charting programs for financial trading. With these charts…www.oreilly.com
Candlestick Charts
Candlestick charts are among the most famous ways to analyze the time series visually. They contain more information than a simple line chart and have more visual interpretability than bar charts. Many libraries in Python offer charting functions but being someone who suffers from malfunctioning import of libraries and functions alongside their fogginess, I have created my own simple function that charts candlesticks manually with no exogenous help needed.
OHLC data is an abbreviation for Open, High, Low, and Close price. They are the four main ingredients for a timestamp. It is always better to have these four values together so that our analysis reflects more the reality. Here is a table that summarizes the OHLC data of hypothetical security:
Our job now is to plot the data so that we can visually interpret what kind of trend is the price following. We will start with the basic line plot before we move on to candlestick plotting.
Note that you can download the data manually or using Python. In case you have an excel file that has OHLC only data starting from the first row and column, you can import it using the below code snippet:
import numpy as np
import pandas as pd
# Importing the Data
my_ohlc_data = pd.read_excel('my_ohlc_data.xlsx')
# Converting to Array
my_ohlc_data = np.array(my_ohlc_data)
Plotting basic line plots is extremely easy in Python and requires only one line of code. We have to make sure that we have imported a library called matplotlib and then we will call a function that plots the data for us.
# Importing the necessary charting library
import matplotlib.pyplot as plt
# The syntax to plot a line chart
plt.plot(my_ohlc_data, color = 'black', label = 'EURUSD')
# The syntax to add the label created above
plt.legend()
# The syntax to add a grid
plt.grid()
Now that we have seen how to create normal line charts, it is time to take it to the next level with candlestick charts. The way to do this with no complications is to think about vertical lines. Here is the intuition (followed by an application of the function below):
Select a lookback period. This is the number of values you want to appear on the chart.
Plot vertical lines for each row representing the highs and lows. For example, on OHLC data, we will use a matplotlib function called vlines which plots a vertical line on the chart using a minimum (low) value and a maximum (high value).
Make a color condition which states that if the closing price is greater than the opening price, then execute the selected block of code (which naturally contains the color green). Do this with the color red (bearish candle) and the color black (Doji candle).
Plot vertical lines using the conditions with the min and max values representing closing prices and opening prices. Make sure to make the line’s width extra big so that the body of the candle appears sufficiently enough that the chart is deemed a candlestick chart.
def ohlc_plot(Data, window, name):
Chosen = Data[-window:, ]
for i in range(len(Chosen)):
plt.vlines(x = i, ymin = Chosen[i, 2], ymax = Chosen[i, 1], color = 'black', linewidth = 1)
if Chosen[i, 3] > Chosen[i, 0]:
color_chosen = 'green'
plt.vlines(x = i, ymin = Chosen[i, 0], ymax = Chosen[i, 3], color = color_chosen, linewidth = 4)
if Chosen[i, 3] < Chosen[i, 0]:
color_chosen = 'red'
plt.vlines(x = i, ymin = Chosen[i, 3], ymax = Chosen[i, 0], color = color_chosen, linewidth = 4)
if Chosen[i, 3] == Chosen[i, 0]:
color_chosen = 'black'
plt.vlines(x = i, ymin = Chosen[i, 3], ymax = Chosen[i, 0], color = color_chosen, linewidth = 4)
plt.grid()
plt.title(name)
# Using the function
ohlc_plot(my_ohlc_data, 50, '')
Knowledge must be accessible to everyone. This is why, from now on, a purchase of either one of my new books “Contrarian Trading Strategies in Python” or “Trend Following Strategies in Python” comes with free PDF copies of my first three books (Therefore, purchasing one of the new books gets you 4 books in total). The two new books listed above feature a lot of advanced indicators and strategies with a GitHub page. You can use the below link to purchase one of the two books (Please specify which one and make sure to include your e-mail in the note).
Pay Kaabar using PayPal.Me
Go to paypal.me/sofienkaabar and type in the amount. Since it’s PayPal, it’s easy and secure. Don’t have a PayPal…www.paypal.com
The Bullish Euphoria
The bullish Euphoria is composed of three candles with technical conditions where each candle is bigger than the previous one. We need to see three bearish candles where the second candle is bigger than the first candle and the third candle is bigger than the second candle. Each low must be lower than the previous close but this is optional. The pattern is based on the reaction after a panic move to the downside, therefore, it is a bullish reversal pattern.
The psychology of the bullish Euphoria is that generally after a news break and a severe downside reaction, profit taking should occur which could cause the market to correct a little bit. The pattern signals consolidation more than it signals a reversal but by definition, it is a contrarian pattern.
The Bearish Euphoria
The bearish Euphoria is composed of three candles with technical conditions where each candle is at least a specified ratio bigger than the previous one. We need to see three bullish candles where the second candle is at least twice as big as the first candle and the third candle is at least three times as big as the first candle. Each high must be higher than the previous close. The pattern is based on the reaction after a euphoric move to the upside, therefore, it is a bearish reversal pattern.
The psychology of the bearish Euphoria is that generally after a news break or a short squeeze, profit taking should occur which could cause the market to correct a little bit. The pattern signals consolidation more than it signals a reversal but by definition, it is a contrarian pattern.
It is worth-mentioning that the pattern does resemble the known three black crows and three white soldiers, however, it takes advantage of the sizing of the candles. I also note that the back-testing results on the known pattern do not add much to trading even though the intuition is clear. Sometimes, financial markets do not make sense and more often than not, they do not.
This pattern can be seen as an alternative of using the known pattern as a reversal configuration but with more conditions.
Creating a Scanning Algorithm
Our aim is to create an algorithm that detects this pattern and places theoretical buy and sell orders. But first, we need to code the intuition of the pattern. Let us review what we will need for the bullish Euphoria:
The three candles are bearish, meaning their opening prices are higher than their closing prices.
The third candle’s close is lower than the second candle’s close which in turn is lower than the first candle’s close.
The third candle’s size is bigger than the second candle’s size which in turn is bigger than the first candle’s size.
Similarly, for the bearish Euphoria, we need the following conditions:
The three candles are bullish, meaning their opening prices are lower than their closing prices.
The third candle’s close is higher than the second candle’s close which in turn is higher than the first candle’s close.
The third candle’s size is bigger than the second candle’s size which in turn is bigger than the first candle’s size.
def signal(Data):
for i in range(len(Data)):
# Bullish Euphoria
if Data[i, 0] > Data[i, 3] and Data[i - 1, 0] > Data[i - 1, 3] and Data[i - 2, 0] > Data[i - 2, 3] and Data[i, 3] < Data[i - 1, 3] and Data[i - 1, 3] < Data[i - 2, 3] and (Data[i, 0] - Data[i, 3]) > (Data[i - 1, 0] - Data[i - 1, 3]) and (Data[i - 1, 0] - Data[i - 1, 3]) > (Data[i - 2, 0] - Data[i - 2, 3]):
Data[i, 6] = 1
# Bearish Euphoria
elif Data[i, 3] > Data[i, 0] and Data[i - 1, 3] > Data[i - 1, 0] and Data[i - 2, 3] > Data[i - 2, 0] and Data[i, 3] > Data[i - 1, 3] and Data[i - 1, 3] > Data[i - 2, 3] and (Data[i, 3] - Data[i, 0]) > (Data[i - 1, 3] - Data[i - 1, 0]) and (Data[i - 1, 3] - Data[i - 1, 0]) > (Data[i - 2, 3] - Data[i - 2, 0]):
Data[i, 7] = -1
return Data
The above function takes an OHLC data array with multiple empty columns to spare and populates columns 6 (Buy) and 7 (Sell) with the conditions that we discussed earlier. We want to input 1’s in the column we call “buy” and -1 in the column we call “sell”. This later allows you to create a function that calculates the profit and loss by looping around these two columns and taking differences in the market price to find the profit and loss of a close-to-close strategy. Then you can use a risk management function that uses stops and profit orders.
If you want to see how to create all sorts of algorithms yourself, feel free to check out Lumiwealth. From algorithmic trading to blockchain and machine learning, they have hands-on detailed courses that I highly recommend.
Learn Algorithmic Trading with Python Lumiwealth
Learn how to create your own trading algorithms for stocks, options, crypto and more from the experts at Lumiwealth. Click to learn more
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.