Finance KPI and P&L dashboard for Snowflake (Streamlit template)
Revenue, gross margin, operating expenses and operating profit by month, with a P&L bridge and year-over-year change. A Streamlit template for Snowflake.
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 monthly management pack, as an app: revenue, gross margin, operating expenses and operating profit, for the month, year to date or the last twelve months, each compared with the same period last year. A P&L bridge shows what moved profit, and operating expenses break down by department.
It is for finance teams whose general ledger already lands in Snowflake, from an ERP export or a data pipeline, and who rebuild the same slides every month.
What's in it
- Revenue, gross margin, opex, operating profit and margin for month, YTD or last 12 months
- Change vs the same period last year
- Revenue vs operating profit and margin trends
- P&L bridge (waterfall) and opex by department
- Monthly P&L table
The data it needs
Ledger
Monthly ledger totals, one row per period, account and department. ACCOUNT_GROUP is Revenue, Cost of sales or Operating expenses; amounts positive.
| Column | Type | Also matches columns named |
|---|---|---|
PERIOD | date | month, period_date, fiscal_period, posting_month, date |
ACCOUNT_GROUP | text | account_type, pl_group, category, line_item_group, account_class |
ACCOUNT | text | account_name, gl_account, line_item, account_description |
DEPARTMENT | text | cost_center, dept, business_unit, function |
AMOUNT | number | value, amount_usd, net_amount, balance, actual |
The query it starts from (LEDGER_SQL):
SELECT PERIOD, ACCOUNT_GROUP, ACCOUNT, DEPARTMENT, AMOUNT
FROM YOUR_DATABASE.YOUR_SCHEMA.GL_MONTHLY
Using it on your data
It expects monthly totals per account, grouped into Revenue, Cost of sales and Operating expenses, with positive amounts. If your ledger stores debits and credits with signs, flip them in the query; if your account groups are named differently, map them with a CASE expression.
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 tryInstall in your Snowflake
StreamGen is a Snowflake Native App: it runs inside your account, and your data stays there.
Open the Marketplace listingCopy the code
It's a plain Streamlit app. Paste it into Streamlit in Snowflake, set DEMO = False and point the query at your table.
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 177 lines
"""Finance KPIs — revenue, gross margin, operating expenses and operating
profit by month, with a P&L bridge and the monthly P&L table."""
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import streamlit as st
st.set_page_config(page_title="Finance KPIs", 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).
# ACCOUNT_GROUP must be one of: Revenue, Cost of sales, Operating expenses.
# AMOUNT is positive for revenue and for costs.
DEMO = True
LEDGER_SQL = """
SELECT PERIOD, ACCOUNT_GROUP, ACCOUNT, DEPARTMENT, AMOUNT
FROM {{DATABASE}}.{{SCHEMA}}.GL_MONTHLY
"""
# ──────────────────────────────────────────────────────────────────────────────
COLORS = px.colors.qualitative.Safe
GROUPS = ["Revenue", "Cost of sales", "Operating expenses"]
def demo_ledger() -> pd.DataFrame:
rng = np.random.default_rng(11)
months = pd.date_range(end=pd.Timestamp.today().normalize().replace(day=1), periods=24, freq="MS")
rows = []
for i, m in enumerate(months):
growth = 1 + 0.015 * i
season = 1 + 0.12 * np.sin((m.month - 2) / 12 * 2 * np.pi)
for account, base in (("Product sales", 820_000), ("Subscriptions", 310_000), ("Services", 140_000)):
rows.append((m, "Revenue", account, "Sales", base * growth * season * rng.uniform(0.95, 1.05)))
for account, share in (("Materials", 0.28), ("Hosting", 0.06), ("Delivery staff", 0.07)):
rows.append((m, "Cost of sales", account, "Operations", 1_270_000 * growth * season * share * rng.uniform(0.95, 1.07)))
for dept, base in (("Sales", 150_000), ("Marketing", 95_000), ("R&D", 180_000), ("G&A", 85_000)):
for account, share in (("Salaries", 0.7), ("Software", 0.12), ("Travel", 0.08), ("Other", 0.1)):
rows.append((m, "Operating expenses", account, dept, base * (1 + 0.008 * i) * share * rng.uniform(0.9, 1.1)))
df = pd.DataFrame(rows, columns=["PERIOD", "ACCOUNT_GROUP", "ACCOUNT", "DEPARTMENT", "AMOUNT"])
df["AMOUNT"] = df["AMOUNT"].round(2)
return df
@st.cache_data(ttl=600, show_spinner=False)
def load_ledger() -> pd.DataFrame:
if DEMO:
df = demo_ledger()
else:
from snowflake.snowpark.context import get_active_session
df = get_active_session().sql(LEDGER_SQL).to_pandas()
df.columns = [c.upper() for c in df.columns]
df["PERIOD"] = pd.to_datetime(df["PERIOD"], errors="coerce").dt.to_period("M").dt.to_timestamp()
df["AMOUNT"] = pd.to_numeric(df["AMOUNT"], errors="coerce").fillna(0)
for c in ("ACCOUNT_GROUP", "ACCOUNT", "DEPARTMENT"):
df[c] = df[c].fillna("Unknown").astype(str)
return df.dropna(subset=["PERIOD"])
def pnl(df: pd.DataFrame) -> pd.DataFrame:
"""One row per month: revenue, cost of sales, gross profit, opex, operating profit, margins."""
p = df.pivot_table(index="PERIOD", columns="ACCOUNT_GROUP", values="AMOUNT", aggfunc="sum", fill_value=0)
for g in GROUPS:
if g not in p:
p[g] = 0.0
out = pd.DataFrame(index=p.index)
out["REVENUE"] = p["Revenue"]
out["COST_OF_SALES"] = p["Cost of sales"]
out["GROSS_PROFIT"] = out["REVENUE"] - out["COST_OF_SALES"]
out["OPEX"] = p["Operating expenses"]
out["OPERATING_PROFIT"] = out["GROSS_PROFIT"] - out["OPEX"]
rev = out["REVENUE"].replace(0, np.nan)
out["GROSS_MARGIN"] = out["GROSS_PROFIT"] / rev
out["OPERATING_MARGIN"] = out["OPERATING_PROFIT"] / rev
return out.reset_index()
st.title("Finance KPIs")
if DEMO:
st.caption("Showing generated demo data — connect your own ledger in the DATA section.")
try:
ledger = load_ledger()
except Exception as e:
st.error(f"Could not load the ledger: {e}")
st.stop()
if ledger.empty:
st.info("No ledger rows yet.")
st.stop()
months = sorted(ledger["PERIOD"].unique())
with st.sidebar:
st.header("Filters")
last = st.select_slider("Month", options=months, value=months[-1], format_func=lambda m: pd.Timestamp(m).strftime("%b %Y"))
view = st.radio("KPIs for", ["Month", "Year to date", "Last 12 months"], index=1)
monthly = pnl(ledger)
last = pd.Timestamp(last)
if view == "Month":
window = monthly[monthly["PERIOD"] == last]
prior = monthly[monthly["PERIOD"] == last - pd.DateOffset(years=1)]
elif view == "Year to date":
window = monthly[(monthly["PERIOD"].dt.year == last.year) & (monthly["PERIOD"] <= last)]
py = last - pd.DateOffset(years=1)
prior = monthly[(monthly["PERIOD"].dt.year == py.year) & (monthly["PERIOD"] <= py)]
else:
window = monthly[(monthly["PERIOD"] > last - pd.DateOffset(months=12)) & (monthly["PERIOD"] <= last)]
prior = monthly[(monthly["PERIOD"] > last - pd.DateOffset(months=24)) & (monthly["PERIOD"] <= last - pd.DateOffset(months=12))]
def totals(frame: pd.DataFrame) -> dict:
s = frame[["REVENUE", "COST_OF_SALES", "GROSS_PROFIT", "OPEX", "OPERATING_PROFIT"]].sum()
s["GROSS_MARGIN"] = s["GROSS_PROFIT"] / s["REVENUE"] if s["REVENUE"] else 0
s["OPERATING_MARGIN"] = s["OPERATING_PROFIT"] / s["REVENUE"] if s["REVENUE"] else 0
return s.to_dict()
now, before = totals(window), totals(prior)
def change(key, pct=False):
if not before.get("REVENUE"):
return None
if pct:
return f"{(now[key] - before[key]) * 100:+.1f} pts"
return f"{(now[key] - before[key]) / abs(before[key]):+.1%}" if before[key] else None
k = st.columns(5)
k[0].metric("Revenue", f"{now['REVENUE']:,.0f}", change("REVENUE"))
k[1].metric("Gross margin", f"{now['GROSS_MARGIN']:.1%}", change("GROSS_MARGIN", pct=True))
k[2].metric("Operating expenses", f"{now['OPEX']:,.0f}", change("OPEX"), delta_color="inverse")
k[3].metric("Operating profit", f"{now['OPERATING_PROFIT']:,.0f}", change("OPERATING_PROFIT"))
k[4].metric("Operating margin", f"{now['OPERATING_MARGIN']:.1%}", change("OPERATING_MARGIN", pct=True))
st.caption(f"{view} to {last:%b %Y}, change vs the same period a year earlier.")
trend = monthly[monthly["PERIOD"] <= last].tail(24)
left, right = st.columns(2)
fig = go.Figure()
fig.add_bar(x=trend["PERIOD"], y=trend["REVENUE"], name="Revenue", marker_color=COLORS[0])
fig.add_bar(x=trend["PERIOD"], y=trend["OPERATING_PROFIT"], name="Operating profit", marker_color=COLORS[1])
fig.update_layout(title="Revenue and operating profit", barmode="group", legend_title_text="", margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")
margins = trend.melt(id_vars="PERIOD", value_vars=["GROSS_MARGIN", "OPERATING_MARGIN"], var_name="MARGIN", value_name="VALUE")
margins["MARGIN"] = margins["MARGIN"].map({"GROSS_MARGIN": "Gross margin", "OPERATING_MARGIN": "Operating margin"})
fig = px.line(margins, x="PERIOD", y="VALUE", color="MARGIN", markers=True, color_discrete_sequence=COLORS,
labels={"VALUE": "", "PERIOD": ""}, title="Margins")
fig.update_layout(yaxis_tickformat=".0%", legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")
left, right = st.columns(2)
fig = go.Figure(go.Waterfall(
x=["Revenue", "Cost of sales", "Gross profit", "Operating expenses", "Operating profit"],
measure=["absolute", "relative", "total", "relative", "total"],
y=[now["REVENUE"], -now["COST_OF_SALES"], 0, -now["OPEX"], 0],
connector={"line": {"color": "#999"}},
))
fig.update_layout(title=f"P&L bridge — {view.lower()}", margin=dict(t=50, b=10), showlegend=False)
left.plotly_chart(fig, width="stretch")
scope = ledger[(ledger["ACCOUNT_GROUP"] == "Operating expenses") & ledger["PERIOD"].isin(window["PERIOD"])]
opex = scope.groupby(["DEPARTMENT", "ACCOUNT"], as_index=False)["AMOUNT"].sum()
fig = px.bar(opex, x="DEPARTMENT", y="AMOUNT", color="ACCOUNT", color_discrete_sequence=COLORS,
labels={"AMOUNT": "Operating expenses", "DEPARTMENT": ""}, title="Operating expenses by department")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")
st.subheader("Monthly P&L")
table = trend.tail(12).set_index("PERIOD")[["REVENUE", "COST_OF_SALES", "GROSS_PROFIT", "OPEX", "OPERATING_PROFIT", "OPERATING_MARGIN"]]
table.index = table.index.strftime("%b %Y")
table = table.T
table.index = ["Revenue", "Cost of sales", "Gross profit", "Operating expenses", "Operating profit", "Operating margin"]
st.dataframe(table.apply(lambda col: col.map(lambda v: f"{v:.1%}" if abs(v) < 1.5 else f"{v:,.0f}")), width="stretch")
Questions
Does it work with a chart of accounts that has more levels?
Yes. Map each account to one of the three groups in the query; the account and department columns keep the detail for the tables.
Can people only see their own department?
In Snowflake, a row access policy on the ledger table does that for every app and query, including this one.
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
Budget vs actual
Spend against budget by department and category, with year-to-date variance, run rate and the lines over budget. A Streamlit template for Snowflake.
Sales dashboard
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.
Marketing performance
Spend, conversions, cost per conversion and ROAS by channel and campaign, with the funnel and weekly trends. A Streamlit template for Snowflake.
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.