0% found this document useful (0 votes)
12 views46 pages

Project Report

The document is a project report on a Stock Prediction Model submitted by Arsh Chauhan and Dev Singh as part of their Bachelor of Technology in Computer Science and Engineering. It outlines the methodology for predicting stock prices using machine learning and deep learning techniques, particularly focusing on LSTM networks. The report includes sections on literature review, problem formulation, system design, implementation, and future scope of the project.

Uploaded by

pawangandhar2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views46 pages

Project Report

The document is a project report on a Stock Prediction Model submitted by Arsh Chauhan and Dev Singh as part of their Bachelor of Technology in Computer Science and Engineering. It outlines the methodology for predicting stock prices using machine learning and deep learning techniques, particularly focusing on LSTM networks. The report includes sections on literature review, problem formulation, system design, implementation, and future scope of the project.

Uploaded by

pawangandhar2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A

Project
Reporton
STOCK PREDICTION MODEL
Submitted in partial fulfillment of the
requirementsfor the award of the degree of

Bachelor of Technology
in
Computer Science and Engineering (Data Science)
by
Arsh Chauhan (22009715490001)
D e v S i n g h (2200971549003)

Under the Supervision


of

MR. VIJAY PRAKASH

Galgotias College of Engineering & Technology


Greater Noida, Uttar Pradesh
India-201306
Affiliated to

Dr. A.P.J. Abdul Kalam Technical University


Lucknow, Uttar Pradesh,
India-226031
December,
2023
GALGOTIAS COLLEGE OF ENGINEERING & TECHNOLOGY
GREATERNOIDA,UTTARPRADESH, INDIA- 201306.

CERTIFICATE

This is to certify that the project report entitled “STOCK MARKET


PREDICTION MODEL” submitted by Arsh Chauhan - Roll. No. 2200971549001, Dev
Singh - Roll. No. 2200971549003 to the Galgotias College of Engineering &
Technology, Greater Noida, Uttar Pradesh, affiliated to Dr. A.P.J. Abdul Kalam
Technical University Lucknow, Uttar Pradesh in partial fulfillment for the award of
Degree of Bachelor of Technology in Computer Science & Engineering is a bonafide
record of the project work carried out by the under my supervision during the
year 2024-2025.

Mr. Vijay Prakash Dr. Pushpa Chowdhary


Asst. Professor Professor and Head
[Link] CSE [Link] CSE

i
GALGOTIAS COLLEGE OF ENGINEERING & TECHNOLOGY
GREATERNOIDA,UTTARPRADESH, INDIA- 201306.

ACKNOWLEDGEMENT

We have taken efforts in this project. However, it would not have been possible
without the kind support and help of many individuals and organizations. We
would like to extend my sincere thanks to all of them.

We are highly indebted to Mr. Vijay Prakash for his guidance and constant
supervision. Also, we are highly thankful to them for providing necessary
information regarding the project & also for their support in completing the project.

We are extremely indebted to Dr. Pushpa Chowdhary, HOD, Department of


Computer Science and Engineering, GCET and Dr. Jaya Sinha / Mr. Vijay
Prakash , Project Coordinator, Department of Computer Science and
Engineering, GCET for their valuable suggestions and constant support
throughout my project tenure. We would also like to express our sincere thanks
to all faculty and staff members of Department of Com- puter Science and
Engineering, GCET for their support in completing this project on time.

We also express gratitude towards our parents for their kind co-operation and
encourage- ment which helped me in completion of this project. Our thanks and
appreciations also go to our friends in developing the project and all the people
who have willingly helped me out with their abilities.

Arsh Chauhan
Dev Singh

ii
ABSTRACT

Stock market prediction is the task of forecasting the


future value of company stocks and other financial assets
traded on an exchange. It is a challenging problem due to
the complex and dynamic nature of the stock market, as
well as the various factors that influence it. Machine
learning and deep learning techniques can help in
analyzing and predicting stock market trends by learning
from historical data and extracting relevant patterns. Some
of the popular machine learning methods for stock market
prediction are regression, classification, support vector
machine, and random forest. Among the deep learning
methods, long short-term memory (LSTM) is a widely used
technique for time series forecasting, as it can capture
long-term dependencies and handle sequential data. LSTM
networks are a type of recurrent neural network that have
four interacting layers and a memory cell that can store
and update information over time. By using LSTM
networks, investors can potentially improve their decision-
making and gain significant profits from the stock market.

iii
Contents

CERTIFICATE i

ACKNOWLEDGEMENT ii

ABSTRACT iii
TABLE OF CONTENTS iv

1 INTRODUCTION

1.1 Application
1.3 Objectives
1.4 Motivation
1.5 Organization of Report

2 LITERATURE REVIEW 4

3 PROBLEM FORMULATION 10

4 METHODOLOGY 11
4.1 Description of the Dataset
4.2 Proposed Work

5 SYSTEM DESIGN 18

5.1 System Components:


5.2 Technology Stack:

6 IMPLEMENTATION 24

6.1 Importing libraries


6.2 Data collection and processing
6.3 Moving Averages
6.4 Generate Machine Learning Model
6.4.1 Model fitting of LSTM & CNN
6.4.2 Hybrid modelling of LSTM+CNN
6.5 Training
6.6 Resultant with web app

7 CONCLUSION,LIMITATIONS AND FUTURE SCOPE 33

7.1 CONCLUSION:
7.2 LIMITATIONS:
7.3 FUTURE SCOPE:

IV
7.4 REFERENCES

V
Stock Market Prediction Model

Chapter 1. Introduction

1.1 Stock Price Prediction


