22MDT1005 CapstoneMDT6099
22MDT1005 CapstoneMDT6099
CAPSTONE PROJECT
Submitted by
Karthick Raja V
Reg. No. 22MDT1083
Department of Mathematics
School of Advanced Sciences
Vellore Institute of Technology, Chennai Campus
Vandalur - Kelambakkam Road, Chennai - 600 127
April - 2024
DECLARATION
I hereby declare that the Project entitled Detecting and Analysing Candle-
stick Pattern in Stock Market Using Deep Learning submitted by me to the
Department of Mathematics, School of Advanced Sciences, Vellore Institute of
Technology, Chennai Campus, 600 127 in partial fulfillment of the requirements
of the award of the degree of Master of Science in Data Science is a bona-fide
record of the work carried out by me under the supervision of Dr. Saroj Kumar
Dash. I further declare that the work reported in this project, has not been submit-
ted and will not be submitted, either in part or in full, for the award of any other
degree or diploma of this institute or of any other institute or University.
This is to certify that the project entitled Detecting and Analysing Candle-
stick Pattern in Stock Market Using Deep Learning is prepared and submitted
by Karthick Raja V (Reg. No. 22MDT1083) to Vellore Institute of Technology,
Chennai Campus, in partial fulfillment of the requirement for the award of the de-
gree of Master of Science in Data Science is a bona-fide record carried out under
my guidance. The project fulfills the requirements as per the regulations of this
University and in my opinion meets the necessary standards for submission. The
contents of this report have not been submitted and will not be submitted either
in part or in full, for the award of any other degree or diploma and the same is
certified.
Acknowledgement
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning iv
Abstract
Given that the stock market operates in a dynamic landscape where vast amounts
of information are generated every second, accurately forecasting prices poses
a significant challenge. The unpredictable nature of stock market fluctuations
often means that conventional approaches to market analysis rely on predicting
future prices, a strategy that carries the risk of inaccuracy. This master’s thesis
now shifts its focus towards the identification and interpretation of candlestick
patterns, visual representations of historical price movements, rather than solely
on the speculative act of price forecasting.
For traders and investors, analyzing candlestick patterns is essential to the
decision-making process. Conventional techniques for identifying and evaluat-
ing these patterns frequently rely on labor-intensive manual interpretation or rule-
based systems that are prone to bias. This master’s thesis suggests an innovative
method for automatically identifying and analyzing candlestick patterns in histor-
ical stock market data by utilizing deep learning techniques, most especially the
You Only Look Once (YOLO) v5 algorithm.
The primary objective of this research is to develop and evaluate a deep learning-
based framework capable of accurately identifying various candlestick patterns
from raw candlestick images. YOLO v5, a state-of-the-art object detection algo-
rithm known for its efficiency and accuracy, will be adapted and trained using a
comprehensive dataset of candlestick images derived from historical stock market
data.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning v
Contents
Declaration i
Certificate ii
Acknowledgement iii
Abstract iv
1 Introduction 1
1.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.1 Candle Sticks: . . . . . . . . . . . . . . . . . . . . . . . 7
1.1.2 Price Action : . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2 Motivation: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.2.1 Patterns: . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2.2 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Literature Review 16
2.1 Understanding market patterns . . . . . . . . . . . . . . . . . . . 16
2.2 Deep Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3 Yolo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3 Methodology 21
3.1 Data Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1.1 Data Source Selection . . . . . . . . . . . . . . . . . . . 21
3.1.2 Pattern Definition: . . . . . . . . . . . . . . . . . . . . . 22
3.1.3 Image Collection: . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Image Labeling: . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2.1 Data Class Count: . . . . . . . . . . . . . . . . . . . . . 27
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning vi
3.2.2 Roboflow: . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.3 Data Split: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.4 Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
A Code Used 50
REFERENCES . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning vii
List of Tables
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning viii
List of Figures
4.1 F1 score . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.2 confusion matrix . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.3 results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.4 PR curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.5 Precision Curve . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.6 Recall Confidence Curve . . . . . . . . . . . . . . . . . . . . . . 45
4.7 chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning ix
4.8 predicted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 1
Chapter 1
Introduction
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 2
Investors
• Focus: Long-term Growth (Years)
• Goal: Build money and attain financial goals throughout time.
• Investment Strategy: Concentrate on the underlying value of businesses and
their potential for future growth. They usually analyze a company’s funda-
mentals (financial health, industry developments, etc.) and hold stocks for
months or even years.
• Examples: Individuals saving for retirement, mutual funds, pension funds.
Traders
• Focus: Short-term Gains (Days, Weeks, Months)
• Goal: Profit from short-term fluctuations in stock prices.
• Trading Strategy: Use price charts, technical indicators, and market senti-
ment to discover buying and selling opportunities. They may adopt a variety
of methods, such as day trading or swing trading, with the goal of capitaliz-
ing on market swings in a shorter timeframe.
• Examples: Day traders, hedge funds (sometimes), individual investors using
short-term trading strategies.
In the field of stock market analysis, there are two primary approaches: fun-
damental analysis and technical analysis. Each strategy employs a specific set of
tools and targets a different segment of the market.
1. Fundamental Analysis
Fundamental analysis is a strategy that investors use to determine the in-
herent value of a stock. It’s similar to determining the genuine value of
a property before purchasing it, except instead of focusing on the house’s
condition and location, you’re examining a company’s financial health and
future possibilities.
• Financial Statements: These are the foundation of basic analysis. In-
vestors look at a company’s balance sheet, income statement, and cash
flow statement to determine its financial health, profitability, debt lev-
els, and cash flow creation.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 3
2. Technical Analysis
Technical analysis is a technique used by investors and traders to assess as-
sets and uncover trading opportunities by studying statistical trends derived
from trading activity, such as price movements and volume. It contrasts with
basic analysis, which concentrates on a company’s financial health, indus-
try, and broader economic conditions.It argue that a security’s market price
already incorporates all essential information (stock, bond, etc.). This cov-
ers information such as corporate finances, industry trends, and economic
statistics.Technical analysts contend that a security’s market price already
includes all relevant information (stock, bond, etc.). This includes informa-
tion on business finances, industry trends, and economic data.
• Charts: Price charts provide the core of technical analysis. They visu-
ally depict a security’s price movement over time, allowing analysts to
see trends, patterns, and probable support and resistance levels.
• Technical Indicators:These are mathematical calculations based on price
and volume data that seek to identify trends, alert possible buying and
selling opportunities, and assess market mood. Moving averages, rel-
ative strength index (RSI), and MACD are three typical examples.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 4
1.1 Background
Several time series models and neural network algorithms attempt to forecast
stock values but frequently fail.As trading and investing are zero-sum games in
which one loses so that another gains, if an algorithm can forecast the price, ev-
eryone can use it to win, and no one will lose, but the market does not operate
that way.Instead of anticipating prices, we may recognize price action patterns
in the market.The Business Standard news release contains statistics on financial
literacy in India. According to the announcement, a 2022 research conducted by
UK-based IBS Intelligence (IBSi) revealed that just 27% of India’s adult popu-
lation is financially educated. This emphasizes the need for improved financial
education activities in the country, particularly given students’ poor baseline fi-
nancial literacy (16.7%), as mentioned in the same article Standard (2023).
Candlestick Charts
Candlestick charts are a common method of visualizing stock market price changes.
They provide a more useful image than merely lines on a chart by including the
opening, closing, high, and low values of an asset (stock, bond, etc.) over a certain
time period (day, week, month).
Anatomy of candlestick:
• Body: The thickness of the candlestick shows the difference between the
opening and closing prices as shown in Fig 1.1.
• Wick (or Shadow): The thin lines extending from the top and bottom of the
body show the period’s highest and lowest prices. A lengthy upper wick
indicates that the price rose far above the opening price before dropping
back down. In contrast, a lengthy lower wick shows that the price dropped
much below the opening price before rebounding.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 5
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 6
• Bullish candle:it indicates a price gain over a particular term. The body
is usually filled (colored) and appears green, blue, or black, depending on
the charting platform. The upper wick is often short or missing, whilst the
bottom wick varies in length.
• Bearish Candle: A bearish candle represents a price drop over time. The
body is usually empty (unfilled) and has the same colors as bullish candles.
The top wick might vary in length, but the bottom wick usually extends
below the closing price.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 7
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 8
• Short-Body Candlesticks:
– Doji: A doji occurs when the starting and closing prices are almost
similar, resulting in a tiny or nonexistent body. It suggests a lack of
market consensus.
– Spinning top :it a short body but extended upper and lower shadows.
It implies that buyers and sellers are at odds or that they are unable to
decide.
– Hammer: A hammer candlestick has a tiny body toward the top of the
candle and a long, downward shadow. It indicates a probable upward
reversal following a decline.
– Inverted hammer : It is similar to a hammer, except it appears at the
bottom of a downtrend. It indicates a probable upward reversal.
– Engulfing Pattern: This pattern is formed when the body of one candle
entirely engulfs the body of the previous candle. A bullish engulfing
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 9
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 10
as economic news, geopolitical events, supply and demand dynamics, and investor
emotion.Traders that use price action analysis look for patterns, trends, and other
forms in price charts to discover trading opportunities. They monitor how prices
move, whether they create identifiable patterns such as triangles, flags, or head
and shoulders, and if they adhere to important levels of support and resistance
1.2 Motivation:
Candlestick charts may reflect price changes over a wide range of periods, from
seconds to years, depending on trading frequency and length of interest. Here’s
how candlestick charts may be used at various time frames:
• Days: Traders and investors commonly use daily candlestick charts to mon-
itor price changes inside a single trading day. Each candlestick illustrates
the price activity that occurred on a single trading day, including the open-
ing, closing, high and low values. Daily charts are often utilized in swing
and position trading methods.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 11
1.2.1 Patterns:
The world of technical analysis offers a vast array of price action patterns,
each with its own interpretation and potential implications.Some of the fre-
quently occurring patters are
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 12
mation comes when the price falls below the support level established
prior to the rounded top formation.
– Head and Shoulders(Fig 1.8): This pattern usually appears at the apex
of an upswing and consists of three peaks. The central peak (the head)
is taller than the two adjacent peaks (the shoulders). It indicates a
possible trend reversal from bullish to negative.
– Inverse Head and Shoulders: The inverse of the head and shoulders
pattern, it usually appears at the bottom of a downturn and indicates a
possible turnaround from bearish to bullish.Seen in Fig 1.9.
– Triangle: In a symmetrical triangle pattern, the top and lower trend-
lines converge to form a triangular shape. This pattern implies a period
of market indecision, with prices making lower highs and higher lows.
Traders predict a breakout from the triangular formation, but the di-
rection is not decided. Breakouts above the top trendline indicate a
bullish continuation, while those below the lower trendline indicate a
bearish continuation.Fig 1.10.
– Ascending/Descending Wedge: Like triangles, wedges are generated
by converging trend lines. An ascending wedge pushes upward and
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 13
1.2.2 Motivation
Many traders and investors use algorithms to try to anticipate market or stock
prices, but this is impossible; if an algorithm can predict the price, everyone in
the market wins, and trading is a zero-sum game, thus it is useless.Instead of
anticipating prices, we can spot price movement patterns, which gives us an ad-
vantage in the market and allows us to make better educated decisions about trades
and investments. It will also assist many people without market understanding in
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 14
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 15
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 16
Chapter 2
Literature Review
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 17
forecasting model predictors, and these indicators were converted into time series
graph images. To assess the usefulness of deep learning for image recognition
in financial markets, the projected accuracies of the proposed model were com-
pared to those of a standard artificial neural network (ANN) and a support vector
machine (SVM) model. The experimental results suggest that CNN may be an
effective tool for developing stock prediction models.
Candlestick charts, as explained by Chen & Tsai (2020), display high, low,
opening, and closing prices over a certain time period. Candlestick patterns form
when human actions and reactions are patterned and frequently imitated. These
patterns capture information about the candles. Thomas Bulkowski’s Encyclo-
pedia of Candlestick Charts includes 103 candlestick designs. Traders use these
patterns to determine when to enter and exit. Candlestick pattern classification
techniques make it simpler to visually recognize these patterns. To show its po-
tential, we propose a two-step approach for spotting candlestick patterns automati-
cally. In the first stage, the time series is encoded as various types of images using
the Gramian Angular Field (GAF).In the second stage, a Convolutional Neural
Network (CNN) is used to learn eight different types of candlestick patterns from
GAF pictures. This publication refers to the approach as GAF-CNN. The study
found that their method surpassed the LSTM model in recognizing eight types of
candlestick patterns in real-world data with an average accuracy of 90.7%.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 18
2.3 Yolo
According to Huang et al. (2021), an effective and efficient object detector is es-
sential for practical applications. To solve these two issues, they extensively eval-
uate a set of current improvements that improve the performance of PP-YOLO
while keeping the infer time nearly constant. This project will use an incremental
ablation study to investigate a set of enhancements and experimentally assess their
impact on final model performance. Things they tried that didn’t work will also be
discussed. They increased the performance of PP-YOLO on COCO2017 test-dev
by incorporating numerous beneficial adjustments, boosting it from 45.9% mAP
to 49.5%.
Serdar Birogul, Günay Temür, and Utku Kose (2020)Birogul et al. (2020) cre-
ated an algorithm that analyzes one-year candlestick charts of stocks traded on
Borsa İstanbul (BIST) from 2000 to 2018. The model’s ability to make a ”Buy-
Sell” decision based just on candlestick charts indicates potential for reliable fore-
casting. The purpose is to improve the ”Buy-Sell” decision-making process by
offering foresight alongside other basic and technical assessments. It may also be
utilized to make independent financial decisions. The test findings clearly demon-
strate the importance of this foresight on achievement. The model had an 85%
success rate and generated a 100% profit. Furthermore, the method is applicable
to any time series that can be represented using candlestick charts.
Kim et al. (2022) highlight the significance of the SMD (Singapore Maritime
collection) as a valuable resource for training deep neural networks (DNN) in mar-
itime object detection, despite its issues with noisy labels and imprecise bounding
boxes. Their research focuses on rectifying these annotations to create a more reli-
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 19
Yang et al. (2020) all utilize YOLOV5 to detect faces, even while they are
wearing masks. Standing in front of the camera allows you to identify people
and unlock the gate. This reduces the need for human crowd management while
saving time and resources. Our experiment had a success percentage of 97.9%.
They compared our findings to other standard machine learning algorithms. Fur-
thermore, a snapshot of someone wearing a mask but not covering their nose is
clearly identified.Given the global effect of COVID-19, we believe this method
can successfully reduce exposure distances while improving surveillance.
Horvat & Gledec (2022) study delves into the prominence of YOLOv5 as a
prevalent and contemporary iteration within deep learning neural networks, partic-
ularly within computer vision tasks. The YOLO algorithm’s increasing popularity
stems from its efficiency in handling complex data scenarios, making it a favored
choice among data scientists. This paper aims to conduct a comparative analysis
of various iterations of the YOLOv5 model using common image datasets. By
doing so, it seeks to provide researchers with refined recommendations for select-
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 20
ing the most suitable model tailored to specific problem categories. The analysis
considers factors such as performance, accessibility, and ease of use, particularly
when integrated with popular programming languages like Python.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 21
Chapter 3
Methodology
Trading view
TradingView is a popular web-based platform for traders and investors that offers
a variety of tools and features for researching financial markets, exchanging trad-
ing ideas, and placing trades. Here are some important aspects of TradingView.Fig
3.1.
• Market Data: The website gives users access to real-time and historical
market data for a variety of financial products, such as equities, indices,
FX, cryptocurrencies, and commodities. Users may get price quotations,
volume data, and other pertinent information for their favorite markets.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 22
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 23
When it comes to selecting time frames for your image collection, it’s impor-
tant to carefully consider the periods that best align with the specific trends you are
aiming to target. You might opt for daily intervals to capture short-term fluctua-
tions or weekly snapshots for a broader perspective. Moving on to stock selection,
diversifying your portfolio with a mix of equities that cover different industries
and exhibit distinct historical patterns is key. This diversified approach enables
your model to build a robust understanding of market behaviors and trends. As
for image capture, it is advisable to take a meticulous Manual image data col-
lection by taking screenshots can be a time-consuming and challenging process,
particularly in scenarios where there is a significant volume of data to be captured,
such as with extensive datasets or instances where meticulous and accurate label-
ing is essential to maintain the integrity and reliability of the collected information
approach by either manually capturing screenshots or exporting charts as images,
ensuring consistent quality and choosing appropriate file formats like PNG or JPG
to maintain clarity and compatibility. manual image collection is a major bottle-
neck in this process. It can be incredibly time-consuming, especially if you need
a large and diverse dataset.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 24
• Search and Selection Process: When beginning the search and selection
process, individuals frequently face the issue of discovering relevant data,
which can take a substantial amount of time. This is especially true when
the data is spread out among several sources or requires precise selection
based on predetermined criteria. This implies that researchers or data col-
lectors may have to filter through massive amounts of information in order
to identify the most relevant data points for their requirements. In essence,
the procedure can be complex and time-consuming due to the need for care-
ful investigation and judgment in finding essential data.
• Data Entry and Annotation: it is the critical act of putting acquired data
into a database or spreadsheet, which is then properly annotated with rele-
vant information. This portion of the data processing journey can be time-
consuming, especially when dealing with data that requires manual format-
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 25
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 26
• Labeling: the process of labeling, you have the option to allocate a des-
ignated label, such as text, to every object that receives a bounding box.
These labels play a crucial role in enabling the model to comprehend the
meaning and identity of the object contained within the box. Examples of
these labels include ’Head and shoulders top’, ’head and shoulders bottom’,
’triangle’, ’W bottom’, and ’M top’ , each serving as a distinctive marker to
guide the model’s recognition capabilities effectively.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 27
3.2.2 Roboflow:
Roboflow stands out as an all-encompassing platform tailored specifically to en-
hance the efficiency of constructing computer vision applications. Eager to sim-
plify and optimize workflow, it boasts a diverse array of tools that cover every
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 28
stage of the development process. Whether it’s facilitating data collection and an-
notation tasks or aiding in model training and deployment endeavors, Roboflow
serves as a comprehensive solution. Now, let’s delve into a detailed exploration of
its essential features and capabilities.
• Data Management:
• Data import
– To export your dataset, first locate the dataset version you want to
download and then click on the ”Export” button available next to it.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 29
• Download
– By accessing the provided Code Snippet Fig 3.7, you will be pre-
sented with Python code specifically tailored for seamless integration
into your project. This resource enables you to efficiently retrieve the
dataset via Roboflow’s API, streamlining your development process.
This functionality proves invaluable for incorporating dataset down-
loads as an integral component of your daily workflow.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 30
3.4 Model
YOLOv5
The ”You Only Look Once” technique approaches object recognition holistically,
examining all input photos at once. This is distinct from the usual ”sliding win-
dow” technique, in which certain portions of the picture are treated independently
and often through numerous steps of categorization. This modern technique con-
siderably boosts processing efficiency by reviewing the entire image at once, elim-
inating the need for many separate assessments and resulting in speedier findings.
Furthermore, this technology improves detection accuracy by adding the total vi-
sual context into the neural network, resulting in a more complete comprehension
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 31
of the scene under analysis. With this global context available throughout the
network, the model can make more informed and precise decisions, resulting in
improved performance in object detection tasks.
– YOLO splits the supplied picture into a grid of squares. This grid aids
in localizing things inside the picture.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 32
The YOLOv5 network design is made up of three key components: the back-
bone, neck, and output seen Fig 3.9. Initially, the input terminal is in charge of
performing critical data preparation activities including mosaic data augmenta-
tion and adaptive image filling. To efficiently adapt to varied datasets, YOLOv5
features adaptive anchor frame computation right on the input, allowing for auto-
mated modification of the anchor frame size as the dataset changes. Moving on
to the backbone, it acts as a convolutional neural network, efficiently combining
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 33
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 34
detection approach.
The YOLOv5 model encompasses a range of architectures, including YOLOv5n,
YOLOv5s, YOLOv5m, YOLOv5l, YOLOv5x, YOLOv5n6, YOLOv5s6, YOLOv5m6,
YOLOv5l6, and YOLOv5x6 + TTA (Jocher, 2020a). However, the academic fo-
cus typically centers on the initial five variations: nano, small, medium, big, and
xlarge. These models differ primarily in the number of feature extraction modules
and convolution kernels, influencing practical considerations regarding computa-
tional resources and the overall neural network parameters.
The specified sizes for YOLOv5n, YOLOv5s, YOLOv5m, YOLOv5l, and
YOLOv5x are 4 MB, 14 MB, 41 MB, 89 MB, and potentially up to 166 MB,
respectively. These details are pivotal for users to make informed decisions re-
garding the model that best suits their computational and performance needs.
For our pattern detection model, we opted to utilize the YOLOv5s model with
pre-trained weights. During the training phase, the model ingests the data and
saves the weights to a file for future predictions, ensuring optimized accuracy in
pattern recognition. Throughout the training process, various metrics are com-
puted, and these results, alongside insightful plots and visualizations, are meticu-
lously archived in a dedicated folder. This comprehensive repository of training
outcomes serves as a valuable resource for analyzing the model’s performance
and refining its capabilities to enhance pattern detection accuracy in subsequent
iterations.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 35
Chapter 4
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 36
Where:
Area of Intersection = Area of the overlap between the predicted bounding box and the gr
bounding box
Area of Union = Total area covered by both the predicted bounding box and the gro
bounding box
2. Precision:
True Positives
Precision = (4.2)
True Positives + False Positives
3. Recall:
True Positives
Recall = (4.3)
True Positives + False Negatives
4. Mean Average Precision (mAP):
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 37
N
1 X
mAP = APi (4.4)
N i=1
5. F1 Score:
Precision × Recall
F1 Score = 2 ×
Precision + Recall
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 38
(4.5)
4.2 Results:
4.2.1 F1 score
The graph 4.1 illustrates the relationship between precision and recall as the
confidence threshold varies. Precision, which measures the proportion of correctly
identified instances among all detected instances, is plotted on the y-axis with
values ranging from 0 to 1. Recall, on the other hand, denotes the proportion of
correctly identified instances among all actual instances and appears on the x-axis
also ranging from 0 to 1.
The ’all classes 0.73 at 0.388’ curve represents the combined precision-recall
outcomes for all classes considered concurrently. For a confidence threshold of
0.388, the model attains a precision rate of 0.73 across all classes. This con-
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 39
veys that when the model’s predictions have a confidence score surpassing 0.388,
around 73
Each distinct curve corresponds to the precision-recall trade-off for individual
classes; however, due to the graph’s complexity, identifying the specific classes
represented by each curve may be challenging. These curves provide insights
into how precision and recall fluctuate per class as the confidence threshold is
adjusted, offering valuable information on model performance across different
class categories.
A confusion matrix Fig 4.2 is an excellent tool for demonstrating the perfor-
mance of classification models. The rows of the matrix represent the actual pricing
patterns seen in the picture data, which reflect the ground truth information uti-
lized for evaluation. On the other side, the columns show the pricing patterns
predicted by the YOLOv5 model for each image. The meticulous investigation of
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 40
this confusion matrix yields important insights into the YOLOv5 model’s accu-
racy in recognizing the complicated pricing patterns inside the picture data. This
study provides a comprehensive view of where the model succeeds and where
it may need improvement.By scrutinizing and interpreting the confusion matrix,
one can pinpoint specific areas for improvement, whether it be through refining the
training data utilized or tweaking the architecture of the model itself. Ultimately,
such insights derived from the confusion matrix are invaluable in bolstering the
overall performance and efficacy of the YOLOv5 model in its task of identifying
and categorizing price patterns within the image data.There seems to be a decent
amount of correct detections along the diagonal, suggesting the model can identify
some price patterns reasonably well.There are also non-zero values off-diagonal,
indicating both false positives and false negatives. The severity of these errors
depends on the specific application. In price pattern detection, missing a crucial
pattern (false negative) might be more critical than a false positive.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 41
Training Losses
• Box Loss: Beginning at 0.08, it gradually drops to roughly 0.03, indicating
an increase in bounding box prediction accuracy.
• Object Loss: Starts at 0.024 and falls to roughly 0.014, suggesting improved
object recognition capabilities with time.
• Class Loss: Begins at 0.04 and decreases to around 0.01, indicating im-
proved item categorization accuracy as training continues.
Validation Losses
• Overall Loss: Initially higher than training loss, but gradually lowers until
leveling out or slightly rising later.
Metrics:
• Precision and Recall: In terms of measurements, precision and recall levels
throughout training sessions are constantly around 0.7. This level implies
that the model strikes a respectable balance between producing correct de-
tections and reducing the incidence of false positives, demonstrating the
training process’s success in maintaining a high degree of performance.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 42
• mAP: The model’s mean Average Precision (mAP) is around 0.75, which
remains consistent within the 0.5:0.95 limits. This performance demon-
strates the model’s ability to properly recognize items across multiple thresh-
olds, as well as its efficacy in capturing a diverse range of objects with con-
stant precision.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 43
Interpretation:
In the context of interpreting the curve in Fig 4.4, it’s important to understand the
information conveyed by the x-axis and y-axis. The x-axis, representing recall,
gives insights into the percentage of true positive detections relative to the actual
positive cases in the dataset. On the other hand, the y-axis, depicting precision,
offers a view of the accuracy in identifying true positive detections among all
the model’s positive predictions. These axes together provide a comprehensive
understanding of the model’s performance.
• Head and shoulders top/bottom: These curves appear to have the best accu-
racy and recall values, indicating that the model detects these items with few
false positives or negatives. Their precisions are around 0.85, which means
that 85% of the detections for these classes are true positives, and their re-
calls are near to 1.0, suggesting that the model discovers the majority of the
real objects in the dataset.
• Triangles have a lesser accuracy (about 0.6), which means there may be
more false positives than real positives. The recall is also lower than other
classes, around 0.6, indicating the model might miss some actual triangles.
• W Bottom: This curve has a precision of 0.78 and a recall of around 0.8,
indicating a fair balance of accuracy and recall.
• All classes (mAP at 0.5): This figure, about 0.77, indicates the model’s
mean average accuracy (mAP) at an intersection-over-union (IoU) thresh-
old of 0.5. The IoU metric measures how well a projected bounding box
overlaps with the ground truth bounding box for an item. A 0.5 IoU thresh-
old indicates that at least half of the predicted bounding box’s area must
coincide with the ground truth box for a correct detection. The mAP mea-
sure aggregates precision-recall performance across all classes at various
IoU levels, resulting in a single score for evaluating the model’s overall de-
tection capacity.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 44
• Confidence Range: The x-axis covers a confidence range of 0.2 to 1.0. This
indicates that the model considers detections across a wide range of confi-
dence levels. No Separate
• Head and Shoulders Curves: Notably high precision and recall values, sug-
gesting excellent model capability in identifying these patterns can be seen
in Fig 4.5.
• Triangle Curve: Lower scores indicate potential for refining model training
or adjusting confidence thresholds to improve triangle detection accuracy.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 45
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 46
4.3 Prediction:
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 47
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 48
Chapter 5
5.1 Summary:
In the dynamic world of the financial market, technical analysis serves as a critical
tool for traders to pinpoint key levels and strategic trade opportunities, facilitat-
ing optimal entry and exit points. Within this landscape, the deep learning model
emerges as a valuable resource, providing substantial assistance and guidance.
By integrating both technical analysis and the innovative yolo model, traders can
enhance their decision-making processes, harnessing the power of data-driven in-
sights to capitalize on market movements and trends. With its ability to identify
potential trades with precision and efficiency, the yolo model empowers traders
to navigate the complexities of the financial market with greater confidence and
success. . This YOLOv5 model, with its cutting-edge capabilities, shows signif-
icant potential in revolutionizing the process of price pattern detection within the
financial market. By leveraging its advanced algorithms and being trained on ex-
tensive historical data, this technology can efficiently detect intricate price action
patterns on charts. Upon detection, the model not only pinpoints these patterns
but also conveniently outlines them with precise bounding boxes, creating a user-
friendly visual aid directly on the chart. The implementation of this model brings
tremendous advantages to traders at all levels: novice traders benefit from sim-
plified pattern recognition, while seasoned traders save precious time that would
otherwise be spent scrutinizing charts manually. Picture the convenience of hav-
ing the YOLOv5 model instantaneously recognize potential trading opportunities,
enabling traders to redirect their focus towards more in-depth analysis and mak-
ing well-informed decisions. With its potential to streamline and enhance trading
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 49
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 50
Appendix A
Code Used
15
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 51
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 52
5 results = model(’/content/cams.png’)
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 53
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 54
Bibliography
Birogul, S., Temür, G. & Kose, U. (2020), ‘Yolo object recognition algorithm and
“buy-sell decision” model over 2d candlestick charts’, IEEE access 8, 91894–
91915.
Chen, J.-H., Chen, S. Y.-C., Tsai, Y.-C. & Shur, C.-S. (2020), ‘Explainable deep
convolutional candlestick learner’, arXiv preprint arXiv:2001.02767 .
Chen, J.-H. & Tsai, Y.-C. (2020), ‘Encoding candlesticks as images for pat-
tern classification using convolutional neural networks’, Financial Innovation
6(1), 26.
Grimes, A. (2012), The art and science of technical analysis: market structure,
price action, and trading strategies, Vol. 544, John Wiley & Sons.
Horvat, M. & Gledec, G. (2022), A comparative study of yolov5 models per-
formance for image localization and classification, in ‘33rd Central European
Conference on Information and Intelligent Systems (CECIIS)’, p. 349.
Huang, X., Wang, X., Lv, W., Bai, X., Long, X., Deng, K., Dang, Q., Han, S.,
Liu, Q., Hu, X. et al. (2021), ‘Pp-yolov2: A practical object detector’, arXiv
preprint arXiv:2104.10419 .
Kim, J.-H., Kim, N., Park, Y. W. & Won, C. S. (2022), ‘Object detection and
classification based on yolo-v5 with improved maritime dataset’, Journal of
Marine Science and Engineering 10(3), 377.
Ramadhan, A., Palupi, I. & Wahyudi, B. A. (2022), ‘Candlestick patterns recogni-
tion using cnn-lstm model to predict financial trading position in stock market’,
Journal of Computer System and Informatics (JoSYC) 3(4), 339–347.
Sim, H. S., Kim, H. I., Ahn, J. J. et al. (2019), ‘Is deep learning for image recog-
nition applicable to stock market prediction?’, Complexity 2019.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus
Detecting and Analysing Candlestick Pattern in Stock Market Using Deep Learning 55
Standard, B. (2023), ‘Spreading the financial literacy wave across india - national
finance olympiad 2023’, Business Standard Press Release .
URL: https://www.business-standard.com/content/press-releases-
ani/spreading-the-financial-literacy-wave-across-india-national-finance-
olympiad-2023-1231221007321 .html
Yang, G., Feng, W., Jin, J., Lei, Q., Li, X., Gui, G. & Wang, W. (2020), Face mask
recognition system with yolov5 based on image recognition, in ‘2020 IEEE 6th
International Conference on Computer and Communications (ICCC)’, IEEE,
pp. 1398–1404.
Yao, J., Qi, J., Zhang, J., Shao, H., Yang, J. & Li, X. (2021), ‘A real-time detection
algorithm for kiwifruit defects based on yolov5’, Electronics 10(14), 1711.
Divison of Mathematics, School of Advanced Sciences, Vellore Institute of Technology , Chennai Campus