Dashboard in Python using Plotly Dash [Implemented]

what-is-a-dashbaord-title.png

A dashboard in Python is a collection of plots displayed all in one place to achieve a greater understanding of the analyzed data. The collection of plots includes, but is not limited to, bar graphs, histograms, pie charts, line charts, contours, shadow charts, etc. A dashboard can include either a combination of different plots displayed on one screen or multiple plots of the same kind.

Python provides multiple libraries to create plots and subplots from them, but in this article, we will be strictly working with the library that was created to make dashboards – Plotly Dash.

Also read: The Complete Python Plotly Tutorial

What is Dash?

Dash is a Plotly product that is used to create plots and render them over web-based APIs. The Plotly website says that Dash apps can easily achieve results of tasks where Tableau and PowerBI would struggle. That makes us choose Dash as our premiere tool to create dashboards in Python.

Creating a Dashboard

In this article, we will be creating a dashboard that analyses the 2020 stock market crash crash and its recovery caused due to covid-19. The example used here takes an index-specific approach. We use the OHLC data of Nifty50 in a daily timeframe. Once the dashboard is plotted, we will discuss the insights observed over the plots.

There are three major steps in order to create a dashboard in Python:

  • Importing necessary Packages
  • Fetching raw data which will get plotted
  • Initialising the application

Installing Necessary Libraries

Creating dash plots requires the main dash package along with its sub-packages. The example illustrated in this article requires 3 dash subpackages and a Numpy package to render raw data. Let’s look at how to install and configure those packages. To install them, type the following commands in the terminal.

pip install dash

The other main package required is pandas. This python library is required for mathematical computations for data frames. To install it, type the following command:

pip install pandas

Note: Creating Dashboards requires three other dash sub packages – dash html components, dash renderer, and dash core components(dcc).

Installing them manually is troublesome, so we recommend performing this example over an IDE like Pycharm or Jupyter Notebooks. For ease of use, we will be carrying forward with Pycharm. Installing these subpackages in Pycharm is simple, follow along with the steps below:

  • Create a new Project.
  • Go to File>Settings>Project:’project_name’>Python Interpreter.
pycharm-interpreter-guide.png

Click on the ‘+’ sign. (If the ‘+’ sign is inactive, choose the basic interpreter from the dropdown above and then click on the ‘+’ sign to add new interpreters.

A new window opens with a list of interpreters. Type the interpreters in the search box and click install package. The keywords you will be looking for are (‘dash-html-components’, ‘dash-core-components’ and ‘dash-renderer’)

Creating Plots for the Dashboard

Once all the necessary libraries are installed and configured, we will be shifting to the coding segment.

Importing data

The following libraries are the ones we will be needing throughout the program.

import dash
from dash import dcc
from dash import html
import pandas as pd

Initializing and Manipulating Data

For this example, we fetched the OHLC (Open-High-low-Close) data of the Nifty 50 index for Dec 2020-2021. We loaded the data into the data frame – ‘data’. The second line changes the ‘Date’ format from abbreviated to numerical.

data = pd.read_csv("nifty 2020 crash.csv")

data['Date'] = pd.to_datetime(data['Date']).dt.strftime('%d-%m-%Y')

Initializing the application

The dash application for offline API is initialized here. When this application is run, the plots will be rendered and broadcasted to a local server port, accessible through the local browser. The example code below plots a single graph in the server, the day-wise highest prices of the index.

app = dash.Dash(__name__)

app.layout=html.Div(
    children=[
        html.H1(children="Nifty 50 Crash and Recovery",),
        html.P(
            children="Analyzing day wise high and low prices of Nifty50 when first wave of Covid-19 hit.",
        ),
        dcc.Graph(
            figure={
                "data":[
                    {
                        "x":data["Date"],
                        "y":data["High"],
                        "type":"lines",
                    },
                ],
                "layout":{"title":"Day-wise highest prices of index"},
                    },
        ),
]
if __name__ == "__main__":
    app.run_server(debug=True)
day-high-plot.png

By now, you must have understood how to deploy a dash application with your desired data. Now, let’s put together all the segments into a single program and create a Nifty50 crash and recovery analysis dashboard.

Code Below:

# importing packages
import dash
from dash import dcc
from dash import html
import pandas as pd

# initialisation and manipulation of data
data = pd.read_csv("nifty 2020 crash.csv")
data['Date'] = pd.to_datetime(data['Date']).dt.strftime('%d-%m-%Y')
app = dash.Dash(__name__)

# Initialising the application.
app.layout=html.Div(
    children=[
        html.H1(children="Nifty 50 Crash and Recovery",),
        html.P(
            children="Analyzing day wise high and low prices of Nifty50 when first wave of Covid-19 hit.",
        ),
        dcc.Graph(
            figure={
                "data":[
                    {
                        "x":data["Date"],
                        "y":data["High"],
                        "type":"lines",
                    },
                ],
                "layout":{"title":"Day-wise highest prices of index"},
                   },
        ),
        dcc.Graph(
            figure={
                "data":[
                    {
                        "x":data["Date"],
                        "y":data["Low"],
                        "type":"lines",
                    },
                ],
                "layout": {"title": "Day-wise lowest prices of index"},
            },
        ),
        dcc.Graph(
            figure={
                "data": [
                    {
                        "x": data["Date"],
                        "y": data["Close"],
                        "type": "lines",
                    },
                ],
                "layout": {"title": "Day-wise closing prices of index"},
            },
        ),
        dcc.Graph(
            figure={
                "data": [
                    {
                        "x": data["Date"],
                        "y": data["Open"],
                        "type": "lines",
                    },
                ],
                "layout": {"title": "Day-wise opening prices of index"},
            },
        ),
] )

# deploying server
if __name__ == "__main__":
    app.run_server(debug=True)

Output:

Dashboard-Openprice.png
daywise-high.png
daywise-low.png
daywise-close.png

Insights

All the stock market crashes that happened before covid-19 witnessed a slow economic recovery process spread across many years. But in the above charts, we can observe that the rebound was quicker than expected, and in a span of just a few months, the whole market catapulted to new highs. This makes coming to a conclusion that:

  • Market Participants were willing to get back their money in the markets.
  • Going by the speed of recovery, it is quite evident that even big financial institutions were ready to invest back into the markets after the crash.
  • It provides a learning example for investors who believe in buying the dip.

Conclusion

To conclude, there are a few important things we could learn from this example. Observing how powerful and efficient dash is, this tool can help in creating complex data-heavy charts easily. You can create graphs, charts, and even a combination of them in your dashboard and can even broadcast it over web-based API through this platform.

We learned from this article the very basics of creating dashboards using Dash, which can both be implemented readily and can also be used as a great learning tool. It is hoped that this article will provide to be a resourceful learning tool in your journey to learning advanced concepts of Dash.

References

https://plotly.com/python/line-charts/#line-charts-in-dash

https://plotly.com/dash/