Due to the high profit of the stock market, it is one of the most popular investments.
People investigated for methods and tools that would increase their gains while
minimizing the risk, as the level of trading and investing grew. Two stock exchanges
namely- the National Stock Exchange (NSE) and the Bombay Stock Exchange (BSE),
which are the most of the trading in Indian Stock Market takes place. Sensex and
Nifty are the two prominent Indian Market Indexes. Since the prices in the stock
market are dynamic, the stock market prediction is complicated.
From gradually the very past years some forecasting models are developed for this
kind of purpose and they had been applied to money market prediction. Generally,
this classification is done by:
1. Time series analysis
2. Fundamental analysis
3. Technical analysis
Time Series Analysis
The definition of forecasting can be like this the valuation of some upcoming result
or results by analyzing the past data. It extents different areas like industry and
business, economics andfinance, environmental science. Forecasting problems can
be classified as follows:
 Long term forecasting (estimation beyond 2 years)
 Medium-term forecasting (estimation for 1 to 2 years)
 Short term forecasting (estimation for weeks or months, days, minutes, few
seconds) The analysis [1] of time consist of several forecasting problems. The
designation of a timeseries is a linear classification of observations for a selected
variable. The variable of the stockprice in our case. Which can weather
multivariate or u n i v a r i a t e ? Only particular stock isincluded in the uni variate
data while more than one company for various instances of time isadded in
multivariate. For investigating trends, patterns and cycle or periods the analysis of
time series advantages in the present data. In spending money wisely an early data of
the bullishor bearish in the case of the stock market. Also, for categorizing the best-
performing companiesthe analysis of patterns plays its role for a specific period.
This makes forecasting as well astime series analysis an important research area.
1
Stock Market Prediction Model

Fundamental analysis
Fundamental Analysts are concerned with the business that reasons the stock itself.
They assess a company's historical performance as well as the reliability of its
accounts. Different performance shares are created that aid the fundamental
forecaster with calculating the validityof a stock, such as the P/E ratio. Warren Buffet
is probably the foremost renowned of all Fundamental Analysts.
What fundamental analysis within the stock market is making an attempt to reach, is
organizing the true value of a stock, that then will be matched with the worth it is
being listed on stock markets and so finding out whether or not the stock on the
market is undervalued or not. Find out the correct value will be completed by
numerous strategies with primarily a similar principle. The principle is that an
organization is price all of its future profits. Those future profits has to be
discounted to their current value. This principle goes on the theory that a business is
all about profits and nothing else. Differing to technical analysis, the fundamental
analysis is assumed as further as a long approach.
Fundamental analysis is created on conviction that hominoid society desires capital
to make progress and if the company works well, than it should be rewarded with an
additional capital and outcome in a surge in stock price. Fundamental analysis is
usually used by the fund managers as it is the maximum sensible, objective and
prepared from openly existing data likefinancial statement analysis.
One more meaning of fundamental analysis is on the far side bottom-up business
analysis, it discusses the top-down analysis since initial analyzing the world economy,
followed by country analysis and also sector analysis, and last the company level
analysis.
Technical analysis
Chartists or the technical analysts are not involved with any other of the
fundamentals of the company. The long run price of a stock based generally
exclusively on the trends of the past value (a form of time series analysis) that is set
by them. The head and shoulders or cup and saucer are various numerous patterns
that are employed. Also the techniques, patterns are used just like the oscillators,
exponential moving average (EMA), support and momentum and volume indicators.
Candlestick patterns, believed to have been initial developed by Japanese rice
merchants, are nowadays widely used by technical analysts. For the short-term
approaches, the technical analysis is used compare to long-run ones. So, in

2
Stock Market Prediction Model

commodities and forex marketsit is more predominant wherever traders target short-
term price movements. There are basic rules are used in this analysis, first all
significant about a company is already priced into the

3
Stock Market Prediction Model

stock, another being that the value changes in trends and finally that history (of
prices) tendsto repeat itself that is especially due to the market science.

1.2 Applications
 Business
 Companies
 Insurance company
 Government Agency
 This application is helpful for stock investors, sellers, buyers, brokers.

1.3 Objectives
A stock market prediction is described as an action of attempting to classify the
future value of the company stock or other financial investment traded on the stock
exchange. The forthcomingprice of a stock of the successful estimation is called the
Yield significant profit. This helps you to invest wisely for making good profits.

1.4 Motivation
The future price of a stock is the main motivation behind the stock price prediction.
In various cases like business and industry, environmental science, finance and
economics motivation canbe useful. The future value of the company’s stock can be
determining.

1.5 Organization of Report


Chapter 2 contains a literature survey that provides a summary of individual paper.
Chapter 3 provides an overview of existing work for stock price prediction that has
been doneusing LSTM, CNN and Hybrid Approach of LSTM+CNN.
Chapter 4 presents Implementation and its results, tools and technology used to
achieve this and datasets detail.
Chapter 5 contains a conclusion about stock price prediction and future work about
what you are wanted to do in future.

4
Stock Market Prediction Model

Chapter 2. Literature Survey

Stock Price Forecasting Using Data From Yahoo Finance and Analyzing Seasonal
andNonseasonal Trend:
Publication Year: 2018
Author: Jai Jagwani, Hardik Sachdeva, Manav Gupta, Alka Singhal
Journal Name: 2018 IEEE
Summary: To identify the [2] relationship between different existing time series
algorithms namely ARIMA and Holt Winter and the stock prices is the main objective
of the proposed work, for the investments a good risk-free range of stock prices are
analyzed and therefore better accuracy of the model can be seen. To find
distinguished results for shares in the stock market, the combination of two different
time series analysis models is opted by producing a range of prices to the consumer
of the stocks. Not complex in nature and estimation of valueswhich are purely based
on the past stock prices for non-seasonal or seasonal is the main advantage of
these models. In this experiment, some limitations are, the work that never takesinto
consideration and other circumstances like news about any new market strategy or
media release relevant to any company which may get affected by the prices of
stocks.

