An Oil and Gas Stock Analysis with LightningChart Python Trader
Tutorial
Written by a Human
Develop an oil and gas stock analysis utilizing LightningChart Python Trader for developing trading applications in Python.
Introduction
This article is a demonstration of the charting features included in LightningChart’s Python trader (PT) library. The library will be used to visualize the stock data of 5 different companies from the last 5 years.
The companies in question are Chevron Corporation (CVX), Exxon Mobil Corporation (XOM), ConocoPhillips (COP), EOG Resources (EOG), and Kinder Morgan, Inc. (KMI). The article covers how to retrieve the data from the API and import data to Python trader, as well as how to generate and customize charts in it. Additionally, a brief introduction to Python Trader and the data being analysed.
How has the Oil & Gas industry changed in the last decade?
In the last decade, oil prices have experienced high volatility due to several events. In 2014-16, oil prices dropped significantly, caused by, among other things, excess supply and a decrease in demand. During the COVID-19 pandemic, prices dropped drastically and even went into the negatives momentarily.
This was due to oil speculators not being able to sell their contracts because the market was oversaturated. This meant that they had to receive physical delivery of oil, but many lacked the storage space to do so. This meant that they had to sell at a negative price, effectively paying someone to take the oil. The Russia–Ukraine war caused a spike in oil prices (especially Brent crude). In 2022 US, UK, and EU placed import bans and sanctions on Russian oil imports.
These factors, as well as environmental concerns and regulations, have had an impact on the industry during the last decade or so. Environmental regulations and Carbon tax, as well as the rise of renewable energy sources, have also caused shifts in the energy industry. Many companies have diversified their investments due to these factors. The ESG (Environmental, Social, Governance) has also seen a rise in recent years.
The API – Alpha Vantage
The Alpha Vantage API provides free access to most of its APIs with a limit of 25 API calls per day. This includes data on stocks, options, forex, and crypto from several exchanges, with historical data covering the last 20 years. Both adjusted and unadjusted data are available in their stock API. This demonstration will focus on their commodities API exclusively.
There is a 15-minute delay in the stock data for the free and cheapest premium subscriptions, thus putting one at a disadvantage if wanting visualize data in real-time. Additionally, the limit of 25 calls per day can be problematic when testing the functionality of the API. The premium subscriptions start at $50 / month (75 API calls per minute).
Plotted variables
Python trader requires Open, High, Low, Close (O, H, L, C) values to work (as well as a date). The API returns of all these.
API parameters
Not all of these are available for all of the series, and available values also vary.
‘function’ = name of the data series of choice. For example, “REAL_GDP”.
‘interval’ = time interval between data points. Not available for all series. Available options also vary between series. Consult Alphavantage’s documentation for detailed options.
‘datatype’ = In what form the data is given. JSON and CSV are available. Optional defaults to JSON.
‘apikey’ = your api key. Either the free or the premium license.
LightningChart Python Trader
LightningChart’s Python Trader (PT) provides extensive charting solutions with a high degree of customizability through its easy-to-use UI and built-in functionalities. Since the library is built for Python, it’s also possible to use other Python libraries if necessary.
As with all Lightningchart products, Performance has been a high priority when developing the library, even when working with large amounts of data, thus removing possible bottlenecks in this area.
Overview of the UI
Above is the PT user interface with stock data charted using the default candlestick chart. On the top left are controls used to customize the chart and work with datasets. Here is the explanation for all the UI controls:
Charting features
These are chart types of Python trader provides out of the box.
Chart types can be changed with the the UI or with the set_price_chart_type(chart_type) command. Available ones are ‘CandleStick’, ‘Bar’, ‘Line’, ‘Mountain’, ‘HeikinAshi’, ‘Renko’, ‘Kagi’, and ‘PointAndFigure’. For example, a mountain creating a mountain chart using the following methods:
trader.set_price_chart_type('Mountain')
trader.add_data_array(data)
trader.open()
Chart visuals can be customized using the Python trader UI. Below are available settings for chart and indicator colours, background colour/image etc.
Default chart colours.
Background and indicator colours changed
Chart customization
Customisation can also be done with code, using the built-in methods. The code below changes the background image and the chart colours to the ones seen in the right image. But why use code for customisation, since working with UI is easier?
trader.set_color_theme('cyberSpace')
# Changing the indicator colours for the candlesticks
trader.set_positive_body_color('#0fdf0c')
trader.set_positive_wick_color('#33d7a0')
trader.set_negative_body_color("#f3eb16")
trader.set_negative_wick_color('#b85900')
When the customization is applied on code level there’s no need to change any settings or load a template. Meaning you won’t have to make the changes every time when opening a chart. Python trader supports the use of templates for customization, and these files can be loaded in with code.
However, you still need to manually select the file, and in case you want to share the chart the template file would also need to be shared. When the changes are done in code, only it needs to be shared to get the same results.
Technical indicators
Python trader supports over 100 technical indicators. These include ones such as Relative Strength Index (RSI), Bollinger bands, Moving averages (SMA, EMA etc), Oscillators for money flow and price, Fibonacci retracements, as well as statistical ones like Standard deviation. Technical indicators can be added to a chart easily with the trader UI, their properties (period count, standard dev) can also be changed the same way.
These indicators can also be added and customized via code.
trader.add_simple_moving_average(period_count=14)
trader.add_bollinger_band(period_count=14)
Indicators such as the Fibonacci patterns can be added with the built-in draw tools. Other markers can also be added this way. To see all the indicators, refer to the documentation.
Setting Up Python Environment
The logic and variables are the same for all charts. Only the ‘ticker’ variable needs to be adjusted between them. Value of 0-,4 depending on what company is being charted. You can find more information regarding the API parameters from Alphavantage’s documentation. Although they don’t need to be changed for this project’s scope. For more information, consult Alpha Vantage’s documentation.
import requests
from lightningchart_trader import TAChart
license_key_path = "Python-Trader_License_key.txt"
# Load the license key and initializing Python trader
license_key = open(license_key_path).read()
trader = TAChart(license_key)
# api_name is the APi you wish to use for data eg: TIME_SERIES_DAILY. 'ticker' is the ticker specific stock eg: AAPL
# key is your Alphavantage API key
# https://www.alphavantage.co/query?function=api_name&symbol=ticker&apikey=key
api_key_path = "API-key.txt"
# Load the license key
api_key = open(api_key_path).read()
# Parameters used in Alphavantages API, consult their documentation for more details. Only 'ticker' needs to be adjusted for this projects scope.
ticker_list = ['CVX', 'XOM', 'COP', 'EOG', 'KMI']
api_name = 'TIME_SERIES_DAILY_ADJUSTED'
outputsize = 'full'
ticker = ticker_list[4]
# API URL change the ticker_list[x] index to whichever company you want tot chart
template_url = f'https://www.alphavantage.co/query?function={api_name}&apikey={api_key}&outputsize={outputsize}&symbol={ticker}'
API function
def api_call(template_url):
"""Make an API call for every URL passed to the function and convert the JSON respond to a Python dictionary"""
request = requests.get(template_url)
request_dict = request.json()
data_key = list(request_dict.keys())
# Formatting the API data for the Trader chart.
data_list = []
for date, value in request_dict[data_key[1]].items():
# Data needs to be in this order for the trader to work. Open,High,Low,Close,Volume(optional),Date.
# Dictionaries returned by the API use date as the dictionary key
data_list.append({'open': float(value['1. open']),
'high': float(value['2. high']),
'low': float(value['3. low']),
'close': float(value['4. close']),
'volume': float(value['6. volume']),
'date': date})
# Adding the data to the chart and setting chart title to the ticker
title_key = request_dict[data_key[0]]['2. Symbol']
trader.set_data(data_list)
trader.set_chart_title(title_key)
Call the api function and set other chart properties
api_call(template_url)
# Set chart customization and indicators
trader.add_simple_moving_average(period_count=5)
trader.add_moving_average_convergence_divergence()
trader.add_volume()
trader.add_relative_strength_index(period_count=5)
trader.change_time_range(2)
trader.open()
Oil and Gas Stock Analysis
As explained in the introduction, the purpose of this article was to analyse the stock of 5 companies that operate in the energy industry over the last five years.
Exxon Mobil Corporation
As with most stock prices during the pandemic, Exxon also experienced a price drop initially in 2020. Afterwards, there was a rebound due to the situation stabilising and stimulus packages. After this, the price becomes less volatile and begins to trend sideways. A similar pattern can be observed in all but one of the 5 companies being analysed.
There’s a strong support level when the price dropped to around $34 in 10/2020. Another level can be observed at approximately $100, as the price has not dropped under that since 9/2022. A resistance level during the sideways trend exists at around $117 – 120.
There was an increase in volume during the price spike in 2021-2023; however, after that, it has gone down. However, if the volume is observed over a longer period, it is slightly higher post-2023. This could be interpreted as the markets considering the current price to be stable and fair.
Chevron Corp
This company follows a similar trend to the previous, rebound after a drop, and then a more stable sideways trend. The sideways trend has had its lowest support level more recently, in 4/2025. This could indicate that the price might not be as stable in the future, but one data point doesn’t prove this. Volume is also higher on average post-2022 than before the pandemic. However, it’s not a large enough margin to be indicative of much.
ConocoPhillips
COP’s stock trend is similar to the previous two between 2020-2023; however, in 2024, it starts to have a much clearer downtrend. There was a resistance level at $125 in 3/2024; since then, the price has dropped steadily to $95 (7/2025).
This could indicate that the stock is underpriced, especially since other stocks in the industry don’t show this type of trend. However, coming to this conclusion purely from technical indicators is not wise, and further investigation is required. Another factor is that the volume of the stock has gone down in 2023 and onwards.
EOG Resources Inc
EOG also follows the pattern of, strong upwards trend followed by a sideways one. EOG’s stock probably has the strongest sideways direction, with very little volatility. It’s good to keep in mind that during this period, most stocks experienced something similar due to the special circumstances brought by COVID.
Nothing notable in terms of support/resistance. The price hasn’t fallen below ~$110, but there’s no sign of it increasing at the moment. Volume levels remain similar to what they were pre-pandemic.
Kinder Morgan Inc
Kinder Morgan’s stock has the most variation from the other stock price trends. While it does experience a slight bump in 2020, it is noticeably smaller compared to the others. In fact, it does not even return to its pre-pandemic levels. It also starts to trend sideways earlier than the other and has much less volatility. Finally, there is a strong upward trend starting in Q2 2024.
As the stock experienced relatively low volatility for a long period of time, there weren’t many supp/res levels to note. However, later on, in 12/2024, the upward trend starting in mid-2024 does slow down, and a notable resistance level can be observed. The stock price at the time was $27.4, a 5-year all-time high.
No notable changes that could be attributed to volume. At least when observed on a larger time horizon.
Conclusion
It’s easy to make a conclusion based on the candlesticks and technical indicators. However, it’s of course important to remember that these do not tell the whole truth. Since events during the last five or so years have affected economies globally, it’s important to keep in mind macroeconomic factors.
This visualization gives a good demonstration of how relying only on charts is not a good idea. One should further investigate macro and microeconomic factors to get a deeper understanding of why something happens.
Continue learning with LightningChart
How to Create a Strip Chart
Written by a human | Updated on April 9th, 2025What is a Strip chart application and what are the modern equivalents to it? Before computers exist or were taking their first steps, a Strip chart was a way to visualize an analog electrical signal. Voltage was...
Data Visualization Template for Electron JS | LightningChart®
Updated on April 4th, 2025 | Written by humanAre you already building cross-platform applications with Electron JS? In some of our previous articles, we’ve worked on TypeScript projects where we created pie charts and vibration chart applications. And as we...
Bar chart race JavaScript
Updated on April 14th, 2025 | Written by humanBar chart race JavaScript When I wrote this article, the COVID-19 pandemic was at its peak point. Today, things are much better thanks to vaccinations that continued their steady positive global effect. With this bar...
