People analytics and HR dashboard for Snowflake (Streamlit template)
Headcount, hires and leavers, attrition, tenure and pay bands by department and location. A Streamlit HR analytics 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
Headcount, hires, leavers and attrition, by department and location, with tenure and pay bands by level. Small groups are protected: pay is hidden for any group under five people, so nobody can work out a colleague's salary.
It is for HR and people analytics teams whose HRIS data is in Snowflake and who answer the same headcount questions every week.
What's in it
- Headcount (with change vs a year ago), hires, leavers and 12-month attrition
- Headcount trend and monthly hires vs leavers
- Headcount by department and tenure distribution
- Pay bands by level, hidden for groups under 5 people
The data it needs
Employees
One row per employee (current and former); TERMINATION_DATE empty for current employees.
| Column | Type | Also matches columns named |
|---|---|---|
EMPLOYEE_ID | text | emp_id, worker_id, person_id, id, employee_number |
DEPARTMENT | text | dept, team, org_unit, business_unit, function |
LOCATION | text | office, site, country, city, work_location |
JOB_LEVEL | text | level, grade, band, job_grade, seniority |
HIRE_DATE | date | start_date, joined_on, date_of_joining, employment_start |
TERMINATION_DATE | date | end_date, exit_date, leave_date, termination_dt, left_on |
SALARY | number | base_salary, annual_salary, pay, compensation, base_pay |
The query it starts from (EMPLOYEES_SQL):
SELECT EMPLOYEE_ID, DEPARTMENT, LOCATION, JOB_LEVEL, HIRE_DATE, TERMINATION_DATE, SALARY
FROM YOUR_DATABASE.YOUR_SCHEMA.EMPLOYEES
Using it on your data
It needs one row per employee, current and former, with hire and termination dates. If your HRIS keeps history as snapshots, take the latest row per employee in the query.
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 154 lines
"""People analytics — headcount, hires and leavers, attrition, tenure and pay
bands by department and location."""
import numpy as np
import pandas as pd
import plotly.express as px
import streamlit as st
st.set_page_config(page_title="People analytics", 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).
# One row per employee; TERMINATION_DATE is empty for current employees.
DEMO = True
EMPLOYEES_SQL = """
SELECT EMPLOYEE_ID, DEPARTMENT, LOCATION, JOB_LEVEL, HIRE_DATE, TERMINATION_DATE, SALARY
FROM {{DATABASE}}.{{SCHEMA}}.EMPLOYEES
"""
# ──────────────────────────────────────────────────────────────────────────────
COLORS = px.colors.qualitative.Safe
MIN_GROUP = 5 # don't show pay for groups smaller than this (privacy)
def demo_employees() -> pd.DataFrame:
rng = np.random.default_rng(17)
today = pd.Timestamp.today().normalize()
depts = {"Engineering": 0.34, "Sales": 0.22, "Customer Success": 0.14, "Marketing": 0.1, "Finance": 0.08, "People": 0.06, "Operations": 0.06}
levels = {"L1": 52_000, "L2": 64_000, "L3": 80_000, "L4": 102_000, "L5": 130_000, "L6": 165_000}
n = 900
hire = today - pd.to_timedelta((rng.beta(1.2, 2.5, n) * 365 * 8).astype(int), unit="D")
tenure_cap = (today - hire).days.to_numpy()
leaves = rng.random(n) < 0.32
term = pd.Series(pd.NaT, index=range(n), dtype="datetime64[ns]")
stay = (rng.gamma(2.0, 400, n)).astype(int)
for i in np.where(leaves & (stay < tenure_cap))[0]:
term[i] = hire[i] + pd.Timedelta(days=int(stay[i]))
level = rng.choice(list(levels), n, p=[0.18, 0.26, 0.24, 0.17, 0.1, 0.05])
dept = rng.choice(list(depts), n, p=list(depts.values()))
pay = np.array([levels[lv] for lv in level]) * np.where(dept == "Engineering", 1.12, 1.0) * rng.uniform(0.9, 1.12, n)
return pd.DataFrame({
"EMPLOYEE_ID": [f"E{i:05d}" for i in range(1, n + 1)],
"DEPARTMENT": dept,
"LOCATION": rng.choice(["Berlin", "London", "New York", "Remote"], n, p=[0.35, 0.25, 0.25, 0.15]),
"JOB_LEVEL": level,
"HIRE_DATE": hire,
"TERMINATION_DATE": term.to_numpy(),
"SALARY": pay.round(-2),
})
@st.cache_data(ttl=600, show_spinner=False)
def load_employees() -> pd.DataFrame:
if DEMO:
df = demo_employees()
else:
from snowflake.snowpark.context import get_active_session
df = get_active_session().sql(EMPLOYEES_SQL).to_pandas()
df.columns = [c.upper() for c in df.columns]
for c in ("HIRE_DATE", "TERMINATION_DATE"):
df[c] = pd.to_datetime(df[c], errors="coerce")
df["SALARY"] = pd.to_numeric(df["SALARY"], errors="coerce")
for c in ("EMPLOYEE_ID", "DEPARTMENT", "LOCATION", "JOB_LEVEL"):
df[c] = df[c].fillna("Unknown").astype(str)
return df.dropna(subset=["HIRE_DATE"])
def headcount_on(df: pd.DataFrame, day: pd.Timestamp) -> pd.Series:
return (df["HIRE_DATE"] <= day) & (df["TERMINATION_DATE"].isna() | (df["TERMINATION_DATE"] > day))
st.title("People analytics")
if DEMO:
st.caption("Showing generated demo data — connect your own table in the DATA section.")
try:
people = load_employees()
except Exception as e:
st.error(f"Could not load employees: {e}")
st.stop()
if people.empty:
st.info("No employees yet.")
st.stop()
with st.sidebar:
st.header("Filters")
departments = st.multiselect("Department", sorted(people["DEPARTMENT"].unique()))
locations = st.multiselect("Location", sorted(people["LOCATION"].unique()))
view = people
if departments:
view = view[view["DEPARTMENT"].isin(departments)]
if locations:
view = view[view["LOCATION"].isin(locations)]
today = pd.Timestamp.today().normalize()
year_ago = today - pd.DateOffset(years=1)
active = view[headcount_on(view, today)]
hires = view[view["HIRE_DATE"] > year_ago]
leavers = view[view["TERMINATION_DATE"] > year_ago]
avg_headcount = (headcount_on(view, today).sum() + headcount_on(view, year_ago).sum()) / 2
attrition = len(leavers) / avg_headcount if avg_headcount else 0
tenure_years = (today - active["HIRE_DATE"]).dt.days / 365.25
k = st.columns(4)
k[0].metric("Headcount", f"{len(active):,}", f"{len(active) - headcount_on(view, year_ago).sum():+,} vs a year ago")
k[1].metric("Hires (12 months)", f"{len(hires):,}")
k[2].metric("Leavers (12 months)", f"{len(leavers):,}")
k[3].metric("Attrition (12 months)", f"{attrition:.1%}")
months = pd.date_range(end=today, periods=24, freq="MS")
trend = pd.DataFrame({
"MONTH": months,
"HEADCOUNT": [headcount_on(view, m).sum() for m in months],
"HIRES": [((view["HIRE_DATE"] >= m) & (view["HIRE_DATE"] < m + pd.offsets.MonthBegin())).sum() for m in months],
"LEAVERS": [((view["TERMINATION_DATE"] >= m) & (view["TERMINATION_DATE"] < m + pd.offsets.MonthBegin())).sum() for m in months],
})
left, right = st.columns(2)
fig = px.area(trend, x="MONTH", y="HEADCOUNT", color_discrete_sequence=COLORS, labels={"MONTH": "", "HEADCOUNT": "Headcount"},
title="Headcount")
left.plotly_chart(fig, width="stretch")
flows = trend.melt(id_vars="MONTH", value_vars=["HIRES", "LEAVERS"], var_name="KIND", value_name="PEOPLE")
flows["KIND"] = flows["KIND"].str.capitalize()
fig = px.bar(flows, x="MONTH", y="PEOPLE", color="KIND", barmode="group",
color_discrete_map={"Hires": COLORS[0], "Leavers": "#d62728"},
labels={"MONTH": "", "PEOPLE": "People"}, title="Hires and leavers")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")
left, right = st.columns(2)
by_dept = active.groupby("DEPARTMENT", as_index=False).size().sort_values("size")
fig = px.bar(by_dept, x="size", y="DEPARTMENT", orientation="h", color_discrete_sequence=COLORS,
labels={"size": "Headcount", "DEPARTMENT": ""}, title="Headcount by department")
left.plotly_chart(fig, width="stretch")
fig = px.histogram(tenure_years, nbins=16, color_discrete_sequence=COLORS, labels={"value": "Tenure (years)"},
title="Tenure of current employees")
fig.update_layout(showlegend=False, yaxis_title="People", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")
st.subheader("Pay bands")
bands = active.groupby("JOB_LEVEL")["SALARY"].agg(PEOPLE="size", P25=lambda s: s.quantile(0.25), MEDIAN="median",
P75=lambda s: s.quantile(0.75)).reset_index()
hidden = bands["PEOPLE"] < MIN_GROUP
bands.loc[hidden, ["P25", "MEDIAN", "P75"]] = np.nan
st.dataframe(bands, width="stretch", column_config={
"JOB_LEVEL": "Level", "PEOPLE": "People",
"P25": st.column_config.NumberColumn("25th pct", format="localized"),
"MEDIAN": st.column_config.NumberColumn("Median", format="localized"),
"P75": st.column_config.NumberColumn("75th pct", format="localized"),
})
if hidden.any():
st.caption(f"Pay is hidden for groups with fewer than {MIN_GROUP} people.")
Questions
Who can see salaries?
Whoever can open the app sees the pay bands it shows. Restrict the app to HR roles in Snowflake, or mask the salary column with a masking policy for everyone else.
Can it show attrition by manager?
Add a manager column and ask StreamGen's agent; keep the small-group rule so individual exits stay private.
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
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.
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.
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.
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.