Stock Market Prediction Using Machine Learning:


Publication Year: 2018
Author: Ishita Parmar, Ridam Arora, Lokesh Chouhan, Navanshu Agarwal, Shikhin Gupta,
Sheirsh Saxena, Himanshu Dhiman
Journal Name: 2018 IEEE
Summary: In this paper studies, the use [3] of Regression and LSTM based Machine
learning to forecast stock prices. Factors measured are open, close, low, high and
volume. This paper was an attempt to determine the future prices of the stocks of a
company with improved accuracy and reliability using machine learning techniques.
LSTM algorithm resulted in a positive outcome with more accuracy in predicting
stock prices.

5
Stock Market Prediction Model

Multi-Category Events Driven Stock Price Trends


Prediction:Publication Year: 2018
Author: Youxun Lei, Kaiyue Zhou, Yuchen Liu
Journal Name: 2018 IEEE
Summary: In this paper, [4] multi-category news events are used as features to
develop stockprice trend prediction, model. The multi-category events are based on
already defined feature word dictionary. And we have employed both neural networks
and SVM models to analyse the relationship between stock price movements and
specific multi-category news. Experimental results showed that the predefined multi-
category news events are more improved than the baseline bag-of-words feature to
predict stock price trend. As compared to long term prediction, short term prediction
is better based on this study.

Share Price Prediction using Machine Learning Technique:


Publication Year: 2018
Author: Jeevan B, Naresh E, Vijaya kumar B P, Prashanth Kambli
Journal Name: 2018 IEEE
Summary: This paper is mostly [5] based on the approach of predicting the share
price usingLong Short Term Memory (LSTM) and Recurrent Neural Networks (RNN)
to forecast the stock value on NSE data using various factors such as current market
price, price-earning ratio, base value and other anonymous events. The efficiency of
the model is analysed by comparing the true data and the predicted data using an
RNN graph. Machine learning to predict stock price as see the model is able to
predict the stock price very close to the actual price where this model captures the
detailed feature and uses different strategies to make a prediction. The model train
for all the NSE data from the internet and recognize the input and group them and
provide input according to the user configuration this RNN based architecture proved
very efficient in forecasting the stock price by changing the configuration
accordingly which also use backpropagation mechanism while gathering and
grouping data to avoid mixing of data.

6
Stock Market Prediction Model

Stock Market Prediction Using Machine Learning


Techniques:Publication Year: 2016
Author: Mehak Usmani, Syed Hasan Adil, Kamran Raza, Syed Saad Azhar Ali
Journal Name: 2016 IEEE
Summary: The prominent aim of this study is to [6] forecast the market performance
of the Karachi Stock Exchange (KSE) on day closing using machine learning
algorithms. A variety of attributes as an input and forecasts market as Positive &
Negative is predicted by using the predictions model. The features employed in the
model are contains Oil rates, Gold & Silver rates, Interest rate, Foreign Exchange (FEX)
rate, NEWS and social media feed. The machinelearning algorithms including Single
Layer Perceptron (SLP), Multi-Layer Perceptron (MLP), Radial Basis Function (RBF)
and Support Vector Machine (SVM) are compared. The algorithm MLP that is multi-
layer perceptron performed best as compared to different methods. The foremost
helpful feature in predicting the market was the oil rate attribute. The end results of
this research confirm that machine learning techniques have the ability to predict the
stock market performance. The Multi-Layer Perceptron algorithm of machine
learning predicted 70% correct market performance.

Forecasting stock price in two ways based on LSTM neural


network:Publication Year: 2019
Author: Jingyi Du, Qingli Liu, Kang Chen, Jiacheng Wang
Journal Name: 2019 IEEE
Summary: The [7] LSTM neural network is used to predict Apple stocks by consuming
single feature input variables and multi-feature input variables to verify the forecast
effect of the model on stock time series. The experimental results show that the
model has a high accuracyof 0.033 for the multivariate input and is accurate, that is
in line with the actual demand. For the univariate feature input, the predicted squared
absolute error is 0.155, which is inferior to the multi-feature variable input.

7
Stock Market Prediction Model

Share Price Trend Prediction Using CRNN with LSTM Structure:


Publication Year: 2018
Author: Shao-En Gao , Bo-Sheng Lin ,Chuin-Mu Wang
Journal Name: 2018 IEEE
Summary: The [8] entire financial market majorly runs by the stock market and one
of the most attractive research issues is predicting stock price volatility. The
information of historical stocks for assuming the future stock price as well deep
learning method is applied to find approximate trend value of stock prices which are
mentioned in this paper. This paper not only stores the data of historical stock with
the time scale but also estimates prices of the future stock by a designed neural
network, this is due to the fact that the trend of stocks is usually connected to the
previous information of stock price. In this paper, the design of the neural network
proposed then with the memory performance the convolutional recurrent neural
network (CRNN) and for improving the long-term dependency of traditional RNN the
Long Short-term memory (LSTM) are the major components. Also to enhance the
accuracy as well as stability of prediction of the RNN LSTM architecture is put. This
paper accumulates a total of ten stock historic data to test and accomplish an
average error rate of 3.449 RMSE. [3]

Applying Long Short Term Memory Neural Networks for Predicting Stock Closing
Price:
Publication Year: 2017
Author: Tingwei Gao, Yueting Chai, Yi Liu
Journal Name: 2017 IEEE
Summary: To [9] assess the scheme that merges RNNs with informative input
variables whichcan give an improved and effective method to forecast the next-day
market is the main objective of this paper. The stock prediction model analyses using
long-short memory (LSTM) and stock basic trading data. On Standard & Poor’s
(S&P500) and NASDAQ, the case study relies. The stock closing price is more
precisely predicted using their forecasting system for the next day, which
outperforms the comparison models. This is the main discovery of the case study.
Five various models namely – moving average (MA), exponential moving average
(EMA), support vector machine (SVM) and LSTM are tested by them to demonstrate
the utilityof the system. The closing value of the next day is the predicting target.

