Predicting Stock Prices Using a Keras LSTM Model (2024)

Artificial Intelligence in Finance

Utilizing a Keras LSTM model to forecast stock trends

Predicting Stock Prices Using a Keras LSTM Model (3)

As financial institutions begin to embrace artificial intelligence, machine learning is increasingly utilized to help make trading decisions. Although there is an abundance of stock data for machine learning models to train on, a high noise to signal ratio and the multitude of factors that affect stock prices are among the several reasons that predicting the market difficult. At the same time, these models don’t need to reach high levels of accuracy because even 60% accuracy can deliver solid returns. One method for predicting stock prices is using a long short-term memory neural network (LSTM) for times series forecasting.

Predicting Stock Prices Using a Keras LSTM Model (4)

LSTMs are an improved version of recurrent neural networks (RNNs). RNNs are analogous to human learning. When humans think, we don’t start our thinking from scratch each second. For example, in the sentence “Bob plays basketball”, we know that Bob is the person who plays basketball because we retain information about past words while reading sentences. Similarly, RNNs are networks with loops in them, which allow them to use past information before arriving at a final output. However, RNNs can only connect recent previous information and cannot connect information as the time gap grows. This is where LSTMs come into play; LSTMs are a type of RNN that remember information over long periods of time, making them better suited for predicting stock prices. For a technical explanation of LSTMs click here.

To begin our project, we import numpy for making scientific computations, pandas for loading and modifying datasets, and matplotlib for plotting graphs.

import numpy as npimport matplotlib.pyplot as pltimport pandas as pd

After making the necessary imports, we load data on Tata Global Beverage’s past stock prices. From the data, we select the values of the first and second columns (“Open” and “High” respectively) as our training dataset. The “Open” column represents the opening price for shares that day and the “High” column represents the highest price shares reached that day.

url = 'https://raw.githubusercontent.com/mwitiderrick/stockprice/master/NSE-TATAGLOBAL.csv'dataset_train = pd.read_csv(url)training_set = dataset_train.iloc[:, 1:2].values

To get a look at the dataset we’re using, we can check the head, which shows us the first five rows of our dataset.

dataset_train.head()

“Low” represents the lowest share price for the day, “Last” represents the price at which the last transaction for a share went through. “Close” represents the price shares ended at for the day.

Normalization is changing the values of numeric columns in the dataset to a common scale, which helps the performance of our model. To scale the training dataset we use Scikit-Learn’s MinMaxScaler with numbers between zero and one.

from sklearn.preprocessing import MinMaxScalersc = MinMaxScaler(feature_range=(0,1))training_set_scaled = sc.fit_transform(training_set)

We should input our data in the form of a 3D array to the LSTM model. First, we create data in 60 timesteps before using numpy to convert it into an array. Finally, we convert the data into a 3D array with X_train samples, 60 timestamps, and one feature at each step.

X_train = []y_train = []for i in range(60, 2035):X_train.append(training_set_scaled[i-60:i, 0])y_train.append(training_set_scaled[i, 0])X_train, y_train = np.array(X_train), np.array(y_train)X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))

Before we can develop the LSTM, we have to make a few imports from Keras: Sequential for initializing the neural network, LSTM to add the LSTM layer, Dropout for preventing overfitting with dropout layers, and Dense to add a densely connected neural network layer.

from keras.models import Sequentialfrom keras.layers import LSTMfrom keras.layers import Dropoutfrom keras.layers import Dense

The LSTM layer is added with the following arguments: 50 units is the dimensionality of the output space, return_sequences=True is necessary for stacking LSTM layers so the consequent LSTM layer has a three-dimensional sequence input, and input_shape is the shape of the training dataset.

Specifying 0.2 in the Dropout layer means that 20% of the layers will be dropped. Following the LSTM and Dropout layers, we add the Dense layer that specifies an output of one unit. To compile our model we use the Adam optimizer and set the loss as the mean_squared_error. After that, we fit the model to run for 100 epochs (the epochs are the number of times the learning algorithm will work through the entire training set) with a batch size of 32.

model = Sequential()model.add(LSTM(units=50,return_sequences=True,input_shape=(X_train.shape[1], 1)))model.add(Dropout(0.2))model.add(LSTM(units=50,return_sequences=True))model.add(Dropout(0.2))model.add(LSTM(units=50,return_sequences=True))model.add(Dropout(0.2))model.add(LSTM(units=50))model.add(Dropout(0.2))model.add(Dense(units=1))model.compile(optimizer='adam',loss='mean_squared_error')model.fit(X_train,y_train,epochs=100,batch_size=32)

