Candlestick Pattern Detection in Python: Techniques and Code
- Vinit Prajapati

- May 22, 2024
- 2 min read
Updated: May 29, 2024

Introduction :-
Welcome to our comprehensive guide on identifying candlestick patterns using Python! In this tutorial, we will delve into the fascinating world of candlestick charts, a powerful tool used in technical analysis to understand market trends and make informed trading decisions. Specifically, we'll focus on two fundamental candlestick patterns: the Marubozu or Bald pattern.
Candlestick charts provide a visual representation of price movements within a specific time frame, offering insights into market sentiment and potential future movements. By the end of this blog, you will have a clear understanding of how to identify the Marubozu or Bald pattern and implement a Python script to detect these patterns in historical stock data.
Single Candlestick Patterns :-
Marubozu or Bald Candle
Body Size: The Marubozu candlestick has a long body, indicating significant price movement within the time frame.
No Shadows (or Very Small Shadows): It has no or very small shadows, meaning the opening and closing prices are at the high and low of the period.
Types of Marubozu:
Bullish Marubozu: The opening price is the low, and the closing price is the high, indicating strong buying pressure.
Bearish Marubozu: The opening price is the high, and the closing price is the low, indicating strong selling pressure. In this tutorial, the theorical concepts is received from varsity...
Marubozu or Bald Candle (More Theory)
Market Sentiment:
Bullish Marubozu: Indicates buyers controlled the market, often signaling an uptrend or new bullish trend.
Bearish Marubozu: Indicates sellers controlled the market, often signaling a downtrend or new bearish trend.
Significance: Marubozu candles indicate strong market sentiment and momentum, aiding in trading decisions.
Python Code To Detect Candle
Installation and Imports
import numpy as np
import pandas as pd
import plotly.graph_objects as go # pip install plotly
from datetime import datetime☝️ Explaination 👇
Imports the NumPy library, which is used for numerical operations and handling arrays in Python.
Imports the Pandas library, which is essential for data manipulation and analysis, particularly for working with data structures like DataFrames.
Imports the graph_objects module from the Plotly library, allowing the creation of interactive visualizations and plots, particularly useful for creating candlestick charts.
Imports the datetime class from the datetime module, which is used for manipulating dates and times in Python.
2. Read Stock Data
Now that we have imported the necessary libraries, we need sample or real stock data to detect the Marubozu candlestick pattern. There are several ways to obtain this data, includes :-
Downloading a CSV file (Yahoo Finance, NSE ...)
Using financial APIs (Alpha Vantage, Quandl, or Yahoo Finance).
Generating a sample dataset. (Git Link...)
stock_data = pd.read_csv('RELIANCE.NS.csv')
print(stock_data)In this tutorial we have used Reliance Stock data, from yahoo Finance
3. Plot stock data on candlestick graph :-
def plot_candle_graph(stock_data):
fig = go.Figure(data = [go.Candlestick(
x=stock_data['Date'],
open=stock_data['Open'],
high=stock_data['High'],
low=stock_data['Low'],
close=stock_data['Close']
)])
return fig☝️ Explaination 👇
def plot_candle_graph(stock_data):
This line defines a function named plot_candle_graph which takes one argument, stock_data, presumably a DataFrame containing stock data.
fig = go.Figure...
Here, we initialize a new Figure object (fig) using go.Figure(). Inside the Figure, we define a candlestick chart using go.Candlestick().
The x parameter is assigned the 'Date' column of the stock_data DataFrame, which presumably contains timestamps.
The open, high, low, and close parameters are assigned the respective columns of the stock_data DataFrame, representing the opening, highest, lowest, and closing prices for each timestamp.
return fig
Finally, the function returns the fig object containing the candlestick chart.
4. Marubuzo Candle Stick Logic :- (IMP)
☝️ Explaination 👇
bearish_marubuzo, bullish_marubuzo = False, False
Here, two boolean variables bearish_marubuzo and bullish_marubuzo are initialized to False, indicating that no Marubozu pattern has been detected yet.
candle_day_movement = abs(((Close - Open)/Open)*100)
This line calculates the percentage movement of the candle for the day, using the formula: ∣Close−OpenOpen∣×100∣∣OpenClose−Open∣∣×100.
if ((Low - (...
This block of code checks if the candlestick meets the criteria for a bullish Marubozu:
The opening price is within 1% of the day's low, and the closing price is within 1% of the day's high.
The candle's movement is between 1% and 10%, indicating a significant move.
If these conditions are met, bullish_marubuzo is set to True to indicate the presence of a bullish Marubozu pattern.
elif ((High - (...
Similarly, this block of code checks if the candlestick meets the criteria for a bearish Marubozu:
The opening price is within 1% of the day's high, and the closing price is within 1% of the day's low.
The candle's movement is between 1% and 10%, indicating a significant move.
If these conditions are met, bearish_marubuzo is set to True to indicate the presence of a bearish Marubozu pattern.
return bearish_marubuzo, bullish_marubuzo
Finally, the function returns a tuple containing the boolean values bearish_marubuzo and bullish_marubuzo, indicating whether a bearish or bullish Marubozu pattern was detected, respectively.
5. Traversing through Entire Data Set (IMP) :-
☝️ Explaination 👇
marubuzo_candle_data = []
for rows, i in stock_data.iterrows():
This loop iterates through each row of the stock_data DataFrame using the iterrows() method.
For each row, it extracts the values for 'Open', 'High', 'Low', and 'Close' prices.
bear_marubuzo, bull_marubuzo = marubuzo(Open=float(i['Open']), High=float(i['High']), Low=float(i['Low']), Close=float(i['Close']))
For each row, it applies the marubuzo() function to detect Marubozu patterns based on the 'Open', 'High', 'Low', and 'Close' prices of that day.
The function returns boolean values indicating whether a bearish or bullish Marubozu pattern was detected for that day.
if bear_marubuzo or bull_marubuzo:
marubuzo_candle_data.append(i)
If either a bearish or bullish Marubozu pattern is detected for the current day, the row data for that day is appended to the marubuzo_candle_data list.
marubuzo_candle_data = pd.DataFrame(marubuzo_candle_data)
After iterating through all rows, the collected data of Marubozu candlestick patterns is converted into a DataFrame.
plot_candle_graph(marubuzo_candle_data)
Finally, the plot_candle_graph() function is called with the DataFrame containing Marubozu candlestick patterns.
6. Outputs :-
>> Detected Marubuzo or Bald Candlestick pattern from reliance data set

>> Entire Data Set graph (Reliance)

Conclusion
With this fundamental understanding of the Marubozu candlestick pattern and its implementation in Python, you are well-equipped to kickstart your journey into algorithmic trading and other financial technologies. By leveraging Python's powerful data manipulation and visualization libraries, you can efficiently analyze market trends and develop automated trading strategies. This foundational knowledge serves as a stepping stone to deeper explorations in technical analysis, quantitative finance, and the exciting world of financial technology. Happy coding and successful trading!
Github link for entire code :- https://github.com/vinit9638/candle-stick-patterns




Comments