8
Stock Market Prediction Model

Developing a Prediction Model for Stock Analysis:


Publication Year: 2017
Author: R. Yamini Nivetha, Dr. C. Dhaya
Journal Name: 2017 IEEE
Summary: A [10] relative study of the three algorithms namely - Multiple Linear
Regression(MLR), Support Vector Machine (SVM) and Artificial Neural Network (ANN)
is the main aimof this study. To predict the coming day market price, the prediction
will be determined by monthly prediction and daily prediction. Sentiment analysis with
the best prediction algorithmforecast the stock price. The less-developed algorithm
is the Multiple Linear Regression algorithm which calculates the correlation between
volume and the stock price. The result of the study shows that deep learning
algorithms are more developed than MLR algorithms and SVM algorithm.

Stock Price Prediction Based on Information Entropy and Artificial Neural Network:
Publication Year: 2019
Author: Zang Yeze, Wang Yiying
Journal Name: 2019 IEEE
Summary: One of the most important components of the financial system is the stock
market.
[11] For supporting the activity and evolvement, money is directed by the investors of
the associated frim. Along with information theory and Artificial Neural Network
(ANN) the combination of machine learning framework is formed. Information
entropy for non-linear causality and stock relevance also to facilitate ANN time
series modelling are creatively used by this method. The feasibility of this machine
learning framework is analysed with Amazon, Apple, Google and Facebook prices. A
time series analysis method based on information theory as well as LSTM to model
the stock price dynamics are outlined in this paper. The transfer entropy between
relevant variables to help LSTM time series prediction is merged in this modelling
infrastructure, thus the accuracy of the assumption outcome is broadly granted.
Modelled and real stock price is highly correlated while differ slightly in terms of
Mean Absolute Error (MAE) and Root Mean Square Error (RMSE) which are
investigated by the outcomes.

9
Stock Market Prediction Model

10
Stock Market Prediction Model

YEAR METHODOLOGY TECHNOLOGY RESULT

2007 Technological as well as fundamental YALE One of the first stock


prediction model
SVM
2018 technology SVM High impact model but
having less accuracy

2019 Fundamental as well as technological MACD High accuracy model due to


the use of powerful
ARMA computation machines and
algorithms
CNN
2022 technological SVM SVM with accuracy 78%

R-forest classifier R-forest classifier with 80.8%

Summary of Literature Survey:

Here, I have reviewed various approaches for Stock price prediction. All approaches
have their own advantages and disadvantages. CNN & LSTM is a most popular
algorithm to prediction the stock price but there are some challenges in this method
like use to need a lot of training data, High computational cost, without GPU data
quite slow to train, depend on any previous information for prediction. A hybrid
approach can be used to overcome these issues. While machine learning is able to
provide highly accurate prediction result using standards tools and also outperforms
all standard prediction methods.

11
Stock Market Prediction Model

Chapter 3. Problem Formulation

Problem formulation is the first and crucial step in any data science or machine learning
project. It involves defining the goal, scope, and expected outcomes of the project, as well as
identifying the data sources, features, and methods to use.

Some of the elements of problem formulation for stock prediction are:

 Goal: What is the objective of the stock prediction model? Is it to forecast the future
price, trend, volatility, or return of a stock or a portfolio of stocks? Is it to support trading
decisions, risk management, or portfolio optimization?
 Scope: What is the time horizon and frequency of the prediction? Is it short-term
(intraday, daily, weekly) or long-term (monthly, quarterly, yearly)? Is it continuous or discrete?
How far ahead do we want to predict?
 Outcomes: How do we measure the performance and success of the model? What are
the evaluation metrics and criteria? How do we compare the model with existing methods or
benchmarks?
 Data sources: What are the data sources and types that we can use for the model? Do
we have access to historical and real-time data? Do we use technical data (such as price,
volume, indicators) or fundamental data (such as earnings, dividends, ratios) or both? Do we
include external data (such as news, sentiment, macroeconomic factors) or not?
 Features: What are the features or variables that we can use for the model? How do we
select, extract, transform, and engineer the features? How do we handle missing, noisy, or
imbalanced data?
 Methods: What are the methods or techniques that we can use for the model? Do we
use traditional statistical methods (such as linear regression, ARIMA, GARCH) or machine
learning methods (such as SVM, random forest, LSTM) or both? How do we train, test, and
validate the model? How do we tune the hyper parameters and optimize the model?

12
Stock Market Prediction Model

Chapter 4. METHODOLOGY
Existing Work, Proposed Work and Data set

4.1 Overview of Existing Work


Stock Price Prediction by Machine Learning present to estimate the stock future
value and machine learning technique like LSTM for existing work. This machine-
learning algorithm is to perform the best predicting result of the stock future price.
LSTM is capable to catching themodifications in the behaviour of the stock price for
the indicated period in this proposed system.

Propose [3] a machine learning-based normalization for stock price prediction. The
dataset utilized for analysis was selected from Yahoo Finance. It consists of
approximately 9 lakh records of the required Stock price and other relevant data. The
data reflected the stock price at some time intervals for every day of the year. It
contains various data like date, symbol, open price, close price, low price, high price
and volume. Here, the data for only one company was considered. All the data was
available in a file of CSV format which was first read and transformed into a data
frame using the Pandas library in Python. The normalization of the data was
performed through the sklearn library in Python and the data were divided into
training and testing sets. The experiment set was kept as 20% of the available
dataset. This paper focuses on two architecture Regression-based Model and LSTM.
The Regression-based Model is employed for predicting unbroken values through
some given autonomous values Regressionuses a given linear function for predicting
continuous values of the most important amongst them and made the predictions
using these. LSTM architecture is able to identify the changes in trends which show
evident from the result. LSTM is identified as the best model for the proposed
methodology. This shows that the proposed system is capable of identifying some
interrelation within the data. In the stock market, there may not always follow the
same cycle or may not always be in a regular pattern for the changes that are
occurred. The period of the existence will differ and the existence of the trend is
based on the companies and the sectors. For investors, this type of analysis of
trends and cycles will obtain more profit. We must use networks like LSTM as they
rely on the current information to analyse various information.

