Data analysis · Intermediate · 22 min
Build a data dashboard with Streamlit
By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · Streamlit 1.67.0 · pandas 3.1.1
You will have a Streamlit sales dashboard running on localhost, with date and region filters, headline numbers, a weekly chart, a table, a CSV download of the filtered rows and a headless test suite that checks it all.
On this page
Streamlit turns a Python script into a web page. You write ordinary top-to-bottom Python, call functions such as st.metric or st.line_chart where you want something on the page, and Streamlit serves the result in a browser. There is no HTML, no JavaScript and no separate front end to build. The one idea to hold on to: every time someone changes a filter, Streamlit runs the whole script again from the top and redraws the page with the new values.
In this tutorial you build a sales dashboard for a made-up company that sells three subscription plans in Accra, Johannesburg, Lagos and Nairobi. The data is six months of orders in a Parquet file. The finished page has a sidebar with date and region filters, three headline numbers, a weekly revenue chart and a table of orders in tabs, and a button that downloads the filtered rows as CSV. Then you write tests that drive the dashboard without a browser, so you can change it later without clicking through every filter by hand.
You build app.py in blocks. Each step appends one block to the end of the file, which works because the script runs in order: load, filter, summarise, show.
Step 1 · Create the project and install Streamlit
Make a throwaway folder and a virtual environment, then install Streamlit with pandas, pyarrow (which pandas uses to read Parquet), NumPy and pytest, pinned to the versions this tutorial was written against:
mkdir -p ~/streamlit-demo/.streamlit
cd ~/streamlit-demo
python3 -m venv .venv
. .venv/bin/activate
pip install "streamlit==1.67.0" "pandas==3.1.1" "pyarrow==26.0.1" "numpy==2.5.5" "pytest==9.2.0"
python -c "import streamlit, pandas, pyarrow; print(streamlit.__version__, pandas.__version__, pyarrow.__version__)"pyarrow is the largest download of the set. On prepaid mobile data, run the install once on Wi-Fi: pip caches the wheels, so the same versions in a later project come from disk.
Next, give the project its own Streamlit settings. Streamlit reads .streamlit/config.toml from the folder you start it in:
cd ~/streamlit-demo
cat > .streamlit/config.toml <<'TOML'
[browser]
gatherUsageStats = false
[server]
showEmailPrompt = false
runOnSave = true
TOMLgatherUsageStats = false stops the page from sending anonymous usage statistics to Streamlit. showEmailPrompt = false skips the question about your email address that Streamlit otherwise asks the first time you run it. runOnSave = true reruns the app as soon as you save app.py, so the browser follows each step without a click.
Check it worked
The last command prints 1.67.0 3.1.1 26.0.1 and your prompt starts with (.venv). If you open a new terminal later, run cd ~/streamlit-demo and . .venv/bin/activate in it before any python, streamlit or pytest command.
Step 2 · Generate the sales data
Real exports have gaps and odd values that would distract from the dashboard, so make_data.py generates clean orders with a fixed seed. Your numbers will match the ones in this tutorial exactly. Each row is one order: an ID, a date, a region, a plan, the number of units and the revenue in US dollars.
cd ~/streamlit-demo
. .venv/bin/activate
cat > make_data.py <<'PY'
"""Six months of made-up orders in four cities. Same numbers on every run."""
import numpy as np
import pandas as pd
rng = np.random.default_rng(seed=2026)
DAYS = pd.date_range("2026-01-01", "2026-06-30", freq="D")
ORDERS_PER_DAY = {"Accra": 18, "Johannesburg": 24, "Lagos": 40, "Nairobi": 30}
PRICES_USD = {"Starter": 12.0, "Standard": 30.0, "Pro": 75.0}
regions = list(ORDERS_PER_DAY)
counts = rng.poisson(list(ORDERS_PER_DAY.values()), size=(len(DAYS), len(regions))).ravel()
date = np.repeat(np.repeat(DAYS.values, len(regions)), counts)
region = np.repeat(np.tile(regions, len(DAYS)), counts)
n = len(date)
product = rng.choice(list(PRICES_USD), size=n, p=[0.5, 0.35, 0.15])
units = rng.integers(1, 4, size=n)
price = pd.Series(product).map(PRICES_USD).to_numpy()
sales = pd.DataFrame(
{
"order_id": np.arange(1, n + 1),
"date": date,
"region": region,
"product": product,
"units": units,
"revenue_usd": units * price,
}
)
sales.to_parquet("sales.parquet", index=False)
print(f"{len(sales):,} orders from {sales['date'].min():%Y-%m-%d} to {sales['date'].max():%Y-%m-%d}")
for region, total in sales.groupby("region")["revenue_usd"].sum().items():
print(f"{region:<13} {total:>12,.2f} USD")
PY
python make_data.pyParquet stores each column with its type, so the date column comes back as dates and not as text, and the file is a fraction of the size of the same data as CSV. For more on the format, see read Excel, CSV and Parquet files with pandas.
Check it worked
The script prints:
20,333 orders from 2026-01-01 to 2026-06-30
Accra 184,188.00 USD
Johannesburg 243,993.00 USD
Lagos 394,725.00 USD
Nairobi 296,658.00 USDand ls shows a new sales.parquet of about 150 KB.
Step 3 · Load the data once and start the app
Create app.py with the first block: page settings, a function that reads the file, a title and a caption that says how many orders were loaded.
cd ~/streamlit-demo
cat > app.py <<'PY'
import pandas as pd
import streamlit as st
st.set_page_config(page_title="Sales dashboard", layout="wide")
@st.cache_data
def load_sales(path):
print(f"Reading {path}", flush=True)
return pd.read_parquet(path)
sales = load_sales("sales.parquet")
st.title("Sales dashboard")
st.caption(f"{len(sales):,} orders loaded from sales.parquet")
PY@st.cache_data matters because of the rerun model. Without it, every click on a filter would read the Parquet file from disk again. With it, Streamlit runs load_sales once for each distinct argument, stores the DataFrame it returns, and hands back a copy of the stored result on every later run. The print goes to the terminal, not the page, so you can see when the file is really read. layout="wide" lets the page use the full browser width, which suits a dashboard.
Start the app in your second terminal, from the project folder, and leave it running:
cd ~/streamlit-demo
. .venv/bin/activate
streamlit run app.pyStreamlit prints something like You can now view your Streamlit app in your browser followed by Local URL: http://localhost:8501, and opens that address in your browser if it can. If no browser opens, visit the address yourself. Back in your first terminal, ask the server whether it is ready:
curl -s http://localhost:8501/_stcore/health; echoThe /_stcore/health address is what a load balancer or a container platform would poll once you deploy the app.
Check it worked
The browser shows the heading Sales dashboard with the line 20,333 orders loaded from sales.parquet under it. The second terminal shows Reading sales.parquet once. The curl command prints ok.
Step 4 · Add date and region filters in the sidebar
Anything you call on st.sidebar goes into a panel on the left of the page. Append the filters and the filtering code:
cd ~/streamlit-demo
cat >> app.py <<'PY'
first_day = sales["date"].min().date()
last_day = sales["date"].max().date()
st.sidebar.header("Filters")
picked = st.sidebar.date_input(
"Dates",
value=(first_day, last_day),
min_value=first_day,
max_value=last_day,
)
all_regions = sorted(sales["region"].unique())
regions = st.sidebar.multiselect("Regions", all_regions, default=all_regions)
if len(picked) != 2:
st.info("Pick an end date in the calendar.")
st.stop()
start, end = picked
in_dates = sales["date"].between(pd.Timestamp(start), pd.Timestamp(end))
filtered = sales[in_dates & sales["region"].isin(regions)]
if filtered.empty:
st.warning("No orders match these filters.")
st.stop()
PYEach widget call does two jobs: it draws the control, and it returns whatever the control currently holds. Passing a pair of dates as value turns date_input into a range picker. While someone is halfway through picking a range, it returns only one date, so the script checks for two before it unpacks them. st.stop() ends the current run at that line, which is a tidy way to show a message and skip everything below it. The filtered DataFrame is plain pandas and is rebuilt on every run, which is cheap; only the file read is cached.
Check it worked
The page now has a sidebar with a date range from 2026/01/01 to 2026/06/30 and all four regions selected. Remove every region: the yellow message No orders match these filters. appears. Add Lagos back and the message goes. In the second terminal, Reading sales.parquet still appears only once, however many times you change the filters, because the cache served every rerun.
Step 5 · Show headline numbers with st.metric
A dashboard should answer the first question at a glance, so put three numbers at the top. st.columns(3) splits the page into three equal columns and returns one container for each:
cd ~/streamlit-demo
cat >> app.py <<'PY'
revenue = filtered["revenue_usd"].sum()
orders = len(filtered)
left, middle, right = st.columns(3)
left.metric("Revenue", f"${revenue:,.0f}")
middle.metric("Orders", f"{orders:,}")
right.metric("Average order", f"${revenue / orders:,.2f}")
PYst.metric shows a label and a large value. Format the value yourself as a string, as here, so the thousands separators and currency symbol are exactly what you want. st.metric also takes a delta argument for a change such as "+4% on last month", which you can add once you have a fair comparison period.
The division is safe because the previous block already stopped the run when no rows matched.
Check it worked
With all regions and dates selected, the three numbers read $1,119,564, 20,333 and $55.06. Select only Lagos and they change to $394,725, 7,201 and $54.82.
Step 6 · Add a weekly chart and a table in tabs
Daily revenue in four regions makes a noisy chart, so total it by week first. pd.Grouper(freq="W-SUN") puts each order in the week that ends on a Sunday, and unstack turns the regions into columns, which is the wide shape st.line_chart draws as one line per column:
cd ~/streamlit-demo
cat >> app.py <<'PY'
weekly = (
filtered.groupby([pd.Grouper(key="date", freq="W-SUN"), "region"])["revenue_usd"]
.sum()
.unstack(fill_value=0)
)
chart_tab, table_tab = st.tabs(["Weekly revenue", "Orders"])
with chart_tab:
st.line_chart(weekly, x_label="Week ending", y_label="Revenue (USD)")
with table_tab:
st.dataframe(
filtered,
hide_index=True,
column_config={
"date": st.column_config.DateColumn("Date"),
"revenue_usd": st.column_config.NumberColumn("Revenue (USD)", format="%.2f"),
},
)
PYst.tabs returns one container per label, and anything you draw inside with chart_tab: appears under that tab. column_config changes how a column is shown without touching the data: the date column shows as a date without a time, and revenue gets a clear heading and two decimals. The first and last weeks are partial (1 January 2026 is a Thursday), so expect them to dip.
Streamlit sends the rows you pass to st.dataframe to the browser. Twenty thousand short rows are fine, but if your team opens the dashboard on phones over prepaid data, a large table costs them data on every filter change. For bigger datasets, show a summary table or the first few hundred rows and leave the full set to the CSV download in the next step.
Check it worked
Under the numbers there are two tabs. Weekly revenue shows four lines, one per region, with Lagos on top, and hovering over a point shows the week and the value. Orders shows a table you can sort by clicking a column heading. Pick March only in the date filter: the chart shrinks to about five weeks and the table to 3,592 rows.
Step 7 · Let people download the filtered rows
People will want the numbers behind the chart in a spreadsheet. st.download_button sends whatever data you give it as a file. Append a block that goes back into the Orders tab, under the table:
cd ~/streamlit-demo
cat >> app.py <<'PY'
with table_tab:
st.download_button(
"Download these orders as CSV",
data=filtered.to_csv(index=False),
file_name=f"sales-{start}-to-{end}.csv",
mime="text/csv",
)
PYYou can enter a container such as a tab more than once; new elements go under what is already there. The file name carries the date range, so two downloads from different periods do not overwrite each other. The CSV is built from filtered, so it holds exactly the rows the filters selected.
Check it worked
The Orders tab has a Download these orders as CSV button under the table. Select only Accra, click it, and your browser saves sales-2026-01-01-to-2026-06-30.csv. Open it: the first line is order_id,date,region,product,units,revenue_usd and every row says Accra.
Step 8 · Test the dashboard without a browser
Clicking through filters is fine once. To keep the dashboard working as you change it, use Streamlit's AppTest. It runs app.py in the test process, lets you set widget values, and gives you the elements the script drew, all without a server or a browser. Create test_app.py:
cd ~/streamlit-demo
cat > test_app.py <<'PY'
from datetime import date
import streamlit as st
from streamlit.testing.v1 import AppTest
def start_app():
at = AppTest.from_file("app.py", default_timeout=30)
at.run()
assert not at.exception
return at
def headline(at):
return [metric.value for metric in at.metric]
def test_headline_numbers_for_all_orders():
at = start_app()
assert [metric.label for metric in at.metric] == ["Revenue", "Orders", "Average order"]
assert headline(at) == ["$1,119,564", "20,333", "$55.06"]
def test_region_filter():
at = start_app()
at.sidebar.multiselect[0].set_value(["Lagos"]).run()
assert headline(at) == ["$394,725", "7,201", "$54.82"]
def test_date_filter():
at = start_app()
at.sidebar.date_input[0].set_value((date(2026, 3, 1), date(2026, 3, 31))).run()
assert headline(at) == ["$202,203", "3,592", "$56.29"]
def test_no_regions_shows_a_warning():
at = start_app()
at.sidebar.multiselect[0].set_value([]).run()
assert at.warning[0].value == "No orders match these filters."
assert len(at.metric) == 0
def test_tabs_and_download_button():
at = start_app()
assert [tab.label for tab in at.tabs] == ["Weekly revenue", "Orders"]
assert at.download_button[0].label == "Download these orders as CSV"
def test_file_is_read_once(capfd):
st.cache_data.clear()
at = start_app()
at.sidebar.multiselect[0].set_value(["Accra"]).run()
at.sidebar.multiselect[0].set_value(["Nairobi"]).run()
assert capfd.readouterr().out.count("Reading sales.parquet") == 1
PY
. .venv/bin/activate
pytest -q test_app.pyA few details make these tests reliable:
AppTest.from_filetakes a path relative to the test file, so keeptest_app.pynext toapp.pyand runpytestfrom the project folder, wheresales.parquetis.at.sidebar.multiselect[0]means the first multiselect in the sidebar.set_value(...)changes it, and.run()reruns the script, exactly as a click in the browser would.default_timeout=30gives each run up to 30 seconds. The first run in a fresh process imports pandas and pyarrow, which can take several seconds on a slow laptop.- The last test clears the cache, drives three runs and counts the
Reading sales.parquetlines thatload_salesprinted. One line proves the cache is doing its job.
Check it worked
pytest prints 6 passed. Change "Average order" to "Mean order" in app.py, run pytest -q test_app.py again, and test_headline_numbers_for_all_orders fails, showing both lists of labels. Change it back and all six pass.
Step 9 · Stop the app and clean up
Stop the server with Ctrl+C in the second terminal. The page in your browser shows that it lost its connection.
If you regenerate sales.parquet while the server is running, the cache keeps serving the old data, because the argument "sales.parquet" has not changed. Restart the server, or give the decorator a lifetime such as @st.cache_data(ttl="1h") so the data is read again after an hour. When you have finished with the project, delete it. This removes the virtual environment and everything you created:
cd ~
rm -rf ~/streamlit-demoCheck it worked
curl -s http://localhost:8501/_stcore/health prints nothing and returns at once, because nothing listens on port 8501 any more, and ls ~/streamlit-demo reports that the folder does not exist.
Next steps
- Design a dashboard people read at a glance covers what to put first, which numbers deserve a metric card and how to label a chart for someone in a hurry.
- Group and aggregate data in pandas goes deeper into the
groupbyandGrouperpatterns behind the weekly chart. - Plot data with matplotlib is the next stop when
st.line_chartis not enough:st.pyplotputs any matplotlib figure on a Streamlit page. - Explore a dataset in JupyterLab is the better tool for the exploring that comes before you know what the dashboard should show.
Related tutorials
- Explore a dataset in JupyterLab without making a messYou will set up JupyterLab 4.6 in a uv project, explore a small price dataset in a notebook that gives the same answer every time it runs top to bottom, and commit it to Git with its outputs stripped.
- Work with dates and time series in pandasYou will turn fifteen months of hourly electricity-meter readings with gaps into clean daily and monthly totals in pandas 3.1, with flagged and filled missing hours, rolling averages, week-on-week and year-on-year comparisons, correct Africa/Lagos and UTC times, and no month-end surprises.
- Validate data with pandera before you analyse itYou will have a pandera 0.36 schema that checks each monthly sales export, writes every problem to a CSV a colleague can fix, and runs in pytest so a broken file stops the report before it starts.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials