LightningChart PythonStock price prediction in Python

TutorialPredictive analysis on stock prices using machine learning and LightningChart Python

Written by a human | Updated on April 23rd, 2025

Stock price prediction in Python

What is the stock market and how does it operate?

The stock market, a complex network of buyers and sellers trading shares, operates as one of the most pivotal components of a free-market economy. Its functionality hinges on the fluctuating prices of shares based on supply and demand dynamics, investor sentiment, and various economic indicators.

Why is it important for stock traders to attempt stock price prediction analyses?

For stock traders, predicting these price movements can mean the difference between significant gains and losses. This is where stock price prediction using machine learning in Python becomes crucial.

How can machine learning help in stock price prediction?

Machine learning, with its capability to analyze vast datasets and identify patterns, has emerged as a powerful tool for stock price prediction. By leveraging algorithms to process historical stock data, traders can make informed decisions and potentially enhance their profitability. This project delves into the intricacies of stock price prediction in Python, exploring various models and methodologies used to forecast market trends.

LSTM Model for Predicting Stock Prices

One of the most effective models for stock price prediction is the Long Short-Term Memory (LSTM) network, a recurrent neural network (RNN) type well-suited for sequence prediction problems. LSTMs are particularly powerful for predicting stock prices due to their ability to capture temporal dependencies and patterns in time series data

LSTM networks are designed to remember long-term dependencies and are equipped with memory cells that can store information for long periods. This makes them highly effective for tasks like stock price prediction, where understanding the sequence and timing of past data points is crucial. In this project, we implemented an LSTM model to predict stock prices, leveraging its strengths to analyze historical price data and forecast future trends.

LightningChart Python

Overview of LightningChart Python

LightningChart Python is a high-performance data visualization library designed for developers who need to create complex, interactive, and real-time charts. It is particularly useful in financial applications where the need for swift and accurate data representation is paramount.

Feature-image---lcpy-social-media

Features and chart types to be used in the Project

LightningChart Python offers a variety of chart types, each designed to handle specific types of data visualization needs. In this project, we use the following chart types to visualize stock price prediction data:

XY Chart. The XY Chart is used for visualizing data between two dimensions, X and Y. It has built-in axis functionality and supports a large set of series types, making it versatile for various data visualization tasks. The series types used in this project include:

  • Line Series: Ideal for displaying continuous data points connected by straight lines, useful for showing trends over time.
  • Point Line Series: Combines points and lines to highlight specific data points while showing trends.
  • Area Series: Fills the area beneath a line series, useful for emphasizing volume or cumulative values.

3D Chart. The 3D Chart is employed for visualizing data in a three-dimensional space, providing a more immersive and detailed view of data trends. Key features include:

  • Camera and Light Source: The camera can be moved around with user interactions, always facing the center of the scene. The light source is located at the camera’s position, directed towards the center of the axes.
  • Line Series: In a 3D space, the line series can help visualize data trends across three dimensions, providing a deeper understanding of data relationships.

Line Chart. A Line Chart is specifically used for visualizing a list of points (pairs of X and Y coordinates) with a continuous stroke. It is straightforward yet powerful for showing changes in stock prices over time.

Stacked Bar Chart and Grouped Bar Chart

  • Stacked Bar Chart: This chart type is used to show the composition of categories. Each bar represents a total and is divided into parts, which can be useful for comparing different components of stock data.
  • Grouped Bar Chart: Used to compare multiple categories side-by-side, allowing for easy comparison of different stock data metrics.

Performance Characteristics

One of the standout aspects of LightningChart Python is its performance. The library is optimized for handling large volumes of data with minimal latency, which is crucial for financial applications where data needs to be processed and visualized in real time to inform trading decisions.

Key performance characteristics include:

  • Real-Time Data Updating: LightningChart Python can handle real-time data updates, essential for real-time stock price monitoring and prediction.
  • High Refresh Rates: Ensures that visualizations are smooth and responsive, even with large datasets.
  • Efficient Data Handling: The library is designed to manage and display large amounts of data efficiently, preventing lag and ensuring a seamless user experience.

These features make LightningChart Python an excellent choice for developing stock price prediction applications, providing robust tools for both 2D and 3D data visualization, and ensuring high performance even under demanding conditions.

Setting Up Python Environment

Installing Python and Necessary Libraries

To begin with stock price prediction in Python, you need to set up your development environment. Start by installing Python from the official Python website. LightningChart Python requires Python version 3.10 or higher. Once Python is installed, you can use pip, the Python package installer, to install the necessary libraries. LightningChart Python can be installed from the Python Package Index (PyPI) using pip:

pip install lightningcharts random numpy pandas scikit-learn tensorflow

Overview of Libraries Used

  • LightningChart: For advanced data visualization capabilities.
  • NumPy: A fundamental package for numerical computation in Python.
  • Pandas: Essential for data manipulation and analysis.
  • Scikit-learn: A robust library for machine learning, providing tools for data mining and data analysis.
  • Tensorflow: For building and training machine learning models.

