A Streamlit KPI dashboard needs four pieces: filters at the top, a row of st.metric cards that compare the current period with the previous one, a couple of charts in st.columns, and a detail table with st.dataframe. This post builds all of it for a small chain of bike shops, using simulated data and Streamlit 1.67.
Quick Example
Save this as app.py and run streamlit run app.py.
import altair as alt
import numpy as np
import pandas as pd
import streamlit as st
st.set_page_config(page_title="Bike Shop KPIs", layout="wide")
STORES = ["Harbor", "Old Town", "Uptown"]
CATEGORIES = {"Bikes": "#0b7285", "Service": "#f59f00", "Accessories": "#ae3ec9"}
@st.cache_data
def load_sales() -> pd.DataFrame:
rng = np.random.default_rng(34)
days = pd.date_range("2025-07-01", "2026-06-30", freq="D")
base = {"Bikes": (5, 640), "Service": (11, 75), "Accessories": (16, 32)}
size = {"Harbor": 1.3, "Old Town": 1.0, "Uptown": 0.7}
rows = []
for store in STORES:
for category, (orders, price) in base.items():
season = 1 - 0.35 * np.cos(2 * np.pi * (days.dayofyear - 15) / 365)
weekend = np.where(days.dayofweek >= 5, 1.4, 1.0)
growth = np.linspace(1.0, 1.25 if store == "Uptown" else 1.08, len(days))
n = rng.poisson(orders * size[store] * season * weekend * growth)
revenue = (n * price * rng.normal(1, 0.08, len(days))).round(2)
returns = rng.binomial(n, 0.04)
rows.append(pd.DataFrame({
"day": days, "store": store, "category": category,
"orders": n, "revenue": revenue, "returns": returns,
}))
return pd.concat(rows, ignore_index=True)
sales = load_sales()
st.title("Bike Shop KPIs")
left, right = st.columns([1, 2])
period = left.segmented_control("Period", [30, 90, 180], default=90, required=True,
format_func=lambda d: f"{d} days")
stores = right.pills("Stores", STORES, selection_mode="multi", default=STORES)
if not stores:
st.info("Select at least one store.")
st.stop()
end = sales["day"].max()
start = end - pd.Timedelta(days=period - 1)
selected = sales[sales["store"].isin(stores)]
current = selected[selected["day"] >= start]
previous = selected[selected["day"].between(start - pd.Timedelta(days=period),
start - pd.Timedelta(days=1))]
def kpis(df: pd.DataFrame) -> dict:
revenue, orders = df["revenue"].sum(), df["orders"].sum()
return {"Revenue": revenue, "Orders": orders,
"Average order": revenue / orders,
"Return rate": df["returns"].sum() / orders}
now, before = kpis(current), kpis(previous)
# Seven-day buckets counted back from the last date, whole weeks only
age = (end - current["day"]).dt.days
full = current[age < period // 7 * 7]
week_end = (end - pd.to_timedelta(age // 7 * 7, unit="D")).rename("week")
weekly = full.groupby(week_end.loc[full.index])[["revenue", "orders", "returns"]].sum()
sparklines = {
"Revenue": weekly["revenue"],
"Orders": weekly["orders"],
"Average order": weekly["revenue"] / weekly["orders"],
"Return rate": weekly["returns"] / weekly["orders"],
}
formats = {"Revenue": "${:,.0f}", "Orders": "{:,.0f}",
"Average order": "${:,.2f}", "Return rate": "{:.1%}"}
for column, name in zip(st.columns(4), formats):
if name == "Return rate": # a change in percentage points
delta = f"{(now[name] - before[name]) * 100:+.2f} pts"
else:
delta = f"{now[name] / before[name] - 1:+.1%}"
column.metric(
name, formats[name].format(now[name]), delta,
delta_color="inverse" if name == "Return rate" else "normal",
chart_data=sparklines[name].tolist(), chart_type="area", border=True,
)
st.caption(f"{start:%b %-d} to {end:%b %-d, %Y}, compared with the {period} days before.")
trend_col, store_col = st.columns([2, 1])
colors = alt.Scale(domain=list(CATEGORIES), range=list(CATEGORIES.values()))
with trend_col.container(border=True):
st.subheader("Weekly revenue by category")
by_week = (full.groupby([week_end.loc[full.index], "category"])["revenue"]
.sum().reset_index())
trend = alt.Chart(by_week).mark_area().encode(
x=alt.X("week:T", title=None),
y=alt.Y("revenue:Q", title=None, axis=alt.Axis(format="$~s")),
color=alt.Color("category:N", scale=colors,
legend=alt.Legend(orient="top", title=None)),
tooltip=["week:T", "category:N", alt.Tooltip("revenue:Q", format="$,.0f")],
).properties(height=300)
st.altair_chart(trend, width="stretch")
with store_col.container(border=True):
st.subheader("Revenue by store")
by_store = current.groupby(["store", "category"])["revenue"].sum().reset_index()
bars = alt.Chart(by_store).mark_bar().encode(
x=alt.X("revenue:Q", title=None, axis=alt.Axis(format="$~s", tickCount=3)),
y=alt.Y("store:N", title=None, sort="-x"),
color=alt.Color("category:N", scale=colors, legend=None),
tooltip=["store:N", "category:N", alt.Tooltip("revenue:Q", format="$,.0f")],
).properties(height=345)
st.altair_chart(bars, width="stretch")
st.subheader("Store detail")
table = current.groupby("store")[["revenue", "orders", "returns"]].sum()
prior = previous.groupby("store")["revenue"].sum()
table["change"] = (table["revenue"] / prior - 1) * 100
table["share"] = table["revenue"] / table["revenue"].sum()
st.dataframe(
table.sort_values("revenue", ascending=False),
column_config={
"store": "Store",
"revenue": st.column_config.NumberColumn("Revenue", format="dollar"),
"orders": st.column_config.NumberColumn("Orders", format="localized"),
"returns": "Returns",
"change": st.column_config.NumberColumn("vs previous", format="%+.1f%%"),
"share": st.column_config.ProgressColumn("Share of revenue", format="percent",
min_value=0, max_value=1),
},
)

For the 90 days to June 30, revenue is $1,771,492, up 63.5% on the 90 days before, and orders are up 65.8%. The average order slipped 1.4%. Harbor brings in the most, 43% of revenue.
KPI Cards With st.metric
Each card is one st.metric call:
st.metric("Support tickets", 128, "-12%", delta_color="inverse",
chart_data=[170, 162, 150, 155, 141, 128], chart_type="line", border=True)
deltasets the arrow. A string that starts with-points down.delta_color="inverse"makes a drop green, which is what you want for returns, tickets, or churn.chart_datatakes a list of numbers and draws a sparkline in the card.chart_typecan be"line","area", or"bar".border=Truedraws the card outline.
Compare periods of equal length. Equal length doesn't remove seasonality, though. Most of the 90-day jump here is spring against winter, since the simulated demand bottoms out in January. To separate growth from season, compare with the same dates a year earlier, which needs at least two years of data.
The sparklines and the area chart use seven-day buckets counted back from the latest date, and skip the leftover days at the start of the period. Without that, a half-filled week shows up as a fake dip.
Lay Out the Dashboard With Columns and Containers
st.set_page_config(layout="wide") gives the dashboard the full window. st.columns splits a row, and a list such as [2, 1] sets relative widths. container(border=True) groups a heading and its chart into a panel.
Columns stack vertically on narrow screens, so the same code works on a phone.
Filters: segmented_control and pills
For a handful of options, st.segmented_control and st.pills show every choice without opening a menu. required=True stops the user from deselecting the period, which would return None. Multi-select pills can still be emptied, so the app calls st.stop() with a message in that case. For long lists, use st.multiselect in the sidebar.
Which Chart Calls Should a Dashboard Use?
The dashboard uses Altair because both charts need a shared color mapping, formatted dollar axes, and custom tooltips. Built-in calls like st.area_chart are shorter and fine when the defaults will do. The Streamlit chart comparison covers the trade-offs.
Practical Tips
- Cache the load, filter afterwards.
load_sales()is wrapped in@st.cache_data, so changing a filter only redoes the fast pandas work. - Show the date range under the cards. A delta means little if readers don't know what it compares.
- Guard against empty data. Real filters can produce zero orders, which breaks ratios like the average order value.
- Refresh live data with
@st.cache_data(ttl="10m")on the loader, plus@st.fragment(run_every="10m")around the part that should redraw on its own. %-ddrops the leading zero from the day on macOS and Linux. On Windows, use%#d.