0% found this document useful (0 votes)
25 views8 pages

Stock Price Prediction Using RNN LSTM Based Machine

This research article presents a machine learning model using RNN LSTM for predicting stock prices, specifically for TCS, utilizing data from January 2013 to May 2018. The model involves data preprocessing, training, and evaluation, achieving a mean absolute percentage error of 3.57854% and an accuracy of 91.4221%. The findings suggest that RNN LSTM models can provide more accurate stock price forecasts compared to traditional methods.

Uploaded by

Kangana W. M
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)
25 views8 pages

Stock Price Prediction Using RNN LSTM Based Machine

This research article presents a machine learning model using RNN LSTM for predicting stock prices, specifically for TCS, utilizing data from January 2013 to May 2018. The model involves data preprocessing, training, and evaluation, achieving a mean absolute percentage error of 3.57854% and an accuracy of 91.4221%. The findings suggest that RNN LSTM models can provide more accurate stock price forecasts compared to traditional methods.

Uploaded by

Kangana W. M
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
You are on page 1/ 8

RESEARCH ARTICLE | JULY 11 2024

Stock price prediction using RNN LSTM based machine


learning model 
Ruchi 

AIP Conf. Proc. 3121, 040021 (2024)


https://doi.org/10.1063/5.0222232


View Export
Online Citation

19 July 2024 04:41:08


Stock Price Prediction using RNN LSTM Based Machine
Learning Model
Ruchi
ECE Department, Chandigarh University, Mohali, Punjab, India

[email protected]

Abstract. RNN LSTM (recurrent neural networks and long short-term memory) models are kind of deep learning
architecture well-suited for analyzing time-dependent data by maintaining memory states. This article presents an ML
based RNN LSTM models for stock price prediction. The API Quandl is used to get the data of stock TCS from 1st January
2013 to 18th May 2018.The data is then pre- processed which involves tasks such as data normalization, feature
engineering, and dividing the data into training and testing sets. For training, the data has been taken from 1st January 2013
to 13th April 2017 followed by testing data from 13th April 2017 to 9th May 2018. Subsequently, the RNN LSTM model
is constructed, consisting of multiple LSTM layers followed by fully connected layers for prediction. The LSTM layers
allow the model to capture sequential patterns, while the fully connected layers help map the learned features to the desired
output, which is future stock prices. After training, its predictive performance is assessed by evaluation using test dataset.
Evaluation metrics like mean squared error (MSE), root mean squared error (RMSE), and mean absolute percentage error

19 July 2024 04:41:08


(MAPE) have been used to quantify the model's accuracy.

1. INTRODUCTION

Stock price prediction is a crucial task in the field of finance and investment. Investors, traders, and ana-lysts are
constantly seeking accurate methods to forecast future stock prices, enabling them to make in-formed decisions about
buying or selling stocks. The application of various machine learning (ML) ap-proaches for predicting stock market
has gained attention due to advancements in technology and the need for accurate forecasts. Various ML algorithms,
including support vector machines, neural networks, and decision trees [1], are employed despite the efficient market
hypothesis suggesting unpredictable stock prices. Researchers have explored improved neural network techniques,
such as long short-term neural networks (LSTM), for predicting stock prices in specific markets like the Chinese stock
market [2]. Soft computing [3] and ML-based computational models were discussed to address the challenges of ana-
lyzing the data related to stock’s market and improve prediction accuracy. Ensemble learning techniques [4], such as
blending, boosting, and bagging, have been evaluated using different classifiers and regres-sors.
Deep learning models, including convolutional neural networks (CNN) and LSTM [5], have shown prom-ise in
predicting stock prices and overcoming the limitations of linear models. Additionally, ensemble classifiers that
combine genetic algorithms and support vector machines [6] have demonstrated better performance than traditional
ML algorithms. Comparisons among classification and regression models have revealed the superiority of deep
learning models based on LSTM networks. Overall, these research studies highlight the potential of ML and deep
learning algorithms in predicting stock market trends and provide valuable insights for future advancements in the
field. One approach that has gained significant attention and success in recent years is using Recurrent Neural
Networks (RNNs) with Long Short- Term Memory (LSTM) cells.
RNNs are a class of artificial neural networks specifically designed to handle sequential data, making them suitable
for analyzing time series data like stock prices. Fig.1 shows a simple architecture of RNN, which clearly depicts that
at one instance of time , the output from a node is propagated to the input at next time instance which adds to itself to
be the output of that node; recurrently exploiting the neuron node to flow multiple node elements to create RNN

