Templates › Marketing performance

Marketing performance and ROAS dashboard for Snowflake (Streamlit template)

Spend, conversions, cost per conversion and ROAS by channel and campaign, with the funnel and weekly trends. A Streamlit template for Snowflake.

MarketingStreamlitRuns in Snowflake157 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

Which channels and campaigns pay for themselves? This template puts spend, conversions, cost per conversion, revenue and return on ad spend side by side, by channel and campaign, against the previous period, with the funnel from impressions to conversions.

It is for marketing teams that already load ad platform and analytics data into Snowflake and want one view across all channels instead of one dashboard per platform.

What's in it

  • Spend, conversions, cost per conversion, revenue and ROAS vs the previous period
  • Weekly spend and ROAS by channel
  • Channel efficiency chart and impressions → clicks → conversions funnel
  • Campaign table with CTR, conversion rate, CPA, ROAS; CSV download

The data it needs

Campaigns

One row per day and campaign with spend and results.

ColumnTypeAlso matches columns named
DATEdateday, report_date, activity_date, event_date
CAMPAIGNtextcampaign_name, ad_campaign, initiative
CHANNELtextsource, medium, platform, network, marketing_channel
SPENDnumbercost, ad_spend, amount_spent, media_cost
IMPRESSIONSnumberimps, views, impr
CLICKSnumberlink_clicks, sessions, visits
CONVERSIONSnumberorders, leads, signups, purchases, conv
REVENUEnumberconversion_value, sales, purchase_value, attributed_revenue

The query it starts from (CAMPAIGNS_SQL):

SELECT DATE, CAMPAIGN, CHANNEL, SPEND, IMPRESSIONS, CLICKS, CONVERSIONS, REVENUE
FROM YOUR_DATABASE.YOUR_SCHEMA.CAMPAIGN_DAILY

Using it on your data

Ad platforms name things differently: Google calls it cost, Meta calls it amount spent. Union them in the query into one row per day and campaign with the same columns. Revenue can come from your own orders table rather than the platforms' attributed numbers.

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 157 lines
"""Marketing performance — spend, conversions and return by channel and
campaign, with the funnel and efficiency over time."""

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="Marketing performance", 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
CAMPAIGNS_SQL = """
SELECT DATE, CAMPAIGN, CHANNEL, SPEND, IMPRESSIONS, CLICKS, CONVERSIONS, REVENUE
FROM {{DATABASE}}.{{SCHEMA}}.CAMPAIGN_DAILY
"""
# ──────────────────────────────────────────────────────────────────────────────

COLORS = px.colors.qualitative.Safe


def demo_campaigns() -> pd.DataFrame:
    rng = np.random.default_rng(3)
    days = pd.date_range(end=pd.Timestamp.today().normalize(), periods=180, freq="D")
    channels = {  # cpm, ctr, cvr, order value
        "Paid search": (9, 0.045, 0.06, 140), "Social": (6, 0.012, 0.025, 110),
        "Display": (3, 0.004, 0.015, 120), "Email": (1, 0.03, 0.05, 95), "Affiliate": (4, 0.01, 0.04, 130),
    }
    campaigns = [("Spring launch", "Paid search"), ("Brand search", "Paid search"), ("Retargeting", "Display"),
                 ("Lookalikes", "Social"), ("Creators", "Social"), ("Newsletter", "Email"), ("Partners", "Affiliate")]
    rows = []
    for d in days:
        weekday = 0.8 if d.dayofweek >= 5 else 1.0
        for name, ch in campaigns:
            cpm, ctr, cvr, aov = channels[ch]
            imps = int(rng.uniform(20_000, 90_000) * weekday)
            clicks = rng.binomial(imps, ctr)
            conv = rng.binomial(clicks, cvr)
            rows.append((d, name, ch, round(imps / 1000 * cpm * rng.uniform(0.9, 1.1), 2), imps, clicks, conv,
                         round(conv * aov * rng.uniform(0.8, 1.2), 2)))
    return pd.DataFrame(rows, columns=["DATE", "CAMPAIGN", "CHANNEL", "SPEND", "IMPRESSIONS", "CLICKS", "CONVERSIONS", "REVENUE"])


@st.cache_data(ttl=600, show_spinner=False)
def load_campaigns() -> pd.DataFrame:
    if DEMO:
        df = demo_campaigns()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(CAMPAIGNS_SQL).to_pandas()
        df.columns = [c.upper() for c in df.columns]
    df["DATE"] = pd.to_datetime(df["DATE"], errors="coerce")
    for c in ("SPEND", "IMPRESSIONS", "CLICKS", "CONVERSIONS", "REVENUE"):
        df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0)
    for c in ("CAMPAIGN", "CHANNEL"):
        df[c] = df[c].fillna("Unknown").astype(str)
    return df.dropna(subset=["DATE"])


