DEV Community

Cover image for Build an Interactive Sales Dashboard with Streamlit
Muhammad Saud
Muhammad Saud

Posted on Originally published at logicstack.org

Build an Interactive Sales Dashboard with Streamlit

Streamlit is an open source Python framework that turns a plain Python script into an interactive web app, with no HTML, CSS or JavaScript needed. In this tutorial we build a sales dashboard with Streamlit 1.67, Plotly and pandas: sidebar filters, four KPI cards, two interactive charts, a data table and a CSV download, all in one short file.

Key takeaways

  • Streamlit turns a Python script into a web app. We write pandas and Plotly code we already know, add a few Streamlit calls, and get a working dashboard.
  • Every widget change reruns the whole script from top to bottom, so filters stay simple: each widget returns a value we use in pandas.
  • st.cache_data loads the CSV once and reuses it on every rerun, as the Streamlit documentation recommends for slow steps such as loading data.
  • st.grid, added in the 5 November 2026 Streamlit release, lays out the KPI cards in a responsive grid, according to the Streamlit release notes.
  • We ran every line in this tutorial. The app serves on localhost:8501, renders two charts and four correct KPIs, and reports no errors.

What we build

Our dashboard reads a sales CSV with 180 orders from January to June 2026, worth $731,530 in total. The sidebar holds three filters: region, category and date range. The main page shows four KPI cards, a bar chart of revenue by category, a line chart of daily revenue, the filtered orders table, and a button that downloads the filtered rows as CSV. Laptops lead our data at $353,187, almost half of all revenue, and the North region leads at $205,471.

What do we need before we start?

We need Python 3.12 and pip. Nothing else is installed in advance. We create a project folder, then install three packages: Streamlit for the app, pandas for the data, and Plotly for the charts. We pin nothing in this tutorial, so we record exactly what pip installed, and we test against those versions.

How does a Streamlit app work?

A Streamlit app is a normal Python script that runs from top to bottom. When a user changes a widget, such as a dropdown or a slider, the whole script runs again, with the widget returning its new value. That sounds wasteful, and it is the first thing to understand. The fix is caching: st.cache_data remembers the result of a function and only runs it again when its inputs change. We cache the CSV load, so filtering stays fast even though the script reruns on every click. Streamlit serves the app on port 8501 by default, as the Streamlit documentation states.

Step 1: Install Streamlit, pandas and Plotly

We install the three packages in one command.

pip install streamlit pandas plotly
Enter fullscreen mode Exit fullscreen mode

Our install pulled in Streamlit 1.67.0, pandas 3.1.1 and Plotly 7.1.0. Those are the versions every step below was tested with. If our versions differ, the same code should still work, but the new st.grid layout in Step 5 needs a Streamlit version from November 2026 or later.

Step 2: Make the sales data

We generate our own dataset so the tutorial runs anywhere, with no download and no account. Save this as generate_data.py and run it once. It uses a fixed random seed, so our numbers match the ones in this tutorial exactly.

import random

import pandas as pd

random.seed(42)

CATEGORIES = {
    "Laptops": (900, 1800),
    "Phones": (400, 1100),
    "Monitors": (200, 600),
    "Accessories": (25, 120),
}
REGIONS = ["North", "South", "East", "West"]

rows = []
for i in range(180):
    category = random.choice(list(CATEGORIES))
    low, high = CATEGORIES[category]
    units = random.randint(1, 12)
    unit_price = random.randint(low, high)
    rows.append(
        {
            "order_id": f"ORD-{1000 + i}",
            "date": pd.Timestamp("2026-01-01") + pd.Timedelta(days=random.randint(0, 180)),
            "category": category,
            "region": random.choice(REGIONS),
            "units": units,
            "unit_price": unit_price,
            "revenue": units * unit_price,
        }
    )

df = pd.DataFrame(rows).sort_values("date").reset_index(drop=True)
df.to_csv("sales.csv", index=False)
print(f"Wrote sales.csv: {len(df)} rows")
print(f"Total revenue: ${df['revenue'].sum():,}")
print(f"Total units: {df['units'].sum():,}")
Enter fullscreen mode Exit fullscreen mode

Running it prints the real output we check our dashboard against later.

Wrote sales.csv: 180 rows
Total revenue: $731,530
Total units: 1,117
Revenue by category:
Laptops        353187
Phones         266848
Monitors        90164
Accessories     21331
Revenue by region:
North    205471
West     196401
East     181498
South    148160
Enter fullscreen mode Exit fullscreen mode

Keep those numbers in mind. If our dashboard shows different totals with all filters open, something in the load step is wrong.

Step 3: Load the data once with st.cache_data

We start app.py with imports, page settings and the cached loader. The @st.cache_data decorator is the whole trick: the CSV is read once, and every later rerun reuses the result.

import pandas as pd
import plotly.express as px
import streamlit as st

st.set_page_config(page_title="Sales Dashboard", layout="wide")

@st.cache_data
def load_data(path="sales.csv"):
    df = pd.read_csv(path, parse_dates=["date"])
    return df