13
Stock Market Prediction Model

4.2 Proposed Work

Fig 3.1 Proposed Workflow

The system presented here composes of five modules:-

1. Input as Dataset
2. Pre processing
3. Data splitting
4. Build & Model train Lstm, CNN and Hybrid approach of LSTM+CNN
5. Output as Predicted Result

Attribute such as: price of open, high, low, close, adjusted close price taken from
huge dataset are fed as input to the models for training to pre-process the data
techniques like normalization& one hot encoding in applied on dateset. After this data
is divided in two sets namely training& testing which are ratio of 80:20 respectively.
Then, this set are used to train a model using 3different approaches: LSTM, CNN and
Hybrid approach of LSTM+CNNS. Finally, all these modules are evaluated using Root
mean square error.

14
Stock Market Prediction Model

Working of LSTM model

Fig 3.2: LSTM Architecture [12]

Long Short Term Memory is a kind of recurrent neural network. In RNN output from
the last step is fed as input within the present step. It tackled the matter of long-term
dependencies of RNN within which the RNN will not predict the word hold on within
the long term memory however can offer additional accurate forecasts from the
recent info. Because the gap length will increases RNN does not offer an economical
performance. LSTM will by default retain the knowledge for a long period of time. It
is used for processing, predicting and classifying on the basis of time-series data.

 Structure of LSTM:
 LSTM has a chain organization that contains four neural networks and different
memoryblocks called cells.
 LSTM has a new structure called a memory cell. The memory cell makes the
decisions aboutwhat information to store, and when to allow reading, writing and
forgetting.
 A memory cell contains three main gates:
o Input gate- a new value flows into the memory cell.
o Forget gate- a value remains in the memory cell.
o Output gate- value in the memory cell is used to compute the output.

15
Stock Market Prediction Model

 Applications of LSTM includes:


 Language Modelling
 Machine Translation
 Image Captioning
 Handwriting generation
 Question Answering Chat bot

16
Stock Market Prediction Model

Working of CNN model

Fig 3.3: CNN Architecture [13]

 Layer of CNN model:


o Convolution
o MAX Pooling
o Dropout
o Flatten
o Dense
o Activation
 Convolution: In the Convolution extract the featured from the input image. It given the
outputin matrix form.
 MAX Pooling: In the MAX polling it takes the largest element from a rectified feature map.
 Dropout: Dropout is randomly selected neurons are ignored during training.
 Flatten: Flatten feed output into a fully connected layer. It gives data in list form.
 Dense: A Linear operation in which every input is connected to every output by
weight. Itfollowed by a nonlinear activation function.
 Activation: It used sigmoid function and predict the probability 0 and 1.

 Applications of CNN
includes:
 Decoding Facial Recognition
 Analyzing Documents

17
Stock Market Prediction Model

Hybrid Approach of LSTM + CNN


In the hybrid approach, the Convolutional Neural Networks (CNNs) offer benefits in
choosing sensible options and Long Short-Term Memory (LSTM) networks have
proven sensible skills to find out to learn sequential data. Each approaches are
reported to produce improved result. CNNs to possess to convolute filters over every
input layer so as to get the simple options and CNNs have shown enhancements in
computer vision, natural language processing and differenttasks [14]. CNN may be a
powerful tool to pick out features in order to improve the predictionaccuracy [15]. The
capabilities of LSTMs in learning data series by considering the previous outputs [16]

The multiple convolutional filters slide over the matrix to produce a new feature map
and also the filters have numerous completely different sizes to generate different
features. The Max- pooling layer is to calculate the most value as a corresponding
feature to a particular filter. The output vectors of the Max-pooling layer become
inputs to the LSTM networks to measure the long-run dependencies of feature
sequences. One in all the benefits of the LSTMs is that the ability to capture the
sequential data by considering the previous data. This layer takes the output vectors
from the dropout layer as inputs. This layer include a set number of units or cellsand
also the input of every cell is that the output from the dropout layer. The final output
of this layer has the same number of units within the network the outputs from LSTMs
are mergedand combined in one matrix then passed to a fully connected layer. The
array is converted into a single output in the range between 0 and 1 using the fully
connected layer, in order to be finally classified using sigmoid function [17].

18
Stock Market Prediction Model

4.3 Data set,


Data set Detail
The data-set is driven directly from the Yahoo finance, which consists of the stock’s
historical data from the National stock exchange (NSE), NASDAQ, S&P500 and
captures the daily information of each stock from all the eminent stock exchanges
around the world. It collects different sectors of stock data, including Banking,
Pharmaceutics, Petroleum, Software and Textiles and it including the opening price,
the highest price, the lowest price, the closing price, the adjusted closing price and
the volume of stock.

Some of the popular stocks that the people might heard of

 GOOGLE

 APPLE

 TCS

 HDFC

 BANK OF AMERICA

 JP MORGAN CHASE &CO

 IOCL

 SHELL PLC

 EXXON MOBIL CORP.

 LUX INDUSTRIES

 RAYMOND Ltd.

 SIYARAM SILK MILLS Ltd.

19
Stock Market Prediction Model

CHAPTER. 5 SYSTEM DESIGN AND TECHNOLOGY STACK