Recent Advancements in Communication, Computing, and Artificial Intelligence (RACCAI-2023)


AIP Conf. Proc. 3121, 040021-1–040021-7; https://doi.org/10.1063/5.0222232
Published under an exclusive license by AIP Publishing. 978-0-7354-4998-5/$30.00

040021-1
LSTM, a type of RNN, is particularly effective at capturing long-term dependencies and patterns in time series
data. This makes it an ideal choice for modelling and predicting stock prices, which are known to exhibit complex
temporal relationships. The underlying principle of using RNN-LSTM for stock price prediction involves training a
neural network on historical stock price data and then using the learned patterns to make predictions on unseen data.
The network takes into account previous price values and other relevant features to generate forecasts.
The usage of the RNN LSTM model to predict the stock price is presented in this paper which is mainly organized
into five sections. Section I Introduces the concept. Section II presents the various similar works done in literature.
The proposed model has been discussed in section III. Further results have been dis-cussed in section IV. The
conclusion and complete work is presented in section V.

19 July 2024 04:41:08


FIGURE 1. An illustration of Recurrent Neural Network

2. BACKGROUND SURVEY
The use of machine learning (ML) methods to forecast the performance of a stock market group in fu-ture is
explored [1]. The study uses four groups from the Tehran stock exchange and evaluates six tree-based models and
three neural network- based algorithms. The study notes that error values generally increase as the number of days
ahead increases, but there is some variability due to deficiencies in the prediction ability of some models in specific
cases. Improved long short-term neural network techniques to predict stock prices is proposed in [2] wherein the
concept of stock vectors to vectorize high-dimensional historical data for input to the neural network is proposed to
predict stock prices in the Chi-nese stock market, specifically the Shanghai A- shares market.
The work in [3] highlights the challenges in analyzing stock market data and proposes using ML and soft
computing algorithms for prediction and analysis. It focuses on ensemble learning techniques and compares the
performance of different ensemble classifiers and regressors using stock data from multiple continents. The study aims
to evaluate and compare the performance of various ensemble methods, such as blending, boosting, bagging, and
super learners, using decision trees, support vector machines, and neu-ral networks as base models. It provides
guidance on the most effective ensemble techniques for stock market prediction and inform future research in this
area, making it relevant and valuable for beginners in the field.
Machine learning algorithms, like neural networks and LSTM-based RNNs, are increasingly used in quantitative
finance for predicting asset prices [4]. Forecast of adjusted closing prices for a portfolio is done using an LSTM-based
algorithm wherein optimizing the number of epochs and the training data length is crucial for accuracy. Promising
results were observed in tracking opening price growth for two assets. The MARS model performs best in capturing
recession and upturn patterns, emphasizing the im-portance of studying a company's pattern for accurate predictions.
The primary focus in [5] is on using deep learning models, including CNN, LSTM, RNN, MLP, and SVM, for
stock price prediction using the NSE dataset of India. Results show that CNN outperforms exist-ing models and has
the potential to predict stock prices in other markets. Deep learning models overcome the limitations of linear models
and handle complex datasets. The article also reviews studies using deep learning for stock market prediction and

