Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build a shareable sales dashboard with Python, pandas, Plotly, and Streamlit. The finished app loads and validates a CSV, filters records by date, region, and category, recalculates KPIs, renders interactive charts, shows filtered rows, and offers a CSV download. You can run it locally with streamlit run app.py and deploy the same project from GitHub.

What Streamlit is—and when to use it

Streamlit is an open-source Python framework for turning data and model code into browser-based applications without requiring HTML, CSS, JavaScript, React, or Flask. Its execution model is simple: when a user changes a widget, Streamlit normally reruns the script from top to bottom. That makes small analytical apps quick to build, but it also means data loading, state, caching, and expensive queries need deliberate design. See the Streamlit documentation.

Streamlit is a strong fit for exploratory data apps, internal dashboards, machine-learning demos, portfolio projects, lightweight reporting tools, and prototypes. A conventional front end, BI platform, Flask/FastAPI service, or more specialized dashboard framework is usually a better choice when you need highly customized consumer UX, complex client-side interactions, a public multi-tenant SaaS, sophisticated background jobs, or a full API.

What you will build

The example is a sales dashboard backed by data/sales.csv. The sample data is assumed to contain these columns:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
  • order_date
  • region
  • category
  • product
  • sales
  • profit
  • quantity

The interface will contain sidebar filters, sales and profit KPIs, a time-series chart, category and regional comparisons, a filtered data table, and a download button. Adapt the names and calculations to your own data model; never assume that one row is one order unless the source defines it that way.

Set up the project

Recommended structure

streamlit-dashboard/
├── app.py
├── data/
│   └── sales.csv
├── requirements.txt
├── README.md
└── .gitignore

Start with one file so the execution flow is easy to understand. When the app grows, move loading, metric, and chart functions into a src/ package and use Streamlit’s pages/ convention for multiple views.

Create an environment and install packages

python -m venv .venv

# macOS/Linux
source .venv/bin/activate

# Windows PowerShell
.venvScriptsActivate.ps1

pip install streamlit pandas plotly

Put the packages your app actually imports in requirements.txt:

streamlit
pandas
plotly

After testing, pin versions for reproducible deployment, for example streamlit==<tested-version>; do not copy untested version numbers into production.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Load and validate the data

Use a path based on the script location rather than a path from your laptop. Parse dates and numeric fields explicitly, check the schema, and stop with a useful message when the file is absent or malformed.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
from pathlib import Path

import pandas as pd
import streamlit as st

DATA_PATH = Path(__file__).parent / "data" / "sales.csv"
REQUIRED_COLUMNS = {
    "order_date", "region", "category", "product",
    "sales", "profit", "quantity",
}

@st.cache_data
def load_data(path: str) -> pd.DataFrame:
    df = pd.read_csv(path)
    missing = REQUIRED_COLUMNS - set(df.columns)
    if missing:
        raise ValueError(
            "Dataset is missing required columns: "
            + ", ".join(sorted(missing))
        )

    df["order_date"] = pd.to_datetime(df["order_date"], errors="coerce")
    for column in ["sales", "profit", "quantity"]:
        df[column] = pd.to_numeric(df[column], errors="coerce")

    return df.dropna(
        subset=["order_date", "region", "category", "sales", "profit", "quantity"]
    )

try:
    df = load_data(str(DATA_PATH))
except FileNotFoundError:
    st.error(f"Could not find the data file: {DATA_PATH}")
    st.stop()
except ValueError as error:
    st.error(str(error))
    st.stop()

st.cache_data is intended for serializable results such as DataFrames. It avoids reading and transforming the same data on every widget rerun. Use st.cache_resource instead for shared resources such as database connections or machine-learning models. The distinction and cache trade-offs are documented in Streamlit’s caching guide.

Create the page and sidebar filters

import streamlit as st

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

st.title("Sales Dashboard")
st.caption("Explore sales performance by date, region, and category.")

st.sidebar.header("Filters")
regions = sorted(df["region"].dropna().unique())
categories = sorted(df["category"].dropna().unique())

selected_regions = st.sidebar.multiselect(
    "Region", regions, default=regions
)
selected_categories = st.sidebar.multiselect(
    "Category", categories, default=categories
)

min_date = df["order_date"].min().date()
max_date = df["order_date"].max().date()
selected_dates = st.sidebar.date_input(
    "Order date",
    value=(min_date, max_date),
    min_value=min_date,
    max_value=max_date,
)