We start off by importing the test set

url = 'https://raw.githubusercontent.com/mwitiderrick/stockprice/master/tatatest.csv'dataset_test = pd.read_csv(url)real_stock_price = dataset_test.iloc[:, 1:2].values

Before predicting future stock prices, we have to modify the test set (notice similarities to the edits we made to the training set): merge the training set and the test set on the 0 axis, set 60 as the time step again, use MinMaxScaler, and reshape data. Then, inverse_transform puts the stock prices in a normal readable format.

dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0)inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].valuesinputs = inputs.reshape(-1,1)inputs = sc.transform(inputs)X_test = []for i in range(60, 76):X_test.append(inputs[i-60:i, 0])X_test = np.array(X_test)X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))predicted_stock_price = model.predict(X_test)predicted_stock_price = sc.inverse_transform(predicted_stock_price)

After all these steps, we can use matplotlib to visualize the result of our predicted stock price and the actual stock price.

plt.plot(real_stock_price, color = 'black', label = 'TATA Stock Price')plt.plot(predicted_stock_price, color = 'green', label = 'Predicted TATA Stock Price')plt.title('TATA Stock Price Prediction')plt.xlabel('Time')plt.ylabel('TATA Stock Price')plt.legend()plt.show()
Predicting Stock Prices Using a Keras LSTM Model (5)

While the exact price points from our predicted price weren’t always close to the actual price, our model did still indicate overall trends such as going up or down. This project teaches us the LSTMs can be somewhat effective in times series forecasting.

Click here for the entire code

[1] Derrick Mwiti, Data and Notebook for the Stock Price Prediction Tutorial(2018), Github

Predicting Stock Prices Using a Keras LSTM Model (2024)

FAQs

How to use LSTM to predict stock prices? ›

Predicting Stock Prices with LSTM and GRU: A Step-by-Step Guide
  1. Getting the Data. To get started, we need historical stock price data. ...
  2. Data Visualization. ...
  3. Data Preprocessing. ...
  4. Creating the Training Data. ...
  5. Building the LSTM Model. ...
  6. Training the Model. ...
  7. Making Predictions. ...
  8. Visualizing the Predictions.

What is the best algorithm for predicting stock prices? ›

In particular, the LSTM algorithm (Long Short- Term Memory) confirms the stability and efficiency in short-term stock price forecasting.

Which AI is best for predicting stock prices? ›

10 AI Tools for Stock Trading & Price Predictions
  • Top 10 AI Tools for Stock Trading in 2024.
  • EquBot.
  • Trade Ideas.
  • TrendSpider.
  • Tradier.
  • QuantConnect.
  • Sentient Trader.
  • Awesome Oscillator.
Jun 4, 2024

Can LSTM be used for prediction? ›

A. Yes, LSTMs can be used to predict stock prices by training on historical data and market trends. They can capture long-term dependencies and make informed predictions.

What is the most accurate stock predictor? ›

Capital Economics has been named the most accurate forecaster of major global stock indices in Reuters polls. The 2023 LSEG StarMine Award was given for forecasting accuracy across 11 equities benchmarks and reflects the breadth and depth of our global coverage of macro and markets.

Is Arima better than LSTM for stock market prediction? ›

The LSTM model provides better results when the data set is large and has fewer Nan values. Whereas, despite providing better accuracy than LSTM, the ARIMA model requires more time in terms of processing and works well when all the attributes of the data set provide legitimate values.

What is the formula for predicting stock price? ›

The formula is shown above (P/E x EPS = Price). According to this formula, if we can accurately predict a stock's future P/E and EPS, we will know its accurate future price. We use this formula day-in day-out to compute financial ratios of stocks.

What is the best indicator to predict stocks? ›

Seven of the best indicators for day trading are:
  • On-balance volume (OBV)
  • Accumulation/distribution (A/D) line.
  • Average directional index.
  • Aroon oscillator.
  • Moving average convergence divergence (MACD)
  • Relative strength index (RSI)
  • Stochastic oscillator.

Which methods is best used for predicting the price of a stock? ›

Time series forecasting (predicting future values based on historical values) applies well to stock forecasting. Because of the sequential nature of time-series data, we need a way to aggregate this sequence of information.

Why can't AI predict stocks? ›

In today's dynamic and ever-evolving investment landscape, stock prices are hard to predict since they are influenced by several factors, including investors' sentiment, global economic conditions, politics, unplanned events, companies' financial performances, and more.

How to use ChatGPT to predict stock price? ›