A system design for stock prediction model using machine learning can be
described as follows:

 The system consists of four main components: data collection, data preprocessing,
model training, and model deployment.
 Data collection: The system collects historical and real-time stock data from various
sources, such as APIs, web scraping, or databases. The data can include technical indicators,
such as price, volume, and moving averages, as well as fundamental indicators, such as
earnings, dividends, and ratios. The system can also collect external data, such as news,
sentiment, and macroeconomic factors, that may affect the stock market.
 Data preprocessing: The system performs various data cleaning and transformation
tasks, such as handling missing, noisy, or imbalanced data, scaling and normalizing the data,
creating and selecting features, and splitting the data into training, validation, and test sets.
The system can also apply techniques such as feature engineering, dimensionality reduction,
and time series analysis to enhance the data quality and relevance.
 Model training: The system uses machine learning and deep learning methods to train
and evaluate the stock prediction model. The system can use traditional statistical methods,
such as linear regression, ARIMA, and GARCH, or machine learning methods, such as SVM,
random forest, and XGBoost, or deep learning methods, such as LSTM, CNN, and Transformer,
or a combination of them. The system can also use techniques such as hyper-parameter
tuning, cross-validation, and ensemble learning to optimize the model performance and
accuracy.
 Model deployment: The system deploys the trained model to a production environment,
where it can receive new data and make predictions in real-time. The system can also monitor
and update the model periodically, based on the feedback and performance metrics. The
system can also provide a user interface, such as a dashboard or an app, to display the
predictions and insights to the end-users.

20
Stock Market Prediction Model

TECHNOLOGICAL STACK:
Tool & Technologies used -
PYTHON
The language of select for this project was Python. This was a straightforward call
for many reasons.
1. Python [19] as a language has a vast community behind it. Any problems which
may be faced is simply resolved with visit to Stack Overflow. Python is the
foremost standard language on the positioning that makes it is very straight
answer to any question.
2. Python [19] is an abundance of powerful tools ready for scientific computing
Packages. The packages like NumPy, Pandas and SciPy area unit freely available
and well documented. These Packages will intensely scale back, and variation the
code necessary towrite a given program. This makes repetition fast.
3. Python is a language as [19] forgiving and permits for the program that appear as
if pseudo code. This can be helpful once pseudo code give in tutorial papers
should be required andverified. Using python this step is sometimes fairly trivial.
However, Python is [19] not without its errors. The python is dynamically written
language and packages are area unit infamous for Duck writing. This may be
frustrating once a packagetechnique returns one thing that, for instance, looks like
an array instead of being an actual array. Plus the standard Python documentation
did not clearly state the return type of a method,this can’t lead without a lot of trials
and error testing otherwise happen in a powerfully written language. This is a
problem that produces learning to use a replacement Python package or library
more difficult than it otherwise may be.

Libraries that were used in the creation as well as deployment of the model:
 Numpy
 Pandas
 yFinance
 Matplotlib
 Scipy

21
Stock Market Prediction Model

 Keras
 Tensorflow
 Scikit-Learn
 Streamlit
NUMPY

Numpy is python package which provide scientific and higher level mathematical
abstractions wrapped in python. It is [20] the core library for scientific computing, that
contains a providetools for integrating C, strong n-dimensional array object, C++ etc. It is
also useful in randomnumber capability, linear algebra etc.
Numpy’s array type augments the Python language with an efficient data structure
used for numerical work, e.g., manipulating matrices. Numpy additionally provides
basic numerical routines, like tools for locating Eigenvectors

PANDAS
The term "Pandas" refers to an open-source library for manipulating high-performance data in
Python. This instructional exercise is intended for the two novices and experts.

It was created in 2008 by Wes McKinney and is used for data analysis in Python. Pandas is an
open-source library that provides high-performance data manipulation in Python.

MATPLOTLIB
Matplotlib is a plotting library for the Python programming language and its numerical
mathematics extension NumPy. It provides an object-oriented API for embedding plots into
applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK. There is also
a procedural "pylab" interface based on a state machine (like OpenGL), designed to closely
resemble that of MATLAB, though its use is discouraged.[3] SciPy makes use of Matplotlib.

YFINANCE
The yfinance is one of the famous modules in Python, which is used to collect online data, and
with it, we can collect the financial data of Yahoo. With the help of the yfinance module, we
retrieve and collect the company's financial information (such as financial ratios, etc.)

22
Stock Market Prediction Model

SCIPY
SciPy is a free and open-source Python library used for scientific computing and technical
computing. It is a collection of mathematical algorithms and convenience functions built on
the NumPy extension of Python. It adds significant power to the interactive Python session by
providing the user with high-level commands and classes for manipulating and visualizing data.
As mentioned earlier, SciPy builds on NumPy and therefore if you import SciPy, there is no
need to import NumPy.

SCIKIT LEARN

Scikit-learn could be a free machine learning library for Python. It features numerous
classification, clustering and regression algorithms like random forests, k-neighbours,
support vector machine, and it furthermore supports Python scientific and numerical
libraries like SciPy and NumPy.
In Python Scikit-learn is specifically written, with the core algorithms written in
Cython to get the performance. Support vector machines are enforced by a Cython
wrapper around LIBSVM .i.e., linear support vector machines and logistic regression
by a similar wrapper around LIBLINEAR.

TENSORFLOW

In the TensorFlow has an open source software library for numerical computation using
data flow graphs. Inside the graph nodes represent mathematical formulae, the edges of
graphrepresent the multidimensional knowledge arrays (tensors) communicated between
them. Theversatile architecture permits to deploy the computation to at least one or many
GPUs or CPUs in a desktop, mobile device, servers with a single API. TensorFlow was
firstly developing by engineers and researchers acting on the Google Brain Team at
intervals Google's Machine Intelligence analysis organization for the needs of conducting
deep neural networks research and machine learning, but, the system is generally
enough to be appropriate in a wide range of alternate domains as well.
Google Brain's second-generation system is TensorFlow. Whereas the reference
implementation runs on single devices, TensorFlow can run on multiple GPUs and
CPUs. TensorFlow is offered on Windows, macOS, 64-bit Linux and mobile
computing platforms together with iOS and Android.
23
Stock Market Prediction Model

