Logistics Stock Analysis with LightningChart Python Trader

Tutorial

Written by a Human

Using LightningChart Python Trader, learn how to create a logistics stock analysis trading application in Python.
Mikael Virtanen

Mikael Virtanen

Data Science Python Developer

LinkedIn icon
Logistics-Stock-Analysis-Cover

Introduction

This article demonstrates how to create a logistics stock analysis using LightningChart Python Trader. The stocks in question are all Indian companies in the logistics and transportation industry. The stock data has been sourced from 4 Kaggle datasets by Dr. Jagadish Tawade & Nitiraj Kulkarni. The data will be preprocessed and imported to the trader using the Python library Pandas.

Dataset

The data for this article was acquired from a Kaggle dataset by Dr. Jagadish Tawade & Nitiraj Kulkarni. The data will be provided in CSV files that contain open, high, low, close, adj close, volume, and date values (as well as the ticker). Data is imported and pre-processed using Pandas data frames. This is the primary data set that is used in all the charts.

Plotted Variables

    Python trader requires Open, High, Low, Close (O, H, L, C) values to work as well as a date. These values refer to the stock’s Highest and Lowest prices during the trading day, as well as what the price was at market open and close. Volume value is not required for the trader to work, but is needed for certain indicators.

    The dataset provides both adjusted and unadjusted close values. LightningChart Python trader can read and process the data automatically as long as the fields (or in this case columns) are labelled correctly. For example, the date columns in the datasets are not, thus need to be addressed.

    Libraries used

    • LightningChart Python
    • Pandas

    Pandas will be used to import data to the trader. This is done by reading the dataset values and importing them into a data frame, which can easily be worked with before visualization. Pandas might be preinstalled with the Python standard library. If this is not the case, simply run the following command in the terminal. Python Trader also needs to be installed.

    pip install pandas
    pip install lightningchart_trader

    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

    Stock-Market-Data-Visualization-with-Python-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:

    Stock-Market-Data-Visualization-Python-UI-Controls-IMG

    Charting features

    These are chart types of Python trader provides out of the box.

    Stock-Market-Data-Visualization-with-Python-Chart-Types

    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()
    Stock-Market-Data-Visualization-with-Python-Mountain-Chart-Example

    Chart visuals can be customized using the Python trader UI. Below are available settings for chart and indicator colours, background colour/image etc.

    Stock-Market-Data-Visualization-with-Python-Color-UI
    Stock-Market-Data-Visualization-with-Python-Background-UI

    Default chart colours.

    Stock-Market-Data-Visualization-with-Python-Default-Colors

    Background and indicator colours changed

    Stock-Market-Data-Visualization-with-Python-Background-Color-Options

    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.

    Stock-Market-Data-Visualization-with-Python-Technical-Indicators

    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 data set is downloaded as a .csv file. This is the code used to process data and import it into charts.

    from lightningchart_trader import TAChart
    import pandas as pd
    import os
    license_key_path = "Python-Trader_License_key.txt" 
    # license key for python trader and the stock API
    license_key = open(license_key_path).read()
    chart = TAChart(license_key)
    path_to_csv = 'data/project-12/'
    # All file names in the filepath
    csv_list = os.listdir(path_to_csv)

    This part of the code imports the necessary libraries and assigns the Python trader license key to a variable. I recommend providing a full file path to the CSV files, even if the data is saved in the same directory or a subdirectory in relation to your .py files. This since I’ve personally experienced issues with Python when only a partial path is provided. In the following example, note the different types of forward slashes used. Python might give an error if you input the path in the same format as it is in the file directory.

    'C:/Users\name\Desktop\path\to\the\files/'

    Logistics Stock Analysis & Visualizations

    We will now start creating the visualizations.

    VRL logistics stock data between 2015-2024

    A line chart for the stock price for VRL Logistics between 2015-2024, with an RSI indicator added. The RSI indicator can help determine if a stock is overbought or oversold.

    Logistics-Stock-Analysis-VRL-Logistics
    from lightningchart_trader import TAChart
    import pandas as pd
    import os
    license_key_path = "Python-Trader_License_key.txt" 
    # license key for python trader and the stock API
    license_key = open(license_key_path).read()
    chart = TAChart(license_key)
    path_to_csv = 'data/project-12/'
    # All file names in the filepath
    csv_list = os.listdir(path_to_csv)
    print(csv_list)
    # Transform the CSV into a dataframe, combine the file path, with the desired files name 
    stock_dataframe = pd.read_csv(path_to_csv + csv_list[3])
    # rename the date column
    stock_dataframe = stock_dataframe.rename(columns={'Unnamed: 0' : 'date'})
    # Set chart title; I'm using the file name as a placeholder, 
    # type; CandleStick, Bar, Line, Mountain, Renko, HeikinAshi, Kagi or Point&Figure 
    # and data source used; in this case the stock dataframe
    chart.set_chart_title(csv_list[3])
    chart.set_price_chart_type('Line') 
    chart.set_data(stock_dataframe)
    # Optional appearence customization
    chart.set_color_theme('darkGold')
    chart.set_line_color("#FCD601")
    chart.change_time_range(3)
    chart.add_high_minus_low()
    chart.add_historical_volatility_index()
    chart.open()

    A dashboard for several Indian logistics companies

    A dashboard for comparing price trends for several stock prices. The date range varies quite a bit between the charts. Thus, they have been limited to the shortest time frame. The dashboard is an effective way to make comparisons, as it still supports all features (indicators, chart types, etc).

    Logistics-Stock-Analysis-Indian-Companies
    from lightningchart_trader import TAChart
    import pandas as pd
    import os
    license_key_path = "Python-Trader_License_key.txt" 
    # license key for python trader and the stock API
    license_key = open(license_key_path).read()
    chart = TAChart(license_key)
    path_to_csv = 'data/project-12/'
    # All file names in the filepath
    csv_list = os.listdir(path_to_csv)
    print(csv_list)
    # Create a new dashboard with two rows and a two column
    new_dashboard = chart.create_dashboard(rows=2, cols=2)
    # These values will be used to add charts to the dashboard
    row_index = 0
    col_index = 0
    # Loop though files other than the chemical index and add them to the dashboard
    for index in range(4):
        # Transform the CSV into a dataframe, combine the file path, with the desired files name 
        stock_dataframe = pd.read_csv(path_to_csv + csv_list[index])
        chart_title = csv_list[index].removesuffix('.csv')
        # rename date column 
        stock_dataframe = stock_dataframe.rename(columns={'Unnamed: 0' : 'date'})
        # Add a chart to the dashboard witht he following parameters      
        dash_chart = new_dashboard.add_chart(chart_type='Line', 
                                             row_index=row_index, column_index=col_index,  
                                             title=chart_title).set_data(stock_dataframe)
        # Place charts to the dashboard based on the current column and row index
        col_index += 1
        if col_index >= 2:
            col_index = 0
            row_index += 1
        # Optional appearence customization
        dash_chart.set_line_color("#65FC01")
        dash_chart.change_time_range(2)   
        dash_chart.add_volume() 
    chart.open()

    Yearly returns for VRL Logistics

    This visualization also includes the RSI index and volume indicators.

    Logistics-Stock-Analysis-VRL-Yearly-Return

    Settings for the volume indicator were changed to not show it as an overlay or have two colored bars. The first change puts the indicator in its own window, which improves visibility. The second one makes the indicator one color (also helps visibility). You can access the settings by clicking on the pen icon in the top left corner. The drawing tool can be accessed from the UI. Set the magnetic mode on as selected by right-clicking on the range nodes. With this setting, the price range tool will automatically lock to the chart.

    Logistics-Stock-Analysis-Settings

    Dashboard with volume  and RSI indicator

    The same dashboard as above, with the two indicators added. The two were chosen to see if there are increases in volume during the oversold or bought periods. The increase in volume can reinforce RSI’s reliability, as spikes and drops that correlate with higher volume tend to be more reliable.

    Logistics-Stock-Analysis-Volume-RSI-Indicator
    from lightningchart_trader import TAChart
    import pandas as pd
    import os
    license_key_path = "Python-Trader_License_key.txt" 
    # license key for python trader and the stock API
    license_key = open(license_key_path).read()
    chart = TAChart(license_key)
    path_to_csv = 'data/project-12/'
    # All file names in the filepath
    csv_list = os.listdir(path_to_csv)
    print(csv_list)
    # Create a new dashboard with two rows and a two column
    new_dashboard = chart.create_dashboard(rows=2, cols=2)
    # These values will be used to add charts to the dashboard
    row_index = 0
    col_index = 0
    # Loop though files other than the chemical index and add them to the dashboard
    for index in range(4):
        # Transform the CSV into a dataframe, combine the file path, with the desired files name 
        stock_dataframe = pd.read_csv(path_to_csv + csv_list[index])
        chart_title = csv_list[index].removesuffix('.csv')
        # rename date column 
        stock_dataframe = stock_dataframe.rename(columns={'Unnamed: 0' : 'date'})
        # Add a chart to the dashboard witht he following parameters      
        dash_chart = new_dashboard.add_chart(chart_type='Line', 
                                             row_index=row_index, column_index=col_index,  
                                             title=chart_title).set_data(stock_dataframe)
        # Place charts to the dashboard based on the current column and row index
        col_index += 1
        if col_index >= 2:
            col_index = 0
            row_index += 1
        # Optional appearence customization
        dash_chart.set_line_color("#65FC01")
        dash_chart.change_time_range(2)   
        dash_chart.add_volume()
        dash_chart.add_relative_strength_index()
    chart.open()

    VRL logistics stock price with High-minus-low and historical volatility indicators

    High minus low simply tracks the difference between the day’s highest and lowest price. Historical volatility measures stock prices from the average price of a period.

    Logistics-Stock-Analysis-VRL-Volatility
    from lightningchart_trader import TAChart
    import pandas as pd
    import os
    license_key_path = "Python-Trader_License_key.txt" 
    # license key for python trader and the stock API
    license_key = open(license_key_path).read()
    chart = TAChart(license_key)
    path_to_csv = 'data/project-12/'
    # All file names in the filepath
    csv_list = os.listdir(path_to_csv)
    print(csv_list)
    # Transform the CSV into a dataframe, combine the file path, with the desired files name 
    stock_dataframe = pd.read_csv(path_to_csv + csv_list[3])
    # rename the date column
    stock_dataframe = stock_dataframe.rename(columns={'Unnamed: 0' : 'date'})
    # Set chart title; I'm using the file name as a placeholder, 
    # type; CandleStick, Bar, Line, Mountain, Renko, HeikinAshi, Kagi or Point&Figure 
    # and data source used; in this case the stock dataframe
    chart.set_chart_title(csv_list[3])
    chart.set_price_chart_type('Line') 
    chart.set_data(stock_dataframe)
    # Optional appearence customization
    chart.set_color_theme('darkGold')
    chart.set_line_color("#FCD601")
    chart.change_time_range(3)
    chart.add_high_minus_low()
    chart.add_historical_volatility_index()
    chart.open()

    How has VRL Logistics’ stock price evolved over time?

    VRL Logistics has experienced moderate volatility between 2015-2024. It had a bad performance before the pandemic and dropped quite a bit in 2022. The price since then has rebounded not only to pre-pandemic levels but also surpassed them. While there was a short upward trend, the stock experienced another sudden drop in Q1/2024.

    What differences exist between the stock performances of VRL Logistics and other logistics companies?

    Most of the observed stocks repeat the same pandemic-related pattern. A drop during 2020 and then a steady rebound, and even a large spike. There is one outlier, Maheshwari Logistics. While the company experienced a large drop, the rebound is less noticeable. It should be noted that their stock price is the most volatile of the four.

    Is there a strong correlation between VRL Logistics’ stock price and market indices?

    At least when comparing these four stocks, no correlation appears to emerge.

    How does trading volume influence price movement in logistics stocks?

    The spikes in both volume and price do appear to happen at the same time. However, this would require a more statistical analysis to confirm. The spikes in volume also tend to be quite large. There’s usually also a trend of a downward trend after a price spike. A spike in volume could be good news or predictions leading to an increase in retail/institutional interest, but turning out to be an overreaction.

    Conclusion

    To create this logistics stock analysis, the stock data has been imported from a CSV file to LightningChart Python Trader. The Pandas library was used to preprocess the data, and all the charting was done within LightningChart Python Trader. After the code was done, it was easy to change the indicators and chart properties for different situations.

    Continue learning with LightningChart

    Water Potability Analysis

    Water Potability Analysis

    Learn to utilize LightningChart in Python for effective water potability analysis, ensuring safe and reliable drinking water evaluations.