Harnessing Deep Learning for Stock Market Predictions: A CNN Approach (2024)

Imports libraries for data preprocessing.

import numpy as npimport matplotlib.pyplot as pltimport pandas as pdimport datetimefrom sklearn import preprocessingfrom operator import itemgetterfrom sklearn.metrics import mean_squared_errorimport kerasimport seaborn as snssns.set()

Various libraries are imported for data manipulation, visualization, and machine learning in Python. Here is an overview of each library’s purpose:

  1. NumPy (imported as np): It is a fundamental package for scientific computing, offering support for large multi-dimensional arrays and matrices, along with various mathematical functions.

  2. Matplotlib.pyplot (imported as plt): Matplotlib is a plotting library used for creating diverse visualizations in Python. The pyplot module provides a MATLAB-like interface for plotting.

  3. Pandas (imported as pd): Pandas is a powerful data manipulation library that enhances NumPy capabilities for fast and simple data analysis in Python.

  4. Datetime: Python’s datetime module facilitates manipulation of dates and times.

  5. sklearn.preprocessing: This module from scikit-learn offers utility functions and transformer classes to preprocess and normalize data for machine learning algorithms.

  6. operator.itemgetter: Used to create a callable that retrieves items at specified indices from iterable objects like lists.

  7. sklearn.metrics.mean_squared_error: Computes the mean squared error (MSE) to evaluate the performance of regression models.

  8. Keras: A high-level neural networks API that simplifies the creation of deep learning models on TensorFlow, CNTK, or Theano.

  9. Seaborn: A Python data visualization library built on Matplotlib, offering a high-level interface for creating visually appealing statistical graphics.

  10. sns.set(): Sets the Seaborn plotting style to the default style.

These libraries enable efficient data analysis, visualization, and machine learning tasks in Python by providing specific functionalities to handle data, develop models, and present results effectively.

Read the data and convert it into a pandas dataframe.

Link to download source code, at the end of this article.

Reads, manipulates, and displays stockdata.

df = pd.read_csv("https://raw.githubusercontent.com/ashishpatel26/NYSE-STOCK_MARKET-ANALYSIS-USING-LSTM/master/nyse/prices-split-adjusted.csv", index_col = 0)df["adj close"] = df.close # Moving close to the last columndf.drop(['close'], 1, inplace=True) # Moving close to the last columndf.head()
Harnessing Deep Learning for Stock Market Predictions: A CNN Approach (1)

This process involves reading a CSV file from a provided URL into a pandas DataFrame. After loading the data, it changes the column ‘close’ to ‘adj close’ (adjusted close) by renaming it. Then, it removes the original ‘close’ column, keeping the adjusted close as the last column in the DataFrame. Finally, a preview of the initial rows of the DataFrame is displayed.

Such a procedure is important for updating and organizing the DataFrame to enhance its usability for analysis or processing. It includes actions like renaming columns and improving the column order to facilitate data interpretation and manipulation.

Reads and displays data fromURL.

df2 = pd.read_csv("https://raw.githubusercontent.com/ashishpatel26/NYSE-STOCK_MARKET-ANALYSIS-USING-LSTM/master/nyse/fundamentals.csv")df2.head()
Harnessing Deep Learning for Stock Market Predictions: A CNN Approach (2)

This script fetches a CSV file from a URL using the Pandas library in Python. The CSV file is then loaded into a Pandas DataFrame using pd.read_csv(). The URL points to a CSV file hosted on a GitHub repository.

Once the data is loaded into the DataFrame, the df2.head() method is utilized to display the initial rows of the DataFrame. This is useful for quickly examining the data’s structure, column names, and example values.

Employing this script is crucial for accessing and evaluating data stored in CSV files available online. It enables the data to be loaded into a structured format for conducting various data manipulation and analysis tasks in Python.

Retrieve all symbols from the given list.

Finds unique symbols in a DataFrame.

symbols = list(set(df.symbol))len(symbols)
501

This process retrieves the unique symbols found in the DataFrame df and saves them into a list named ‘symbols’.

Here’s the explanation:

  1. By using set(df.symbol), a set of unique elements is created by isolating the ‘symbol’ column from the DataFrame df.

  2. This set of unique symbols is then converted into a list using the list() function.

  3. len(symbols) provides the count of unique symbols in the list.

This snippet is beneficial for removing duplicate symbols from a dataset, allowing for analysis or processing with only distinct values. It aids in eliminating repetition and guaranteeing that each unique symbol is only considered once in subsequent tasks.

Selects the first 11 elements.

symbols[:11]
['ES', 'NLSN', 'PNW', 'SYY', 'NTRS', 'MTB', 'HP', 'DPS', 'NFLX', 'MON', 'MUR']

This process extracts the elements from index 0 up to (but not including) index 11 of the “symbols” data structure. Extraction is commonly utilized when you wish to access a specific portion of a collection or sequence of items. It is important in situations where you need to work with only a subset of data rather than the entire dataset. This approach allows you to concentrate on a smaller portion of the data for analysis or manipulation, without the need to handle the entire collection simultaneously.

