LightningChart PythonNorthern Lights Prediction Python Application
TutorialImplementation of a Python application that predicts Northern Lights activity.
Written by a human | Updated on April 24th, 2025
Northern Lights Prediction in Python
Solar flares originate from regions of intense magnetic activity on the Sun, particularly around sunspots. They release huge amounts of energy in the form of radiation and energetic particles, including protons, electrons, and heavier ions. These high-energy particles, known as solar energetic particles (SEPs), are ejected into space, traveling along the Sun’s magnetic field lines. If directed toward Earth, these charged particles can reach our planet in a matter of minutes to hours.
When solar flare emissions interact with Earth’s magnetic field, they can cause geomagnetic storms. These storms disturb satellite communications, GPS systems, and power grids. SEPs can also trigger the Aurora Borealis (Northern Lights), a phenomenon caused when charged particles collide with Earth’s magnetosphere, particularly at the polar regions. Thus, solar flares play a significant role in both technological disruptions and the creation of natural light shows like the aurora.
To model and visualize solar energetic particles (SEPs), particularly protons, these variables must be considered:
- Density of Protons. A higher proton density increases the chance of geomagnetic storms when these particles collide with Earth’s magnetic field.
- Speed of Protons. Faster protons carry more kinetic energy and can penetrate Earth’s magnetic shield more deeply, causing stronger geomagnetic disturbances.
- Direction of Travel. Protons and other charged particles follow the Sun’s magnetic field lines, so their direction of travel is also important to consider.
Correlation between particles bursts and the KP index
The Kp index is a global geomagnetic activity index that measures disturbances in Earth’s magnetic field on a scale from 0 to 9. A higher Kp value indicates more intense geomagnetic storms, typically caused by solar wind and solar energetic particle (SEP) streams interacting with Earth’s magnetosphere. It is widely used to assess the potential for space weather effects, such as disruptions to communication systems and the visibility of auroras.
The density and speed of proton streams from solar flares or coronal mass ejections (CMEs) directly affect Earth’s geomagnetic activity. When high-density, high-speed streams reach Earth, they can compress the magnetosphere and intensify geomagnetic storms. A key factor in this interaction is the Bz dimension of Earth’s magnetic field, which refers to the north-south orientation of the magnetic field in the solar wind.
When the Bz component is negative (southward), it aligns oppositely to Earth’s magnetic field, allowing for stronger magnetic reconnection. This opens up the magnetosphere to more solar wind particles, intensifying geomagnetic disturbances
LightningChart Python
For this task, we use the LightningChart Python library. It provides a wide range of tools for creating graphs useful for northern lights predictions in Python. In this project, we will use:
- XY Charts (Link to docs)
LightningChart uses GPUs for faster rendering, so it is possible to ‘feed’ it a huge sample of data.
Setting Up Python Environment
To create the northern lights prediction dashboard in Python, first, we need to set up our Python environment.
1. The first step is installing Homebrew itself
I recommend using Homebrew package manager as it is popular and has a lot of packages. Moreover, it is arguably more convenient than installing Python using .dmg. You can skip this step if it is already installed on your Mac. Enter Terminal app and copy/paste this string:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Important note: the installation of Homebrew is not fast, it usually takes between 5 to 15 minutes.
2. Installation of Python
This command will install the latest stable version of Python.
brew install python
NOTE: if you don’t want to use Homebrew, you can access the official Python website, select the latest stable version downloader for MacOS (its named macOS 64-bit universal2 installer), and follow the installation instructions. You can check the version using python3 –version in the terminal. If it displays Unknown command error, it is most likely due to PATH variables. Refer to this guide to fix it.
Installation of Python on Windows
I recommend using the tool Winget. To install the Python package, open cmd or PowerShell as Administrator and type:
winget install Python.Python.3
NOTE: if you don’t want to use Winget, You can access the official Python website, select the latest stable version downloader for Windows
(it is named Windows installer (64-bit)) and follow the installation instructions. You can verify the installation of Python and pip by typing python --version and pip --version respectively. If it displays command' is not recognized error, it is most likely due to PATH variables. Refer to this guide to fix.
3. Installation of IDE
For IDE (integrated development environment), I recommend using PyCharm as it is clean and powerful. However, the full version is paid so you can also use VSCode. Optionally, you may want to set up Venv (Python virtual environment) to install packages there and not clutter the Python installation. The environment-creating instructions are:
4. Setting up jupyter notebook
For PyCharm (ONLY PROFESSIONAL VERSION): Just create an .ipynb file and start coding. The IDE will install everything needed on its own.
For Visual Studio Code
- Install Jupyter extension:
- Select and open the working directory
- Create venv (
⇧⌘PorCtrl-⇧-P). Very recommended! - Refer to the following article (starting from “Workspace Trust” paragraph)
5. Libraries Used
- Pandas: In this project, we will mainly use the two-dimensional data frame data structure provided by Pandas. It can be easily created from a .CSV or Excel file.
- NumPy: NumPy is provided with Pandas and it is a fundamental package for scientific computing in Python. It provides support for arrays, mathematical functions, and linear algebra operations.
- LightningChart: LightningChart is the main library used in the project for creating different types of charts in Python. It provides highly customizable graph-building tools, including simple XY charts, 3D charts, Bar charts, Spider charts, and Map charts.
6. Installing and importing libraries
Firstly, we need to import needed libraries. We use datetime for working with timestamps, math to make equations. Also, we use external libraries pandas, numpy and lightningchart.
from datetime import datetime
import math
import pandas as pd
import lightningchart as lc
import numpy as np
7. LightningChart License
To activate the license for your project, use the following code as shown below. Important! I always recommend storing license keys and other sensitive information in separate files that are included in .gitignore file.
with open("license_key.txt", "r") as file: # License key is stored in 'license_key.txt'
key = file.read()
lc.set_license(key)
Loading and Processing Data
Note that you can see the complete code files in GitHub, here will be the summary. You can find suitable data on the Space Weather Prediction website. You can use either pair of files, be it 1 day or 2 hours etc. There is a ready-made script to download and merge the files (file_download.py). If you want to use other files from this index, you can change these urls inside the script:
# urls of the data
url1 = "https://services.swpc.noaa.gov/products/solar-wind/mag-1-day.json"
url2 = "https://services.swpc.noaa.gov/products/solar-wind/plasma-1-day.json"
You can retrieve the real-time data by running the script (file_download.py). The updated file will be in data folder. To extract data from a .csv file and store it in dataframe we need to use pd.read_csv function. After this, we need to convert dataframe columns to lists.
df = pd.read_csv('data/output.csv') # read csv
Then it is needed to evaluate phi, which is needed for analysis.
# normalize phi - first calculated using np.arctan2() and then mapped to range(0, 2pi) using np.mod
df['phi_gsm'] = np.degrees(np.mod(np.arctan2(df["by_gsm"], df["bx_gsm"]), 2 * np.pi))
df.fillna(0, inplace=True) # fill na values as 0s to avoid errors
print(df.head(), df.tail()) # print head tail of dataframe (optional)
After it, we create lists to import them to Chart Series.
# create lists
y_bz = df['bz_gsm'].to_list()
y_density = df['density'].to_list()
y_phi = df['phi_gsm'].to_list()
y_speed = df['speed'].to_list()
y_temp = df['temperature'].to_list()
x = df['time_tag'].to_list()
One of the important steps is to convert the datetime to the appropriate format so LightningChart can read it properly. In our case, it is a timestamp in milliseconds.
def convert_to_timestamp(dt_str):
dt_format = "%Y-%m-%d %H:%M:%S.%f"
# parse the datetime string into a datetime object
dt = datetime.strptime(dt_str, dt_format)
# convert datetime object to Unix timestamp
timestamp = dt.timestamp() * 1000
return timestamp
x_time = [convert_to_timestamp(dt) for dt in x]
Visualizing Northern Lights Predictions
Let’s initialize Dashboard, and then ChartXYs from LightningChart library. Also, we can customize titles, as well as point color and sizes.
dashboard = lc.Dashboard(columns=1, rows=5, theme=lc.Themes.Black) # initialize Dashboard
chart_bz = dashboard.ChartXY(column_index=0, row_index=0, title='Bz') # create first chart
chart_bz.get_default_x_axis().dispose()
chart_bz.add_x_axis(axis_type="linear-highPrecision").set_tick_strategy("DateTime") # change axis to datetime format
series_bz = chart_bz.add_point_series().append_samples( # insert data
x_values=x_time,
y_values=y_bz
).set_point_size(3) # size of points (for visual purposes)
Then, we can repeat the same for other 4 XY charts.
Conclusion
The parameters visualized in the graphs are useful for geomagnetic storm prediction:
-
Bz: negative Bz is a strong indicator of severe geomagnetic storms
-
Phi: Phi can help track the source of the solar wind contributing to the storm.
-
Density: high solar wind density typically amplifies geomagnetic storms, as it increases the dynamic pressure on the magnetosphere.
-
Speed: geomagnetic storms caused by high-speed solar wind are typically longer-lasting but less intense than those triggered by slower winds
-
Temperature: tracking temperature changes helps to analyze the energy profile of the storm and the behavior of incoming solar wind structures.
Debunking SciChart’s Performance
Learn about SciChart’s misleading benchmark performance metrics that distort how a real high-end chart library performs.
Swing index indicator: formula and implementation with LC JS Trader
Learn the Swing Index indicator formula and implementation with LightningChart JS Trader to detect trend direction and refine trading signals.
How to use the Supertrend indicator for Fintech app development
Learn about the Supertrend indicator in fintech app development to generate clear buy and sell signals, optimize ATR settings, and enhance trading strategies.