def efficiency(frame: pd.DataFrame, by: list) -> pd.DataFrame:
    g = frame.groupby(by, as_index=False)[["SPEND", "IMPRESSIONS", "CLICKS", "CONVERSIONS", "REVENUE"]].sum()
    g["CTR"] = g["CLICKS"] / g["IMPRESSIONS"].replace(0, np.nan)
    g["CVR"] = g["CONVERSIONS"] / g["CLICKS"].replace(0, np.nan)
    g["CPA"] = g["SPEND"] / g["CONVERSIONS"].replace(0, np.nan)
    g["ROAS"] = g["REVENUE"] / g["SPEND"].replace(0, np.nan)
    return g


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

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

with st.sidebar:
    st.header("Filters")
    days = st.select_slider("Period", options=[7, 14, 30, 60, 90, 180], value=30, format_func=lambda d: f"Last {d} days")
    channels = st.multiselect("Channel", sorted(data["CHANNEL"].unique()))

end = data["DATE"].max()
scope = data if not channels else data[data["CHANNEL"].isin(channels)]
current = scope[scope["DATE"] > end - pd.Timedelta(days=days)]
previous = scope[(scope["DATE"] <= end - pd.Timedelta(days=days)) & (scope["DATE"] > end - pd.Timedelta(days=2 * days))]
if current.empty:
    st.info("No data for these filters.")
    st.stop()

now, before = efficiency(current.assign(ALL=1), ["ALL"]).iloc[0], efficiency(previous.assign(ALL=1), ["ALL"])
before = before.iloc[0] if not before.empty else None


def change(key):
    if before is None or not before[key] or pd.isna(before[key]):
        return None
    return f"{(now[key] - before[key]) / before[key]:+.1%}"


k = st.columns(5)
k[0].metric("Spend", f"{now['SPEND']:,.0f}", change("SPEND"), delta_color="off")
k[1].metric("Conversions", f"{now['CONVERSIONS']:,.0f}", change("CONVERSIONS"))
k[2].metric("Cost per conversion", f"{now['CPA']:,.2f}", change("CPA"), delta_color="inverse")
k[3].metric("Revenue", f"{now['REVENUE']:,.0f}", change("REVENUE"))
k[4].metric("ROAS", f"{now['ROAS']:.2f}×", change("ROAS"))
st.caption(f"Last {days} days vs the {days} days before.")

weekly = efficiency(current.assign(WEEK=current["DATE"].dt.to_period("W").dt.start_time), ["WEEK", "CHANNEL"])
left, right = st.columns(2)
fig = px.bar(weekly, x="WEEK", y="SPEND", color="CHANNEL", color_discrete_sequence=COLORS,
             labels={"SPEND": "Spend", "WEEK": ""}, title="Spend by week")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")

fig = px.line(weekly, x="WEEK", y="ROAS", color="CHANNEL", markers=True, color_discrete_sequence=COLORS,
              labels={"ROAS": "Return on ad spend", "WEEK": ""}, title="ROAS by week")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")

by_channel = efficiency(current, ["CHANNEL"])
left, right = st.columns(2)
fig = px.scatter(by_channel, x="CPA", y="ROAS", size="SPEND", color="CHANNEL", text="CHANNEL",
                 color_discrete_sequence=COLORS, size_max=50,
                 labels={"CPA": "Cost per conversion", "ROAS": "Return on ad spend"}, title="Channel efficiency")
fig.update_traces(textposition="top center")
fig.update_layout(showlegend=False, margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")

fig = go.Figure(go.Funnel(y=["Impressions", "Clicks", "Conversions"],
                          x=[now["IMPRESSIONS"], now["CLICKS"], now["CONVERSIONS"]],
                          textinfo="value+percent previous", marker={"color": COLORS[:3]}))
fig.update_layout(title="Funnel", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")

st.subheader("Campaigns")
table = efficiency(current, ["CAMPAIGN", "CHANNEL"]).sort_values("SPEND", ascending=False).reset_index(drop=True)
st.dataframe(table, width="stretch", column_config={
    "SPEND": st.column_config.NumberColumn("Spend", format="localized"),
    "REVENUE": st.column_config.NumberColumn("Revenue", format="localized"),
    "IMPRESSIONS": st.column_config.NumberColumn("Impressions", format="compact"),
    "CLICKS": st.column_config.NumberColumn("Clicks", format="localized"),
    "CONVERSIONS": st.column_config.NumberColumn("Conversions", format="localized"),
    "CTR": st.column_config.NumberColumn("CTR", format="percent"),
    "CVR": st.column_config.NumberColumn("Conversion rate", format="percent"),
    "CPA": st.column_config.NumberColumn("Cost / conversion", format="%.2f"),
    "ROAS": st.column_config.ProgressColumn("ROAS", min_value=0, max_value=float(max(table["ROAS"].max(), 1)), format="%.2f"),
})
st.download_button("Download CSV", table.to_csv(index=False), "campaigns.csv", "text/csv")

Questions

Which attribution model does it use?

None of its own. It shows the conversions and revenue your data has; choose the model where the data is prepared.

Can it show daily rather than weekly trends?

Yes. Change the grain in the trend section, or ask StreamGen's agent to add a daily/weekly switch.

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.