040021-2
discusses techniques like PSO, LSSVM, genetic algorithms, and wavelet transform to improve predictions. It is
observed that CNN outperforms existing models and has the potential to predict stock prices in other markets. The
soft computing and ML have been used for pre-diction and analysis in [6]. The primary focus is on ensemble learning
techniques and evaluating and comparing the execution times, accuracy, and error metrics of various ensemble
methods, such as blend-ing, boosting, bagging, and super learners, using decision trees, support vector machines, and
neural net-works as base models.
The study introduces GASVM, an ensemble classifier combining Genetic Algorithm (GA) and Support Vector
Machines (SVM) for accurate stock price prediction. GASVM outperforms traditional ML algo-rithms and eliminates
manual parameter optimization. The study emphasizes the importance of accurate prediction for profitable outcomes
and highlights the potential of intelligent systems and soft computing in stock market analysis. GASVM demonstrates
promising results in forecasting price movement on the Ghana Stock Exchange ten-days ahead [6]. Eight classification
and regression models, including logistic regression, decision trees, boosting, and artificial neural networks, are
compared, along with two deep learning models based on LSTM and CNN networks. Extensive performance analysis
is provided for each model. The results show that the deep learning model using an LSTM network outperforms all
other mod-els [7].The paper explores predicting stock prices using pattern analysis and introduces a deep-learning
LSTM network. MARS model performs best in capturing recession and upturn patterns, emphasizing the importance
of studying a company's pattern for accurate predictions [8].
Machine learning techniques improve stock price prediction by handling the non-linear and unpredictable nature
of the market. Neural networks like ANN, CNN, RNN, and LSTM are utilized. Data from various sources are used,
and ensemble methods like Random Forest are effective in analyzing stock market data. The models are evaluated
using RMSE, MAPE, and MBE to minimize prediction errors [9]. LSTM, CNN, and GA models are effective. External
factors impact trends. SVM, neural networks used. Optimization improves. Decision support system proposed.
Reliable data and accurate outputs were achieved [10].The traditional stock market prediction was deemed impossible,
but deep learning models like DNN have proven effective. This paper proposes a DNN-based model using 2D PCA.
The experiment shows im-proved efficiency and accuracy compared to other models. Incorporating deep learning and
appropriate data sets enhances stock trend prediction [11]. ML algorithms analyze large data volumes for stock price

19 July 2024 04:41:08


predictions. SVM, ANN, and decision trees are popular methods. Despite efficient market hypothesis, investors use
fundamental and technical analysis. Regression approaches are highlighted [12].

3. PROPOSED MODEL
The RNN LSTM model for to forecast the price of stock TCS is proposed in this section. The first step in the
process is data collection for which API Quandl has been used. The next step in the process is data pre-processing
followed by model training and testing. The last step in implementation of the model is model evaluation and
measuring the accuracy of the proposed model. The details of the proposed model are explained in each step.

A. Upload API: Using an API to retrieve stock data in Python is a useful way to gather financial data for analysis
or machine learning applications. One popular API provider is Quandl, which offers a wide range of financial and
economic data. To use the Quandl API in Python, first sign up for a free Quandl account and obtain an API key. Then
constructed an API request URL that includes your API key, the stock symbol required to retrieve data for, and the
date range of the data. Fig 2 shows the start and the end date of pre-processed stock data TCS with the open and close
values of the stock on the respective day.
B. Read data from Quandl API: To read an API label in Python, import the `API label` imposed and use the
`get()` function to create a file object. Then, API reader object is created and the file object is used to iterate over the
rows in the API label. The process involves several steps, including opening the file, creat-ing a reader object, iterating
over the rows, processing the data, and closing the file.
C. Split data: To implement the respective model the stock data TCS from 1st January 2013 to 18th May 2018
is collected and divided into training and testing data. The data selected for training the RNN LSTM model ranges
from 1st January 2013 to 13th April 2017 and the testing from 13th April 2017 to 9th May 2018. Also, the training
data is further split into validation set from 6th June 2016 to 30th April 2017 to check the performance and
generalization ability of a ML model during the model development and train-ing process.

040021-3
D. Create LSTM layers: To form LSTM layers for model implementation, the necessary libraries -Sequential,
LSTM, and Dense are imported from the Keras module. After importing the modules, model architecture is defined
as shown in Fig 3.
E. Plotting model: Once the model has been built, Python's plotting libraries, matplotlib and Seaborn, have been
used to visualize the results. By visualizing the results, one can gain insights into how the mod-el is performing and
identify any areas where it may need improvement. For this, validation set from the training data is formed which is
used to evaluate the model during training and tune its hyper parameters. Fig 4 compares the prediction on training
data superimposed along with the prediction on the validation dataset. “y_train” shows the original dataset of closing
values of TCS stocks used for training the model.

19 July 2024 04:41:08


FIGURE 2. Opening and Closing Price

FIGURE 3. Model Architecture

040021-4
F. Validate and verify model: Evaluation metrics and visualization techniques validate and verify a model to
help ensure that it is accurate and can be generalized to new data.

4. RESULTS AND DISCUSSIONS