df = load_data()

st.title("Sales Dashboard")
st.write("Filter the data in the sidebar. Every widget change reruns this script.")
Enter fullscreen mode Exit fullscreen mode

The parse_dates=["date"] argument matters. Without it, pandas reads the date column as text, and the date filter in the next step fails. We also set layout="wide" so the charts get room to breathe.

Step 4: Add filters in the sidebar

Filters live in the sidebar so the main page stays clear for charts. Each multiselect defaults to all values selected, so the dashboard starts by showing everything. The date input defaults to the full range of the data.

st.sidebar.header("Filters")
regions = st.sidebar.multiselect(
    "Region", options=sorted(df["region"].unique()), default=sorted(df["region"].unique())
)
categories = st.sidebar.multiselect(
    "Category", options=sorted(df["category"].unique()), default=sorted(df["category"].unique())
)
date_range = st.sidebar.date_input(
    "Date range",
    value=(df["date"].min().date(), df["date"].max().date()),
    min_value=df["date"].min().date(),
    max_value=df["date"].max().date(),
)

filtered = df[
    df["region"].isin(regions)
    & df["category"].isin(categories)
    & (df["date"].dt.date >= date_range[0])
    & (df["date"].dt.date st.stop() ends the run cleanly and shows the warning instead of a crash.

## Step 5: Show KPI cards with st.grid

Four headline numbers sit above the charts: total revenue, order count, units sold and average order value. We lay them out with st.grid, the responsive grid container Streamlit added in its 5 November 2026 release. It reflows the cards when the window narrows, which is exactly what a KPI row needs.

Enter fullscreen mode Exit fullscreen mode

total_revenue = int(filtered["revenue"].sum())
total_orders = len(filtered)
total_units = int(filtered["units"].sum())
avg_order = total_revenue / total_orders

grid = st.grid(4)
with grid.container():
st.metric("Total revenue", f"${total_revenue:,}")
with grid.container():
st.metric("Orders", f"{total_orders:,}")
with grid.container():
st.metric("Units sold", f"{total_units:,}")
with grid.container():
st.metric("Avg order value", f"${avg_order:,.0f}")


With all filters open, our test run shows $731,530 total revenue, 180 orders, 1,117 units sold and a $4,064 average order value. Those match the generator output from Step 2 exactly, which is the check that tells us the pipeline is sound.

## Step 6: Draw the charts with Plotly

Plotly charts are interactive by default: hover, zoom and pan all work with no extra code. We group the filtered data with pandas, then hand the result to Plotly Express. The bar chart answers which category earns the most, and the line chart shows whether revenue is rising or falling over time.

Enter fullscreen mode Exit fullscreen mode

by_category = filtered.groupby("category", as_index=False)["revenue"].sum()
fig_category = px.bar(
by_category, x="category", y="revenue", title="Revenue by category"
)
st.plotly_chart(fig_category, width="stretch")

daily = filtered.groupby("date", as_index=False)["revenue"].sum()
fig_trend = px.line(daily, x="date", y="revenue", title="Daily revenue")
st.plotly_chart(fig_trend, width="stretch")


Grouping by date gives one point per day, so the line chart has 121 points across the six months. If we grouped by month instead, the trend would look smoother but hide the daily shape. For a sales dashboard, the daily view is the honest one.

## Step 7: Add the table and a CSV download

Charts show the shape, but users also want the rows. We show the filtered table and a download button that exports exactly what the filters selected.

Enter fullscreen mode Exit fullscreen mode

st.subheader("Filtered orders")
st.dataframe(filtered, width="stretch")
st.download_button(
"Download filtered data as CSV",
data=filtered.to_csv(index=False),
file_name="filtered_sales.csv",
mime="text/csv",
)


The download is the feature users ask for first in every dashboard we have shipped. It turns the dashboard from a picture into a tool: filter to one region, download, and paste the rows into a report.

## Step 8: Run it and check it works

We run the app from the project folder.

Enter fullscreen mode Exit fullscreen mode

streamlit run app.py




The terminal prints the local address, and the browser opens at http://localhost:8501. We verified our app three ways: the server answered HTTP 200 on the local address, a scripted run of the app produced no exceptions and rendered two Plotly charts, one data table, one download button and two multiselect widgets, and the four KPI cards matched the generator totals. Try the filters now: pick only the North region and watch the revenue card drop to $205,471 and the orders count fall with it.

## What should we try next?

First, point the loader at a real CSV of our own and see the same dashboard work on our data. Second, add a second page with st.page_link for a per-region view, so each region gets its own chart. Third, deploy it free on Streamlit Community Cloud from a GitHub repository, which takes the dashboard from our laptop to a public link in a few minutes.

---

*Originally published on [LogicStack](https://logicstack.org/blog/build-interactive-sales-dashboard-streamlit). Run the code examples right in your browser with our free interactive [Python](https://logicstack.org/python-playground) and [SQL](https://logicstack.org/sql-playground) playgrounds — no setup, no sign-up.*
Enter fullscreen mode Exit fullscreen mode

Top comments (0)