Templates › Sales dashboard

Sales dashboard for Snowflake (Streamlit template)

A ready-made Streamlit sales dashboard for Snowflake. Revenue, orders and customers by region, product and channel, with period-over-period change. Try it live.

SalesStreamlitRuns in Snowflake166 lines of Python
Live demo: the real app, running in your browser on generated sample data

Click Run to start the app here.

The first start downloads Python for the browser (about 30 MB) and takes 10–30 seconds.

What it answers

The first dashboard most teams build on Snowflake: how much did we sell, where, and is it more or less than last period? This template answers that from one orders table: revenue, orders, average order value and customers, with the change against the previous period of the same length.

It suits a sales or revenue operations team that already has orders in Snowflake and wants something better than a spreadsheet export, without waiting for a BI project.

What's in it

  • Revenue, orders, average order and customers with change vs the previous period
  • Monthly revenue by category
  • Region and channel breakdown
  • Top products and top customers
  • Date, region and category filters; CSV download

The data it needs

Orders

One row per order (or order line).

ColumnTypeAlso matches columns named
ORDER_DATEdatedate, order_dt, created_at, sale_date, transaction_date, invoice_date
REGIONtextterritory, area, market, country, geo, sales_region
PRODUCTtextproduct_name, item, sku, article
CATEGORYtextproduct_category, product_line, family, segment
CUSTOMERtextcustomer_name, account, client, customer_id, account_name
CHANNELtextsales_channel, source, order_channel
AMOUNTnumberrevenue, sales, net_amount, total, order_total, value, net_sales
QUANTITYnumberqty, units, quantity_ordered, items

The query it starts from (ORDERS_SQL):

SELECT ORDER_DATE, REGION, PRODUCT, CATEGORY, CUSTOMER, CHANNEL, AMOUNT, QUANTITY
FROM YOUR_DATABASE.YOUR_SCHEMA.ORDERS

Using it on your data

Most order tables already have the columns it needs under other names: NET_AMOUNT for AMOUNT, TERRITORY for REGION. If you sell in several currencies, convert in the query first; the dashboard adds amounts as they come.

In StreamGen you don't edit any of this by hand: the agent looks at your tables, matches columns by name and type (including the names above), shows you the mapping, and checks the app on your live data before you deploy it.

Three ways to use it

Try it in StreamGen

Two hours on sample data in a ready-made Snowflake sandbox. No sign-up, nothing to install.

Start the 2-hour try

Install in your Snowflake

StreamGen is a Snowflake Native App: it runs inside your account, and your data stays there.

Open the Marketplace listing

Copy the code

It's a plain Streamlit app. Paste it into Streamlit in Snowflake, set DEMO = False and point the query at your table.

Show the code

The code

All of it, as it runs in the demo above. The data section at the top is the only part that changes for your tables.

Show all 166 lines
"""Sales dashboard — revenue, orders and customers over time, by region,
product and channel."""

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

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

# ── DATA ──────────────────────────────────────────────────────────────────────
# DEMO = True runs on generated sample data. To use your own table, set
# DEMO = False and make the query return these columns (rename with AS).
DEMO = True
ORDERS_SQL = """
SELECT ORDER_DATE, REGION, PRODUCT, CATEGORY, CUSTOMER, CHANNEL, AMOUNT, QUANTITY
FROM {{DATABASE}}.{{SCHEMA}}.ORDERS
"""
# ──────────────────────────────────────────────────────────────────────────────

COLORS = px.colors.qualitative.Safe