By the means of Recurrent Neural Network, the data set is analyzed. Then tested on TCS’s predicted clos-ing
prices are subjected RMSE and MAPE for getting the optimum minimalized error. The visual represen-tation of the
prediction of TCS stock data during training (1st January 2013 to 13th April 2017) and test-ing (13th April 2017 to
9thMay 2018) and the original trend is shown in Fig 5. “Y” shows the original dataset of closing values of TCS stocks
used for training the model.
In Fig. 6 the title of the plot is "Training, Val error- TCS stock", indicating that it pertains to the TCS stock and
displays both the training and validation errors. The x-axis is labelled as "Epochs", representing the number of training
iterations, and the y-axis is labelled as "Error", indicating the magnitude of the error. Fig 7 shows the training and
validation loss on the same stock. The training loss curve (in blue) indicates how well the model is fitting the training
data, while the validation loss curve (in red) indicates how well the model generalizes to unseen data. The calculated
accuracy of the proposed model is 91.4221% and the mean absolute error is 101.56925 which is 3.57854%.

19 July 2024 04:41:08


FIGURE 4. Comparison Between the Prediction on Training Data and the Validation Set With the Original Closing Values
of TCS Stocks.

5. CONCLUSION
Predicting stock prices is a complex task due to the volatile nature of financial markets and the interde-pendence
of various economic factors. However, using an RNN LSTM model for stock price prediction can provide a more
accurate and reliable forecast compared to traditional methods. This paper provided a detailed explanation and step-
by-step procedure to implement the RNN LSTM model for stock price pre-diction. The first step in the process was
data collection for which API Quandl was used to gather the stock data of TCS from 1st January 2013 to 18th May

040021-5
2018. The next step in the process was data pre- processing followed by model training and evaluation. With the
proposed methodology, the mean abso-lute percent error came out to be3.57854%. The predicted trend based on the
dataset was very close to the original trend.

FIGURE 5. Comparison between the Prediction on Training Data and the Prediction on Testing Data with the Original

19 July 2024 04:41:08


Closing Values of TCS Stocks.

FIGURE 6. Training and Validation Error Graph

040021-6
FIGURE 7. Training and Validation Loss Graph
:

REFERENCES
1. Nabipour, M.; Nayyeri, P.; Jabani, H.; Mosavi, A.; Salwana, E.; S., S. “Deep learning for stock market prediction.”
Entropy 22,840 (2020). https://doi.org/10.3390/e22080840.

19 July 2024 04:41:08


2. Pang, X., Zhou, Y., Wang, P. et al. “An innovative neural network approach for stock market prediction. “J Super
comput, 76, 2098–2118 (2020).
3. Sachdeva, Akshay, et al. “An effective time series analysis for equity market prediction using deep learning
model.” 2019 International Conference on Data Science and Communication (IconDSC). IEEE, (2019).
4. Mehtab, Sidra, Jaydip Sen, and Abhishek Dutta. “Stock price prediction using machine learning and LSTM-based
deep learning models.” Machine Learning and Metaheuristics Algorithms, and Applications: Second Symposium,
SoMMA (2020), Chennai, India, October 14–17 (2020).
5. Anand, C. “Comparison of stock price prediction models using pre-trained neural networks.” Journal of
Ubiquitous Computing and Communication Technologies (UCCT) 3.02:122-134 (2021).
6. Nti, I.K., Adekoya, A.F. and Weyori, B.A. “A comprehensive evaluation of ensemble learning for stock-market
prediction.” J Big Data 7, 20 (2020). https://doi.org/10.1186/s40537-020- 00299-5
7. Adil Moghar, Mhamed Hamiche, “Stock market prediction using LSTM recurrent neural network”, Procedia
Computer Science, 170, (2020).
8. Nti, Isaac Kofi, Adekoya, Adebayo Felix and Weyori, Benjamin Asubam, “Efficient stock market prediction using
ensemble support vector machine” Open Computer Science, 10(1) , 53-163 (2020). https://doi.org/10.1515/comp-
2020- 0199
9. Mehtab, Sidra, and Jaydip Sen. “A time series analysis-based stock price prediction using machine learning and
deep learning models.” International Journal of Business Forecasting and Marketing Intelligence 6.4: 272-335
(2020).
10. Vijh, Mehar, et al. “Stock closing price prediction using machine learning techniques.” Procedia computer science
167: 599- 606 (2020).
11. Singh, Ritika, and Shashi Srivastava. “Stock prediction using deep learning.” Multimedia Tools and Applications,
76, 18569- 18584 (2017).
12. H. L. Siew and M. J. Nordin, “Regression techniques for the prediction of stock price trend,” International
Conference on Statistics in Science, Business and Engineering (ICSSBE), Langkawi, Malaysia, 1-5, (2012). doi:
10.1109/ICSSBE.2012.639653.

040021-7

You might also like