Harnessing Deep Learning for Stock Market Predictions: A CNN Approach (2024)

FAQs

Can CNN be used for stock prediction? ›

Because the stock data can be seen as a large 2D matrix, [3] has used ANN model to make prediction and gain a satisfied result, both of which have proved that CNN also can be used to do the same thing.

What is the best deep learning model for stock prediction? ›

The LSTM algorithm has the ability to store historical information and is widely used in stock price prediction (Heaton et al. 2016). For stock price prediction, LSTM network performance has been greatly appreciated when combined with NLP, which uses news text data as input to predict price trends.

Is CNN a deep learning approach? ›

Convolutional Neural Network (CNN) is a deep learning approach that is widely used for solving complex problems. It overcomes the limitations of traditional machine learning approaches. The motivation of this study is to provide the knowledge and understanding about various aspects of CNN.

What is the best algorithm for stock prediction? ›

A. Moving average, linear regression, KNN (k-nearest neighbor), Auto ARIMA, and LSTM (Long Short Term Memory) are some of the most common Deep Learning algorithms used to predict stock prices.

What is the best stock market prediction tool? ›

TradingView: If you're looking for free stock predictions software, TradingView is worth considering. Although TradingView is best known for its technical analysis tools, it also offers insights from sell-side analysts. Across thousands of stocks, you can assess analyst ratings from 'Strong Sell' to 'Strong Buy'.

How do I make predictions with CNN? ›

Use Model. predict() to make a prediction with your model. There are many hyperparameters to choose from to improve model performance. Fitting separate models with different hyperparameters and comparing their performance is a common and good practice in deep learning.

Which AI is best for stock price prediction? ›

We screened 69 titles and read 43 systematic reviews, including more than 379 studies, before retaining 10 for the final dataset. This work revealed that support vector machines (SVM), long short-term memory (LSTM), and artificial neural networks (ANN) are the most popular AI methods for stock market prediction.

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

Long short-term memory (LSTM) networks

LSTMs are a type of neural network that can learn long-term dependencies and are useful for predicting stock prices. They examine a sequence of stock prices over time to detect patterns and predict future prices.

Which theory is best for stock market? ›

It is one that affects all kinds of markets from the usual markets where we purchase foodstuff to the stock market, the law of demand and supply is an economic theory that has been tried and tested and proven times without number. In the stock market, the law of demand and supply controls everything.

What is an example of a CNN in deep learning? ›

Examples of CNN in computer vision are face recognition, image classification etc. It is similar to the basic neural network. CNN also have learnable parameter like neural network i.e, weights, biases etc.

Can deep learning predict stock prices? ›

Training the Model

Training a deep learning model for stock price prediction involves feeding historical price sequences into the LSTM network and using backpropagation through time (BPTT) to optimize the model's parameters.

What is the best indicator to predict stocks? ›

However, if you'd like to get started with technical trading, here are five of the best indicators you can start with.
  • The Simple Moving Average. A simple moving average (SMA) is exactly what it sounds like. ...
  • Bollinger Bands. ...
  • 52-Week High/Low. ...
  • P/E Ratio. ...
  • Parabolic Stop-And-Reverse.
Mar 8, 2024

How do you predict stocks accurately? ›

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. But instead of future price, we use it for current price.

Can CNN be used for forecasting? ›

Key Advantages of CNNs for Time Series Forecasting:

This makes them capable of capturing both short-term and long-term dependencies. Parallel Processing: CNNs can process multiple sequences simultaneously, making them efficient for handling large datasets and multivariate time series.

Can Neural Networks predict stock prices? ›

Neural networks possess unsurpassed abilities in identifying underlying patterns in chaotic, non-linear, and seemingly random data, thus providing a mechanism to predict stock price movements much more precisely than many current techniques.

What is CNN best suited for? ›

The Convolutional Neural Network (CNN or ConvNet) is a subtype of Neural Networks that is mainly used for applications in image and speech recognition. Its built-in convolutional layer reduces the high dimensionality of images without losing its information.

Is there an AI that can predict the stock market? ›

"We found that these AI models significantly outperform traditional methods. The machine learning models can predict stock returns with remarkable accuracy, achieving an average monthly return of up to 2.71% compared to about 1% for traditional methods," adds Professor Azevedo.

Top Articles
Latest Posts
Article information

Author: Dr. Pierre Goyette

Last Updated:

Views: 6000

Rating: 5 / 5 (70 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Dr. Pierre Goyette

Birthday: 1998-01-29

Address: Apt. 611 3357 Yong Plain, West Audra, IL 70053

Phone: +5819954278378

Job: Construction Director

Hobby: Embroidery, Creative writing, Shopping, Driving, Stand-up comedy, Coffee roasting, Scrapbooking

Introduction: My name is Dr. Pierre Goyette, I am a enchanting, powerful, jolly, rich, graceful, colorful, zany person who loves writing and wants to share my knowledge and understanding with you.