filtered_df = df[
    df["region"].isin(selected_regions)
    & df["category"].isin(selected_categories)
].copy()

if len(selected_dates) == 2:
    start_date, end_date = selected_dates
    filtered_df = filtered_df[
        filtered_df["order_date"].dt.date.between(start_date, end_date)
    ]

if filtered_df.empty:
    st.warning("No records match the selected filters.")
    st.stop()

Apply every filter before calculating metrics or charts so the dashboard describes the visible selection. A cleared multiselect returns an empty list, and a date input can temporarily return one date rather than a two-date tuple; the checks above handle both cases.

Calculate and display KPIs

Use labels that identify the measure and format values for the relevant currency and geography. If the dataset has an order_id, count unique orders rather than rows.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
total_sales = filtered_df["sales"].sum()
total_profit = filtered_df["profit"].sum()
total_quantity = filtered_df["quantity"].sum()
profit_margin = total_profit / total_sales if total_sales else 0

col1, col2, col3, col4 = st.columns(4)
col1.metric("Sales", f"${total_sales:,.0f}")
col2.metric("Profit", f"${total_profit:,.0f}")
col3.metric("Quantity", f"{total_quantity:,.0f}")
col4.metric("Profit margin", f"{profit_margin:.1%}")

The zero check prevents division errors. Also distinguish rows, line items, orders, and customers: len(filtered_df) is only an order count when each row represents exactly one order.

Add interactive charts

Sales over time

import plotly.express as px

sales_by_date = (
    filtered_df.groupby("order_date", as_index=False)["sales"].sum()
)
sales_chart = px.line(
    sales_by_date,
    x="order_date",
    y="sales",
    title="Sales over time",
    markers=True,
)
st.plotly_chart(sales_chart, use_container_width=True)

Category and region comparisons

left, right = st.columns(2)

with left:
    sales_by_category = (
        filtered_df.groupby("category", as_index=False)["sales"]
        .sum().sort_values("sales", ascending=False)
    )
    chart = px.bar(
        sales_by_category, x="category", y="sales",
        title="Sales by category", text_auto=".2s"
    )
    st.plotly_chart(chart, use_container_width=True)

with right:
    profit_by_region = (
        filtered_df.groupby("region", as_index=False)["profit"]
        .sum().sort_values("profit", ascending=False)
    )
    chart = px.bar(
        profit_by_region, x="region", y="profit",
        title="Profit by region", text_auto=".2s"
    )
    st.plotly_chart(chart, use_container_width=True)
Question Useful chart
How does a measure change over time? Line chart
Which groups rank highest? Bar chart
How are two numeric variables related? Scatter plot
What is the distribution? Histogram or box plot
What are the exact records? Dataframe or table

Use clear axis labels and units. Avoid pie charts with many categories, 3D charts for ordinary business data, and unexplained abbreviations.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Show and download the filtered data

st.subheader("Filtered records")
st.dataframe(
    filtered_df.sort_values("order_date", ascending=False),
    use_container_width=True,
    hide_index=True,
)

csv = filtered_df.to_csv(index=False).encode("utf-8")
st.download_button(
    "Download filtered CSV",
    data=csv,
    file_name="filtered_sales.csv",
    mime="text/csv",
)

The download reflects the current filters, not necessarily the original file. Treat that as a data-export capability: do not expose confidential columns or records without appropriate access controls.

Understand reruns, caching, and state

Streamlit reruns the script when a widget changes or source code is updated. Keep loading and deterministic transformations cacheable, and make filtering and chart generation safe to execute repeatedly. st.cache_data returns cached data results; st.cache_resource is for shared resources and can expose the same object across sessions, so avoid mutating cached resources.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use st.session_state for per-user values that must survive reruns, such as a selected record, a multi-step workflow, or a page-specific toggle. It is not durable storage and should not replace a database. Caching can also produce stale data or memory pressure; choose an expiration or refresh strategy when freshness matters.

Run the app locally

  1. Place app.py and the data/ directory at the project root.
  2. Activate the virtual environment.
  3. Install the packages listed in requirements.txt.
  4. Run streamlit run app.py.
  5. Open the local URL printed in the terminal if a browser does not open automatically.

A local absolute path such as /Users/name/Desktop/sales.csv may work only on one computer. The Path(__file__).parent pattern keeps the app portable.