def demo_orders() -> pd.DataFrame:
    rng = np.random.default_rng(7)
    n = 6000
    products = {
        "Laptop Pro": ("Hardware", 1800), "Laptop Air": ("Hardware", 1100), "Monitor 27": ("Hardware", 380),
        "Dock": ("Accessories", 220), "Keyboard": ("Accessories", 90), "Headset": ("Accessories", 140),
        "Support Plan": ("Services", 600), "Onboarding": ("Services", 1500),
    }
    names = list(products)
    product = rng.choice(names, n, p=[0.12, 0.16, 0.14, 0.12, 0.16, 0.12, 0.1, 0.08])
    days = pd.Timestamp.today().normalize() - pd.to_timedelta(rng.integers(0, 730, n), unit="D")
    season = 1 + 0.25 * np.sin((days.month.to_numpy() - 3) / 12 * 2 * np.pi)
    qty = rng.integers(1, 6, n)
    price = np.array([products[p][1] for p in product])
    return pd.DataFrame({
        "ORDER_DATE": days,
        "REGION": rng.choice(["EMEA", "North America", "APAC", "LATAM"], n, p=[0.35, 0.4, 0.17, 0.08]),
        "PRODUCT": product,
        "CATEGORY": [products[p][0] for p in product],
        "CUSTOMER": [f"Customer {i:03d}" for i in rng.integers(1, 260, n)],
        "CHANNEL": rng.choice(["Direct", "Partner", "Online"], n, p=[0.45, 0.3, 0.25]),
        "AMOUNT": (price * qty * season * rng.uniform(0.85, 1.1, n)).round(2),
        "QUANTITY": qty,
    })


@st.cache_data(ttl=600, show_spinner=False)
def load_orders() -> pd.DataFrame:
    if DEMO:
        df = demo_orders()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(ORDERS_SQL).to_pandas()
        df.columns = [c.upper() for c in df.columns]
    df["ORDER_DATE"] = pd.to_datetime(df["ORDER_DATE"], errors="coerce")
    for c in ("AMOUNT", "QUANTITY"):
        df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0)
    for c in ("REGION", "PRODUCT", "CATEGORY", "CUSTOMER", "CHANNEL"):
        df[c] = df[c].fillna("Unknown").astype(str)
    return df.dropna(subset=["ORDER_DATE"])


st.title("Sales dashboard")
if DEMO:
    st.caption("Showing generated demo data — connect your own table in the DATA section.")

try:
    orders = load_orders()
except Exception as e:
    st.error(f"Could not load orders: {e}")
    st.stop()
if orders.empty:
    st.info("No orders yet.")
    st.stop()

# ── filters ───────────────────────────────────────────────────────────────────
with st.sidebar:
    st.header("Filters")
    lo, hi = orders["ORDER_DATE"].min().date(), orders["ORDER_DATE"].max().date()
    default_start = max(lo, (pd.Timestamp(hi) - pd.DateOffset(months=12)).date())
    period = st.date_input("Period", (default_start, hi), min_value=lo, max_value=hi)
    regions = st.multiselect("Region", sorted(orders["REGION"].unique()))
    categories = st.multiselect("Category", sorted(orders["CATEGORY"].unique()))

start, end = (period if isinstance(period, tuple) and len(period) == 2 else (lo, hi))
start, end = pd.Timestamp(start), pd.Timestamp(end) + pd.Timedelta(days=1)
mask = pd.Series(True, index=orders.index)
if regions:
    mask &= orders["REGION"].isin(regions)
if categories:
    mask &= orders["CATEGORY"].isin(categories)
scoped = orders[mask]
current = scoped[(scoped["ORDER_DATE"] >= start) & (scoped["ORDER_DATE"] < end)]
previous = scoped[(scoped["ORDER_DATE"] >= start - (end - start)) & (scoped["ORDER_DATE"] < start)]

if current.empty:
    st.info("No orders match the filters.")
    st.stop()


# ── KPIs ──────────────────────────────────────────────────────────────────────
def delta(now, before):
    return f"{(now - before) / before:+.1%}" if before else None


rev, rev_prev = current["AMOUNT"].sum(), previous["AMOUNT"].sum()
n_orders, n_prev = len(current), len(previous)
aov, aov_prev = rev / n_orders, (rev_prev / n_prev if n_prev else 0)
cust, cust_prev = current["CUSTOMER"].nunique(), previous["CUSTOMER"].nunique()

k1, k2, k3, k4 = st.columns(4)
k1.metric("Revenue", f"{rev:,.0f}", delta(rev, rev_prev))
k2.metric("Orders", f"{n_orders:,}", delta(n_orders, n_prev))
k3.metric("Average order", f"{aov:,.0f}", delta(aov, aov_prev))
k4.metric("Customers", f"{cust:,}", delta(cust, cust_prev))
st.caption("Change vs the previous period of the same length.")