Here are some key factors to predict stock price using ChatGPT Code Interpreter:
  1. Understanding the ChatGPT Code Interpreter.
  2. Data Preparation and Exploration.
  3. Building predictive models.
  4. Evaluating Model Performance.
  5. Fine-tuning and Optimization.
  6. Complex Market Dynamics.
  7. Machine Learning Advancements.
  8. Risk Management.
Jan 29, 2024

Is there any free AI tool for stock market? ›

Trade Ideas is an free AI tool for stock market india that works with the stock market to find trading opportunities by utilizing AI cloud computing. It sorts through a lot of data to identify equities that are doing strangely. It analyzes vast amounts of market data, news and trends to Identify trading opportunities.

How to use LSTM to predict stock price? ›

The Process involved,
  1. Data preparation.
  2. Visualization of historical price trends.
  3. Feature engineering using a sliding window approach.
  4. Building a Sequential neural network model with multiple LSTM layers and dropout regularization.
  5. Training the model to predict the next day's stock price.
Sep 25, 2023

Is LSTM obsolete? ›

Therefore, we can safely conclude that LSTM layers are still an invaluable component in a time series deep learning model. Moreover, they don't antagonize the Attention mechanism. Instead, they can still be combined with an Attention-based component to further improve the efficiency of a model.

What are the pitfalls of LSTM? ›

Common challenges and problems in LSTM include the vanishing gradient problem (VGP) and inefficiency in long-term dependencies convergence. The VGP occurs during the backpropagation process, causing the network to stop learning and generate poor prediction accuracy, especially in long-term dependencies 3.

What is the LSTM trading strategy? ›

The integration of LSTM aims to improve the ability to predict trading signals accurately. In basic trading strategies, instead of using the current day's closing price to generate technical indicators and make trading decisions, an LSTM model is applied to predict the future closing price.

What is the best neural network for stock prediction? ›

Neural Networks for Stock Price Prediction

LSTM (Long Short-Term Memory) Networks: Ideal for sequential data, LSTM networks can capture dependencies and patterns over time, making them suitable for time-series prediction tasks like stock prices.

Top Articles
5 Simple Ways To Save Money by Visiting Your Local Library
Why Azure vs. AWS | Microsoft Azure
Mybranch Becu
Kreme Delite Menu
Dannys U Pull - Self-Service Automotive Recycling
Loves Employee Pay Stub
Couchtuner The Office
Sissy Transformation Guide | Venus Sissy Training
Craigslist Dog Sitter
Fallout 4 Pipboy Upgrades
Swimgs Yung Wong Travels Sophie Koch Hits 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Springs Cow Dog Pig Hollywood Studios Beach House Flying Fun Hot Air Balloons, Riding Lessons And Bikes Pack Both Up Away The Alpha Baa Baa Twinkle
Globe Position Fault Litter Robot
Was sind ACH-Routingnummern? | Stripe
Sport Clip Hours
1Win - инновационное онлайн-казино и букмекерская контора
Evangeline Downs Racetrack Entries
Hartford Healthcare Employee Tools
Red Tomatoes Farmers Market Menu
Vcuapi
Sky X App » downloaden & Vorteile entdecken | Sky X
Brett Cooper Wikifeet
How do I get into solitude sewers Restoring Order? - Gamers Wiki
How pharmacies can help
Dallas Mavericks 110-120 Golden State Warriors: Thompson leads Warriors to Finals, summary score, stats, highlights | Game 5 Western Conference Finals
Craigslistodessa
Best Sports Bars In Schaumburg Il
Regal Amc Near Me
Bellin Patient Portal
Divina Rapsing
Craigslist Hunting Land For Lease In Ga
Kimoriiii Fansly
Aes Salt Lake City Showdown
Gesichtspflege & Gesichtscreme
Ups Drop Off Newton Ks
Darktide Terrifying Barrage
Otis Inmate Locator
Pfcu Chestnut Street
Beaver Saddle Ark
Craigslist Albany Ny Garage Sales
School Tool / School Tool Parent Portal
Weapons Storehouse Nyt Crossword
Google Chrome-webbrowser
Main Street Station Coshocton Menu
Flags Half Staff Today Wisconsin
Craigslist - Pets for Sale or Adoption in Hawley, PA
Wilson Tire And Auto Service Gambrills Photos
Bmp 202 Blue Round Pill
Tyco Forums
Treatise On Jewelcrafting
91 East Freeway Accident Today 2022
Minecraft Enchantment Calculator - calculattor.com
Latest Posts
Article information

Author: Otha Schamberger

Last Updated:

Views: 5939

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.