KERAS

Keras is a high-level neural networks API, it is written in Python and also capable of
running on top of the Theano, CNTK, or. TensorFlow. It was developed with
attention on enabling quick experimentation. having the ability to travel from plan to
result with the smallest amount doable delay is key to doing great [Link]
permits for straightforward and quick prototyping (through user-friendliness,
modularity, and extensibility). Supports each recurrent networks and convolutional
networks, also as combinations of the 2. Runs seamlessly on GPU and CPU. The
library contains numerous implementations of generally used neural network
building blocks like optimizers, activation functions, layers, objectives and a number
of tools to create operating with text and image data easier. The code is hostedon
GitHub, and community support forums embody the GitHub issues page, a Gitter
channeland a Slack channel.

STREAMLIT

Streamlit is a free and open-source framework to rapidly build and share beautiful
machine learning and data science web apps. It is a Python-based library specifically
designed for machine learning engineers. Data scientists or machine learning engineers
are not web developers and they're not interested in spending weeks learning to use
these frameworks to build web apps. Instead, they want a tool that is easier to learn and
to use, as long as it can display data and collect needed parameters for modeling.
Streamlit allows you to create a stunning-looking application with only a few lines of
code.

24
Stock Market Prediction Model

COMPILER OPTION
Anaconda is free premium open-source distribution of the R and Python
programming languages for scientific computing, predictive analytics, and large-
scale process that aim is to modify package managing and deployment. Package
versions unit managed by the package management system conda.

JUPITER NOTEBOOK
The Jupyter Notebook is an open-source web application that enables to making
and sharing documents that contain visualizations, narrative text, live code and
equations. Uses include: data , data visualization, data transformation, statistical
modelling, machine learning, numerical simulation, data cleaning and much more.

