Create Customized Stock Price Graphs

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to create a graph of multiple time series that demonstrates custom styling of plot frame, tick lines, tick labels, and line graph properties using Matplotlib. The graph will display stock prices of various companies over a period of 32 years.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedPlottingGroup(["`Advanced Plotting`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/AdvancedPlottingGroup -.-> matplotlib/log_scale("`Logarithmic Scale`") matplotlib/PlotCustomizationGroup -.-> matplotlib/grid_config("`Grid Configuration`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/FileHandlingGroup -.-> python/file_reading_writing("`Reading and Writing Files`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/with_statement -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} matplotlib/importing_matplotlib -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} matplotlib/figures_axes -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} matplotlib/line_plots -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} matplotlib/log_scale -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} matplotlib/grid_config -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/booleans -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/for_loops -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/lists -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/tuples -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/dictionaries -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/lambda_functions -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/importing_modules -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/using_packages -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/standard_libraries -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/file_reading_writing -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/numerical_computing -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/data_visualization -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} python/build_in_functions -.-> lab-48962{{"`Create Customized Stock Price Graphs`"}} end

Import necessary libraries

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.cbook import get_sample_data
import matplotlib.transforms as mtransforms

Load the stock data

with get_sample_data('Stocks.csv') as file:
    stock_data = np.genfromtxt(
        file, delimiter=',', names=True, dtype=None,
        converters={0: lambda x: np.datetime64(x, 'D')}, skip_header=1)

Create a figure and axis object

fig, ax = plt.subplots(1, 1, figsize=(6, 8), layout='constrained')

Define the colors to be used in the plot

ax.set_prop_cycle(color=[
    '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
    '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
    '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
    '#17becf', '#9edae5'])

Set the names and tickers of the stocks to be plotted

stocks_name = ['IBM', 'Apple', 'Microsoft', 'Xerox', 'Amazon', 'Dell',
               'Alphabet', 'Adobe', 'S&P 500', 'NASDAQ']
stocks_ticker = ['IBM', 'AAPL', 'MSFT', 'XRX', 'AMZN', 'DELL', 'GOOGL',
                 'ADBE', 'GSPC', 'IXIC']

Manually adjust the label positions vertically to avoid overlapping

y_offsets = {k: 0 for k in stocks_ticker}
y_offsets['IBM'] = 5
y_offsets['AAPL'] = -5
y_offsets['AMZN'] = -6

Plot each stock separately with its own color

for nn, column in enumerate(stocks_ticker):
    ## Plot each line separately with its own color.
    ## don't include any data with NaN.
    good = np.nonzero(np.isfinite(stock_data[column]))
    line, = ax.plot(stock_data['Date'][good], stock_data[column][good], lw=2.5)

    ## Add a text label to the right end of every line. Most of the code below
    ## is adding specific offsets y position because some labels overlapped.
    y_pos = stock_data[column][-1]

    ## Use an offset transform, in points, for any text that needs to be nudged
    ## up or down.
    offset = y_offsets[column] / 72
    trans = mtransforms.ScaledTranslation(0, offset, fig.dpi_scale_trans)
    trans = ax.transData + trans

    ## Again, make sure that all labels are large enough to be easily read
    ## by the viewer.
    ax.text(np.datetime64('2022-10-01'), y_pos, stocks_name[nn],
            color=line.get_color(), transform=trans)

Set the limits of the x-axis and y-axis, and add title and grid

ax.set_xlim(np.datetime64('1989-06-01'), np.datetime64('2023-01-01'))
fig.suptitle("Technology company stocks prices dollars (1990-2022)", ha="center")
ax.spines[:].set_visible(False)
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()
ax.set_yscale('log')
ax.grid(True, 'major', 'both', ls='--', lw=.5, c='k', alpha=.3)
ax.tick_params(axis='both', which='both', labelsize='large',
               bottom=False, top=False, labelbottom=True,
               left=False, right=False, labelleft=True)

Display the graph

plt.show()

Summary

In this lab, you learned how to create a graph of multiple time series that demonstrates custom styling of plot frame, tick lines, tick labels, and line graph properties using Matplotlib. You also learned how to plot each stock separately with its own color, set the limits of the x-axis and y-axis, and add title and grid.

Other Python Tutorials you may like