Deploy to Streamlit Community Cloud

  1. Commit app.py, requirements.txt, and any permitted sample data to a GitHub repository.
  2. Confirm that every path is relative to the repository and that the entry-point file runs locally.
  3. Sign in to Streamlit Community Cloud with GitHub.
  4. Choose the repository, branch, and app file, then deploy.
  5. Read the deployment logs if the build or app fails.

Streamlit describes Community Cloud as a free service for creating, deploying, managing, and sharing apps, and says it connects to public and private GitHub repositories; most apps launch within a few minutes. Free hosting does not make every workload appropriate for the service: confidential or regulated data, guaranteed uptime, private networking, enterprise identity, and specialized infrastructure may require another deployment model. See the Community Cloud overview and deployment guide.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Keep credentials out of Git

Never put passwords, API keys, or database credentials in Python, screenshots, query parameters, or a committed secrets file. For local development, create .streamlit/secrets.toml and add it to .gitignore:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.streamlit/secrets.toml
[database]
host = "example-host"
username = "example-user"
password = "example-password"
import streamlit as st
password = st.secrets["database"]["password"]

Enter deployment secrets through the app settings rather than committing the file. Follow Community Cloud secrets management and Streamlit’s general secrets guidance. If a credential has been pushed, revoke and replace it; deleting the latest copy does not erase its exposure from repository history.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use an API or database when a CSV is no longer enough

A local CSV is excellent for a tutorial, small static data, and reproducible portfolio demos. An API suits frequently changing external data. A database is more appropriate for larger datasets, controlled updates, multiple users, and centralized permissions.

For database-backed apps, use parameterized queries, limit data at the source, put credentials in secrets, cache connections with st.cache_resource where appropriate, and define how users refresh data. Streamlit documents connections to CSVs, APIs, and databases in Connecting to data. Its local filesystem should not be treated as permanent storage on Community Cloud.

Troubleshoot common failures

The app works locally but deployment fails

  • Check that every imported package appears in requirements.txt.
  • Check filename capitalization and replace absolute paths.
  • Confirm the data file is committed and the selected entry point is correct.
  • Add missing secrets through deployment settings.
  • Read the build and runtime logs for the first error, not just the final message.

The app is slow

  • Cache file reads and deterministic transformations with st.cache_data.
  • Cache database connections with st.cache_resource.
  • Filter in the database before downloading rows.
  • Aggregate before plotting and limit very large tables.
  • Do not mutate shared cached resources.

Filters show nothing

Display a warning and stop instead of rendering blank charts. Suggest broadening the date range or selecting more categories. Check for inconsistent whitespace and capitalization in categorical fields.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Date filtering is wrong

Convert strings with pd.to_datetime before comparison, decide whether the end date is inclusive, handle invalid dates, and guard against a one-value date input before unpacking two dates.

Metrics are misleading

Verify the dataset grain and denominator. For example, if there is an order_id, use filtered_df["order_id"].nunique() for orders rather than counting line-item rows.

Choose the right tool and host

Need Likely choice
Python-first interactive analysis or prototype Streamlit
Sequential exploration and narrative code Notebook
Governed drag-and-drop reporting for many business authors BI platform
Custom web UI or API service Flask, FastAPI, or a separate front end
Highly component-driven Plotly dashboard Dash may be preferable

For hosting, Community Cloud is the simplest route for a public demo or student project. Streamlit in Snowflake is aimed at organizations already using Snowflake; its costs depend on app runtime and query-warehouse usage, as described in Snowflake’s billing documentation. Hugging Face Spaces can suit machine-learning demos and offers hardware tiers through its pricing page. Other hosting options involve compute, TLS, authentication, monitoring, backups, networking, and CI/CD decisions; see Streamlit’s deployment overview.

Frequently Asked Questions

Can I build a Streamlit dashboard without JavaScript?

Yes. Streamlit lets you create the interface and interactions primarily in Python, although its predefined layout and widget model are less customizable than a conventional front end.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does my Streamlit code run again after every filter change?

That is Streamlit’s normal rerun model. Cache expensive data or resource creation, and use session state for per-user values that must persist between reruns.

Should I use a CSV or a database?

Use a CSV for small, static, tutorial, or portfolio data. Move to an API or database when data changes frequently, grows large, needs controlled updates, or must support multiple users and permissions.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.