Setting Up Your Development Environment

Set up an Integrated Development Environment (IDE) such as Jupyter Notebook, PyCharm, or Visual Studio Code. This will help in organizing and running your code efficiently.

Loading and Processing Data

How to Load the Data Files

Stock price data can be obtained from various sources, including Yahoo Finance, Alpha Vantage, and Quandl. For this example, we’ll use a CSV file from Yahoo Finance:

import pandas as pd
 
# Load the dataset
df_googl = pd.read_csv('./Alphabet Inc - Class A (GOOGL).csv')
df_googl.rename(columns={"Date":"date","Open":"open","High":"high","Low":"low","Close":"close"}, inplace=True)
df_googl['date'] = pd.to_datetime(df_googl.date)
df_googl.sort_values(by='date', inplace=True)

Handling and preprocessing the data

Preprocessing involves cleaning the data, handling missing values, and transforming it into a format suitable for machine learning models. Here’s how to preprocess the data:

from sklearn.preprocessing import MinMaxScaler
 
specified_start_date = pd.to_datetime('2020-01-01')
specified_end_date = pd.to_datetime('2024-05-14')
filtered_df = df_googl[(df_googl['date'] >= specified_start_date) & (df_googl['date'] <= specified_end_date)]
 
# Normalize/scale the close values between 0 and 1
close_stock_values = filtered_df['close'].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(0, 1))
normalized_close_values = scaler.fit_transform(close_stock_values)

Validation of the Study

The effectiveness of the LSTM model in predicting stock prices can be validated through various performance metrics, which are used in this project:

  • Train R² Score: 0.99: Indicates that the model explains 99% of the variance in the training data, showcasing a high level of accuracy.
  • Test R² Score: 0.98: Demonstrates that the model retains its accuracy when applied to unseen test data, explaining 98% of the variance.

Training Data Metrics

  • Train RMSE: 3.00
  • Train MSE: 8.98
  • Train MAE: 2.26

These metrics show that the model has a low error rate on the training data, indicating it has learned the patterns in the historical stock prices effectively.

Testing Data Metrics

  • Test RMSE: 3.28
  • Test MSE: 10.79
  • Test MAE: 2.48

The metrics for the testing data indicate a high level of accuracy and generalizability of the model.

Visualizing Data with LightningChart

LightningChart Python allows for the creation of highly interactive and customizable charts. This library is useful for financial data visualization due to its performance and feature set. Here are some of the LC charts below:

Creating the charts

To visualize stock data, you can create various charts using LightningChart Python:

import lightningchart as lc
import random
from datetime import datetime

# Initialize LightningChart and set the license key
lc.set_license('my-license-key')

chart = lc.ChartXY(title='Actual vs Predicted Close Prices')

Customizing visualizations

LightningChart offers extensive customization options. You can adjust the colors, add markers, or integrate real-time data updates to enhance the visualization:

# Dispose the default x-axis and create a high precision datetime axis
chart.get_default_x_axis().dispose()
axis_x = chart.add_x_axis(axis_type='linear-highPrecision')
axis_x.set_tick_strategy('DateTime')

# Convert datetime to timestamps for plotting
actual_dates = filtered_df['date'].tolist()
actual_close = filtered_df['close'].tolist()
actual_date_timestamps = [x.timestamp() * 1000 for x in actual_dates]

# Plot actual prices
series_actual = chart.add_line_series()
series_actual.add(x=actual_date_timestamps, y=actual_close)
series_actual.set_name('Actual Prices')

# Customize the chart
chart.get_default_x_axis().set_title('Date')
chart.get_default_y_axis().set_title('Stock Price')
chart.add_legend()
chart.open()

Conclusion

Creating a stock price prediction application in Python involves several steps, from setting up the development environment to loading and processing data, and finally visualizing it using LightningChart. By using an LSTM model, we leverage the power of deep learning to predict future stock prices based on historical data. The application demonstrates how advanced machine learning techniques can be integrated with high-performance visualization tools to provide insightful and actionable information for stock traders.

Benefits of using LightningChart Python for visualizing data

LightningChart Python’s high performance and extensive feature set make it an excellent choice for visualizing stock market data. Its ability to handle large datasets with minimal latency ensures that traders have access to real-time data, allowing them to make timely and informed decisions.

Omid Ahmad

Ahmad Omid

Data Science Python Developer

LinkedIn icon
divider-light

Continue learning with LightningChart

Best ApexCharts Alternatives in 2026: Scale Beyond SVG, Add Real 3D

Best ApexCharts Alternatives in 2026: Scale Beyond SVG, Add Real 3D

ApexCharts earned its position through a set of genuine strengths executed consistently well: MIT license, the best default visual aesthetics among free JavaScript chart libraries, official and actively maintained React, Vue, and Angular component wrappers, clean...