VS CODE
Visual Studio Code is a lightweight but powerful source code editor which runs on your
desktop and is available for Windows, macOS and Linux. It comes with built-in support for
JavaScript, TypeScript and [Link] and has a rich ecosystem of extensions for other
languages and runtimes (such as C++, C#, Java, Python, PHP, Go, .NET). Begin your journey
with VS Code with these introductory videos.

25
Stock Market Prediction Model

CHAPTER. 6 IMPLEMENTATION

IMPORTING LIBRARIES
import numpy as np
import pandas as pd
import [Link] as plt
import yfinance as yf
from [Link] import MinMaxScaler
from [Link] import Dense, Dropout, LSTM
from [Link] import Sequential
from [Link] import load_model
import streamlit as st

DATA COLLECTION AND PROCESSING


data = [Link](stock, start, end)
data
date open high low close [Link]

2013-01-
0 17.918339 18.107130 17.846855 18.013729 18.013729 102033017
02

2013-01-
1 18.055573 18.229919 17.950716 18.024191 18.024191 93075567
03

2013-01-
2 18.165413 18.467529 18.124067 18.380356 18.380356 110954331
04

2013-01-
3 18.317591 18.415474 18.196297 18.300158 18.300158 66476239
07

2013-01-
4 18.319834 18.338762 18.043119 18.264042 18.264042 67295297
08

... ... ... ... ... ... ... ...

2023-12-
2749 131.294006 131.449997 129.399994 130.630005 130.630005 24117100
04

2023-12-
2750 130.369995 133.539993 129.729996 132.389999 132.389999 19235100
05

2023-12-
2751 132.899994 133.309998 131.309998 131.429993 131.429993 16360600
06

2023-12-
2752 136.600006 140.000000 136.229996 138.449997 138.449997 38419400
07

2023-12-
2753 135.660004 137.990005 135.570007 136.639999 136.639999 22990900
08

Moving Average(MA) for the last 100 days

26
Stock Market Prediction Model

ma_100_days = [Link](100).mean()

PLOTTING

[Link](figsize=(8,6))
[Link](ma_100_days, 'r')
[Link]([Link], 'g')
[Link]()

27
Stock Market Prediction Model

MA for the last 200 days

ma_200_days = [Link](200).mean()

PLOTTING

[Link](figsize=(8,6))
[Link](ma_100_days, 'r')
[Link](ma_200_days,'b')
[Link]([Link],'g')
[Link]()

28
Stock Market Prediction Model

MODEL FITTING OF LSTM & CNN

model = Sequential()
[Link](LSTM(units = 50, activation = 'relu', return_sequences = True,
input_shape = (([Link][1],1))))
[Link](Dropout(0.2))

[Link](LSTM(units = 60, activation='relu', return_sequences = True))


[Link](Dropout(0.3))

[Link](LSTM(units = 80, activation = 'relu', return_sequences = True))


[Link](Dropout(0.4))

[Link](LSTM(units = 120, activation = 'relu'))


[Link](Dropout(0.5))

[Link](Dense(units =1))

29
Stock Market Prediction Model

Summary of our hybrid LSTM + CNN model

After generating training dataset, to apply training I have created LSTM,


CNN & Hybrid Approach of LSTM + CNN network using KERAS. several
variations of this architecture using various numbers of layers and
various size of Bottleneck layer.

APPLY TRAINING
30
Stock Market Prediction Model

31
Stock Market Prediction Model

Resultant With the help of Web App

The web app which was made with help of python and few of it’s libraries is used
to project the model we have prepared, the webapp is user interactive and
dynamic.
Not just that you can actually predict any stock which is listed on the yahoo
finance,
All you need to do is type the company/corporation abbreviation which is listed
on the yahoo finance, it will then extract the stock data using yfinance and then it
will plot the graphs regarding:
 Price Vs Moving Averages of past 50 days, 100 days and 200 days.
 Price Vs predicted price

32
Stock Market Prediction Model

PRICE VS MA50

PRICE VS MA50 VS MA 100

33
Stock Market Prediction Model

PRICE VS MA100 VS MA200

ORIGINAL PRICE VS PREDICTED PRICE

34
Stock Market Prediction Model

Chapter 7

Conclusion

Internet has a growing rate and the rate with which the data is being
generating , it has become almost impossible for us to handle and take
care of such data. Such an enormous amount of information is processing
nowadays that it becomes difficult for us to study their behavior or to
conclude anything from them, thus making it so hard to summarize it.
Then comes Machine Learning algorithms that helps us in understanding
such datasets. Technical and fundamental analysis have showed a little
work in the experiments carried out. Machine learning algorithm was
applied to various data sources of different companies. Report highlights
that stock market is prone to differences. Report also concludes that
predicting stock prices is extremely tough job.

35
Stock Market Prediction Model

The main objective of this system is providing ways to heal the stock
market. Our task is such that it can’t be used for official model
because of its limitedness. We have reached to a certain degree of
accuracy by incorporating the limited number of parameters. Since
stock market is highly fluctuating so to predict everything with great or
large accuracy can’t be taken into account. So our model that we have
created has only depends on the selected number ofparameters and
their relationship with the share price.
By this basic learning of Extractive and Abstractive Method and tried
to implement the initial one. We have successfully taken a dataset of
different companies and performed data cleaning and normalization.
Then we have split the dataset into testing and training in which
testing dataset is almost 10%. After that, we have created Linear
Regression, support regression model and Decision Tree algorithm to
trained our model on dates and prices.
Predicting the stock market forecast is always challenging and a
tedious job, specially a challenging work for business analysts. We
have calculated our prediction with an overallaccuracy of 60% to 65%
approx. To achieve accuracy higher than this, we definitely need to
research in deep.

custom list of capabilities and acquire forecasts with incredible proficiency. We


have directed tests utilizing non straight RBF portion which is demonstrating
extensive precision in result. What's more, the most significant thing, the above
investigation helped us in anticipating the future result of costs of organization
yet they additionally gave us important and profound bits of knowledge about the
idea of information which is positively can be utilized to prepare our SVM
classifiers in a superior manner. The venture can be extended further by ad
labeling highlight list and with various classifier. Future work should be possible

36
Stock Market Prediction Model

by including the unaided preprocessor use alongside the direct classifier.


Based on the performances of all the three Algorithms, Linear Regression,
Support Vector Machine, and Decision Tree, we concluded that Decision Tree is
best among the three and second comes the Linear Regression based on the
RMSE values, RMSE(DT)<RMSE(LR)<RMSE(SVM)
As the RMSE should be least which means the error or difference between the
Actual or Y_test and Predicted_Y, so it should be less because if they will be less
there would be more chances of the two to be close enough and thus a good
prediction to be called.
RMSE(DT)-833.0699 RMSE(LR)-923 RMSE(SVM)-5051.96
Also based on the Pie Chart if we calculate the modular difference between
Actual and Predicted mean, we would easily conclude that Decision Tree(DT) is
the best as it have a modular difference of 35.37, Linear Regression being the
second in the race with 76.85 and SVM at the last having 1255.22 mean
difference.

Future scope of improvement

1. Our dataset and analysis method can improve potentially

2. If more accurate algorithm and refined data with precise research is

taken then future scope can be done with possible improvement.

3. Introduction of twitter feeds.

4. Advanced predictions form news feed and different websites can be

37
Stock Market Prediction Model

taken for better results.

5. Refining key phase extraction and doing more work will definitely

produce betters results.

Limitations:

Stock market prediction using machine learning is a challenging and

fascinating research area, but it also has some limitations. Here are

some of them:

 Inaccuracy of predictions: Machine learning algorithms become more

competent and accurate over time, but they are not perfect.

38
Stock Market Prediction Model

 Inability to forecast everything: Machine learning models rely on historical

data and existing factors, but they cannot account for unforeseen events or

black swan scenarios that may affect the stock market.

 Complexity and cost: Developing and setting up a machine learning solution

for stock market prediction is costly and resource-intensive. It requires a lot

of data, computing power, and expertise.

References

1. S. M. Idrees, M. A. Alam and P. Agarwal, "A Prediction Approach for Stock Market
Volatility Based on Time Series Data," in IEEE Access, vol. 7, pp. 17287-17298, 2019.
2. Z. Wang, S. Ho and Z. Lin, "Stock Market Prediction Analysis by Incorporating Social and
News Opinion and Sentiment," 2018 IEEE International Conference on Data Mining
Workshops(ICDMW), Singapore, Singapore, 2018,
3. S. Sarode, H. G. Tolani, P. Kak and C. S. Lifna, "Stock Price Prediction Using Machine
Learning Techniques," 2019 International Conference on Intelligent Sustainable Systems
(ICISS), Palladam, Tamilnadu, India, 2019,
4. S. D. Bekiros, "Sign Prediction and Volatility Dynamics With Hybrid Neurofuzzy
39
Stock Market Prediction Model

Approaches," in IEEE Transactions on Neural Networks, vol. 22, no. 12, pp. 2353-2362, Dec.
2011.
5. P. Chang, C. Fan and C. Liu, "Integrating a Piecewise Linear Representation Method and a
Neural Network Model for Stock Trading Points Prediction," in IEEE Transactions on
Systems, Man, and Cybernetics, Part C (Applications and Reviews), vol. 39, no. 1, pp. 80-92,
Jan. 2009.

40

You might also like