# ── charts ────────────────────────────────────────────────────────────────────
monthly = (current.assign(MONTH=current["ORDER_DATE"].dt.to_period("M").dt.to_timestamp())
           .groupby(["MONTH", "CATEGORY"], as_index=False)["AMOUNT"].sum())
fig = px.bar(monthly, x="MONTH", y="AMOUNT", color="CATEGORY", color_discrete_sequence=COLORS,
             labels={"AMOUNT": "Revenue", "MONTH": ""}, title="Revenue by month")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
st.plotly_chart(fig, width="stretch")

left, right = st.columns(2)
by_region = current.groupby("REGION", as_index=False)["AMOUNT"].sum().sort_values("AMOUNT")
fig = px.bar(by_region, x="AMOUNT", y="REGION", orientation="h", color_discrete_sequence=COLORS,
             labels={"AMOUNT": "Revenue", "REGION": ""}, title="Revenue by region")
left.plotly_chart(fig, width="stretch")

by_channel = current.groupby("CHANNEL", as_index=False)["AMOUNT"].sum()
fig = px.pie(by_channel, names="CHANNEL", values="AMOUNT", hole=0.55, color_discrete_sequence=COLORS,
             title="Revenue by channel")
right.plotly_chart(fig, width="stretch")

left, right = st.columns(2)
top_products = (current.groupby("PRODUCT", as_index=False)
                .agg(REVENUE=("AMOUNT", "sum"), UNITS=("QUANTITY", "sum"))
                .sort_values("REVENUE", ascending=False).head(10))
fig = px.bar(top_products.sort_values("REVENUE"), x="REVENUE", y="PRODUCT", orientation="h",
             color_discrete_sequence=COLORS, labels={"REVENUE": "Revenue", "PRODUCT": ""}, title="Top products")
left.plotly_chart(fig, width="stretch")

top_customers = (current.groupby("CUSTOMER", as_index=False)
                 .agg(REVENUE=("AMOUNT", "sum"), ORDERS=("AMOUNT", "size"), LAST_ORDER=("ORDER_DATE", "max"))
                 .sort_values("REVENUE", ascending=False).head(15).reset_index(drop=True))
right.subheader("Top customers")
right.dataframe(
    top_customers,
    width="stretch",
    column_config={
        "REVENUE": st.column_config.NumberColumn("Revenue", format="localized"),
        "ORDERS": st.column_config.NumberColumn("Orders"),
        "LAST_ORDER": st.column_config.DateColumn("Last order"),
        "CUSTOMER": "Customer",
    },
)

with st.expander("Orders in the period"):
    st.dataframe(current.sort_values("ORDER_DATE", ascending=False).head(1000).reset_index(drop=True), width="stretch")
    st.download_button("Download CSV", current.to_csv(index=False), "orders.csv", "text/csv")

Questions

Can it show order lines rather than orders?

Yes. One row per order line works; the order count then counts lines. Add a distinct order ID column if you want both.

How far back does it look?

The period filter starts at the last 12 months and goes back as far as the table does. For very large tables, limit the query (for example to the last 24 months) so the app stays fast and cheap.

Can I use the code without StreamGen?

Yes. It is a plain Streamlit app. In Snowsight, create a Streamlit app, paste the code, add plotly to its packages, set DEMO = False and point the query at your table. StreamGen does that mapping, the checks and the deploy for you, and keeps the app working afterwards.

Does my data leave Snowflake?

No. In Snowflake the app runs inside your account and queries your tables there. The live demo on this page runs in your browser on generated sample data; nothing is sent anywhere.

Warehouse or container runtime?

Both work. The template only needs pandas, numpy and plotly, which both Streamlit in Snowflake runtimes provide.

Related templates

All templates · Guides

Build it on your own Snowflake data

In StreamGen you pick this template, the agent matches it to your tables, checks it, and deploys it to Snowflake with roles, approvals and an audit trail. Then ask for changes in plain words.

No sign-up for the 2-hour try. The Native App is free to install, with a free 7-day trial key.