Budget vs actual report for Snowflake (Streamlit template)
Spend against budget by department and category, with year-to-date variance, run rate and the lines over budget. 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
Where are we against budget, and which lines will overrun? This template compares actual spend with budget by month, department and category, shows the year-to-date variance and the full-year run rate, and lists the lines more than 5% over budget.
It is for finance business partners and budget owners who track spend every month and want the same view as the controller, without a spreadsheet passed around by email.
What's in it
- Actual, budget and variance year to date, full-year run rate
- Monthly and cumulative budget vs actual
- Variance by department with over/under status
- Lines more than 5% over budget; CSV download
The data it needs
Budget
One row per month, department and category with the budget and the actual (actual empty for future months).
| Column | Type | Also matches columns named |
|---|---|---|
PERIOD | date | month, period_date, fiscal_period, date |
DEPARTMENT | text | cost_center, dept, business_unit, team |
CATEGORY | text | expense_category, account, line_item, cost_type |
BUDGET | number | budget_amount, plan, planned, target, forecast_budget |
ACTUAL | number | actual_amount, actuals, spend, spent, cost |
The query it starts from (BUDGET_SQL):
SELECT PERIOD, DEPARTMENT, CATEGORY, BUDGET, ACTUAL
FROM YOUR_DATABASE.YOUR_SCHEMA.BUDGET_ACTUALS
Using it on your data
Budget and actuals often live in separate tables. Join them in the query on month, department and category; months without actuals yet stay empty and count towards the run rate.
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 151 lines
"""Budget vs actual — spend against budget by department and category, with
variances, year-to-date burn and the lines that need attention."""
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="Budget vs actual", 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
BUDGET_SQL = """
SELECT PERIOD, DEPARTMENT, CATEGORY, BUDGET, ACTUAL
FROM {{DATABASE}}.{{SCHEMA}}.BUDGET_ACTUALS
"""
# ──────────────────────────────────────────────────────────────────────────────
COLORS = px.colors.qualitative.Safe
TOLERANCE = 0.05 # over budget by more than this share → flagged
def demo_budget() -> pd.DataFrame:
rng = np.random.default_rng(5)
year = pd.Timestamp.today().year
months = pd.date_range(f"{year}-01-01", periods=12, freq="MS")
today = pd.Timestamp.today().normalize()
plan = {
"Sales": {"Salaries": 120_000, "Travel": 18_000, "Software": 9_000, "Events": 12_000},
"Marketing": {"Salaries": 70_000, "Campaigns": 55_000, "Software": 14_000, "Events": 20_000},
"R&D": {"Salaries": 210_000, "Cloud": 45_000, "Software": 22_000, "Contractors": 30_000},
"Operations": {"Salaries": 90_000, "Facilities": 40_000, "Software": 8_000, "Logistics": 35_000},
}
rows = []
for m in months:
for dept, cats in plan.items():
for cat, base in cats.items():
budget = base * (1 + 0.1 * np.sin(m.month / 12 * 2 * np.pi)) if cat in ("Events", "Campaigns") else base
drift = {"Cloud": 1.12, "Travel": 1.08, "Contractors": 0.85}.get(cat, 1.0)
actual = budget * drift * rng.uniform(0.9, 1.1) if m <= today else np.nan
rows.append((m, dept, cat, round(budget, 2), None if np.isnan(actual) else round(actual, 2)))
return pd.DataFrame(rows, columns=["PERIOD", "DEPARTMENT", "CATEGORY", "BUDGET", "ACTUAL"])
@st.cache_data(ttl=600, show_spinner=False)
def load_budget() -> pd.DataFrame:
if DEMO:
df = demo_budget()
else:
from snowflake.snowpark.context import get_active_session
df = get_active_session().sql(BUDGET_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()
for c in ("BUDGET", "ACTUAL"):
df[c] = pd.to_numeric(df[c], errors="coerce")
for c in ("DEPARTMENT", "CATEGORY"):
df[c] = df[c].fillna("Unknown").astype(str)
return df.dropna(subset=["PERIOD"])
st.title("Budget vs actual")
if DEMO:
st.caption("Showing generated demo data — connect your own table in the DATA section.")
try:
data = load_budget()
except Exception as e:
st.error(f"Could not load budget data: {e}")
st.stop()
if data.empty:
st.info("No budget rows yet.")
st.stop()
with st.sidebar:
st.header("Filters")
years = sorted(data["PERIOD"].dt.year.unique(), reverse=True)
year = st.selectbox("Year", years)
departments = st.multiselect("Department", sorted(data["DEPARTMENT"].unique()))
year_rows = data[data["PERIOD"].dt.year == year]
if departments:
year_rows = year_rows[year_rows["DEPARTMENT"].isin(departments)]
closed = year_rows[year_rows["ACTUAL"].notna()]
if closed.empty:
st.info("No actuals booked for this year yet.")
st.stop()
last_closed = closed["PERIOD"].max()
ytd = year_rows[year_rows["PERIOD"] <= last_closed]
budget_ytd, actual_ytd = ytd["BUDGET"].sum(), ytd["ACTUAL"].sum()
budget_year = year_rows["BUDGET"].sum()
months_done = ytd["PERIOD"].nunique()
forecast = actual_ytd / months_done * year_rows["PERIOD"].nunique() if months_done else 0
k = st.columns(4)
k[0].metric("Actual YTD", f"{actual_ytd:,.0f}")
k[1].metric("Budget YTD", f"{budget_ytd:,.0f}")
k[2].metric("Variance YTD", f"{actual_ytd - budget_ytd:+,.0f}",
f"{(actual_ytd - budget_ytd) / budget_ytd:+.1%}" if budget_ytd else None, delta_color="inverse")
k[3].metric("Full-year run rate", f"{forecast:,.0f}",
f"{(forecast - budget_year) / budget_year:+.1%} vs budget" if budget_year else None, delta_color="inverse")
st.caption(f"Year to date through {last_closed:%B %Y}; run rate = average month so far × months in the year.")
monthly = year_rows.groupby("PERIOD", as_index=False)[["BUDGET", "ACTUAL"]].sum(min_count=1)
monthly["CUM_BUDGET"] = monthly["BUDGET"].cumsum()
monthly["CUM_ACTUAL"] = monthly["ACTUAL"].cumsum()
left, right = st.columns(2)
fig = go.Figure()
fig.add_bar(x=monthly["PERIOD"], y=monthly["BUDGET"], name="Budget", marker_color="#c7d2e0")
fig.add_bar(x=monthly["PERIOD"], y=monthly["ACTUAL"], name="Actual", marker_color=COLORS[0])
fig.update_layout(title="By month", barmode="group", legend_title_text="", margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")
fig = go.Figure()
fig.add_scatter(x=monthly["PERIOD"], y=monthly["CUM_BUDGET"], name="Budget", line=dict(dash="dash", color="#7f8c9d"))
fig.add_scatter(x=monthly["PERIOD"], y=monthly["CUM_ACTUAL"], name="Actual", line=dict(color=COLORS[0], width=3))
fig.update_layout(title="Cumulative", legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")
lines = ytd.groupby(["DEPARTMENT", "CATEGORY"], as_index=False)[["BUDGET", "ACTUAL"]].sum()
lines["VARIANCE"] = lines["ACTUAL"] - lines["BUDGET"]
lines["VARIANCE_PCT"] = np.where(lines["BUDGET"] != 0, lines["VARIANCE"] / lines["BUDGET"], np.nan)
by_dept = lines.groupby("DEPARTMENT", as_index=False)[["BUDGET", "ACTUAL", "VARIANCE"]].sum()
by_dept["STATUS"] = np.where(by_dept["VARIANCE"] > by_dept["BUDGET"] * TOLERANCE, "Over budget",
np.where(by_dept["VARIANCE"] < 0, "Under budget", "On track"))
fig = px.bar(by_dept.sort_values("VARIANCE"), x="VARIANCE", y="DEPARTMENT", orientation="h", color="STATUS",
color_discrete_map={"Over budget": "#d62728", "On track": "#7f8c9d", "Under budget": "#2ca02c"},
labels={"VARIANCE": "Variance YTD (actual − budget)", "DEPARTMENT": ""}, title="Variance by department")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
st.plotly_chart(fig, width="stretch")
st.subheader("Lines over budget")
over = lines[lines["VARIANCE_PCT"] > TOLERANCE].sort_values("VARIANCE", ascending=False).reset_index(drop=True)
if over.empty:
st.success(f"No line is more than {TOLERANCE:.0%} over its year-to-date budget.")
else:
st.dataframe(over, width="stretch", column_config={
"BUDGET": st.column_config.NumberColumn("Budget YTD", format="localized"),
"ACTUAL": st.column_config.NumberColumn("Actual YTD", format="localized"),
"VARIANCE": st.column_config.NumberColumn("Variance", format="localized"),
"VARIANCE_PCT": st.column_config.NumberColumn("Variance %", format="percent"),
})
with st.expander("All lines"):
st.dataframe(lines.sort_values(["DEPARTMENT", "CATEGORY"]).reset_index(drop=True), width="stretch")
st.download_button("Download CSV", lines.to_csv(index=False), "budget_vs_actual.csv", "text/csv")
Questions
Can the 5% threshold change?
Yes, it is one constant at the top of the app. Ask StreamGen's agent to make it a slider if budget owners want to choose.
Does it handle reforecasts?
Add a version column (budget, forecast 1, forecast 2) and filter on it in the query, or ask the agent to add a version picker.
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
Finance KPIs
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.
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.