Forecasting app for Snowflake (trend, seasonality, accuracy)
Project a metric forward with trend and seasonality, a 90% range, backtest accuracy and unusual periods flagged. 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 is this number heading? This template forecasts any daily metric (sales, tickets, sign-ups, usage) by week or month, with a 90% range, by segment. It also shows how accurate the method has been recently, by testing it on periods it didn't see, and flags unusual periods.
It is for analysts who need a credible forecast in an afternoon, and want to show how far it can be trusted.
What's in it
- Weekly or monthly forecast with a 90% range, by segment
- Recent accuracy from a backtest on held-out periods
- Unusual periods flagged against the model
- Forecast table; notes on SNOWFLAKE.ML.FORECAST for production
The data it needs
Series
One row per date (and optional segment) with the numeric value to forecast — daily or finer; the app aggregates to week or month.
| Column | Type | Also matches columns named |
|---|---|---|
DATE | date | day, order_date, ds, timestamp, period, event_date |
SEGMENT (optional) | text | region, channel, store, product, category, series |
VALUE | number | orders, sales, revenue, quantity, units, count, y, amount |
The query it starts from (SERIES_SQL):
SELECT DATE, SEGMENT, VALUE
FROM YOUR_DATABASE.YOUR_SCHEMA.DAILY_METRIC
Using it on your data
The template's model is deliberately simple and runs inside the app. For production forecasts on many series, the app's notes explain how to switch to Snowflake's built-in SNOWFLAKE.ML.FORECAST, which trains and predicts inside Snowflake.
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 147 lines
"""Forecast — projects a metric forward with trend and seasonality, shows the
uncertainty band, how accurate the model was recently, and unusual periods."""
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
st.set_page_config(page_title="Forecast", 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 date (and segment) with the value to forecast.
DEMO = True
SERIES_SQL = """
SELECT DATE, SEGMENT, VALUE
FROM {{DATABASE}}.{{SCHEMA}}.DAILY_METRIC
"""
METRIC_NAME = "Orders"
# ──────────────────────────────────────────────────────────────────────────────
def demo_series() -> pd.DataFrame:
rng = np.random.default_rng(29)
days = pd.date_range(end=pd.Timestamp.today().normalize(), periods=3 * 365, freq="D")
t = np.arange(len(days))
rows = []
for seg, base, growth in (("Online", 420, 0.0009), ("Retail", 300, 0.0003), ("Wholesale", 120, 0.0006)):
yearly = 1 + 0.18 * np.sin((days.dayofyear.to_numpy() - 80) / 365 * 2 * np.pi)
weekly = np.where(days.dayofweek.to_numpy() >= 5, 0.75, 1.05)
y = base * (1 + growth * t) * yearly * weekly * rng.normal(1, 0.06, len(days))
spikes = rng.random(len(days)) < 0.006
y[spikes] *= rng.uniform(1.6, 2.2, spikes.sum())
rows.append(pd.DataFrame({"DATE": days, "SEGMENT": seg, "VALUE": y.round()}))
return pd.concat(rows, ignore_index=True)
@st.cache_data(ttl=600, show_spinner=False)
def load_series() -> pd.DataFrame:
if DEMO:
df = demo_series()
else:
from snowflake.snowpark.context import get_active_session
df = get_active_session().sql(SERIES_SQL).to_pandas()
df.columns = [c.upper() for c in df.columns]
df["DATE"] = pd.to_datetime(df["DATE"], errors="coerce")
df["VALUE"] = pd.to_numeric(df["VALUE"], errors="coerce")
df["SEGMENT"] = df["SEGMENT"].fillna("All").astype(str) if "SEGMENT" in df else "All"
return df.dropna(subset=["DATE", "VALUE"])
def design(index: pd.DatetimeIndex, start: pd.Timestamp, grain: str) -> np.ndarray:
"""Trend + seasonal dummies (month of year for monthly, week of year buckets for weekly)."""
t = ((index - start).days / 365.25).to_numpy()
season = index.month.to_numpy() if grain == "Month" else ((index.isocalendar().week.to_numpy() - 1) // 4 + 1).clip(1, 13)
k = 12 if grain == "Month" else 13
dummies = np.eye(k)[season - 1][:, 1:]
return np.column_stack([np.ones(len(index)), t, dummies])
def fit_forecast(y: pd.Series, grain: str, horizon: int):
start = y.index[0]
X = design(y.index, start, grain)
coef, *_ = np.linalg.lstsq(X, y.to_numpy(), rcond=None)
fitted = pd.Series(X @ coef, index=y.index)
resid = y - fitted
freq = "MS" if grain == "Month" else "W-MON"
future = pd.date_range(y.index[-1], periods=horizon + 1, freq=freq)[1:]
pred = pd.Series(design(future, start, grain) @ coef, index=future)
sigma = resid.std(ddof=X.shape[1]) if len(y) > X.shape[1] else resid.std()
return fitted, pred, sigma, resid
st.title(f"{METRIC_NAME} forecast")
if DEMO:
st.caption("Showing generated demo data — connect your own table in the DATA section.")
try:
series = load_series()
except Exception as e:
st.error(f"Could not load the series: {e}")
st.stop()
if series.empty:
st.info("No data yet.")
st.stop()
with st.sidebar:
st.header("Settings")
segments = sorted(series["SEGMENT"].unique())
chosen = st.multiselect("Segment", segments, default=segments)
grain = st.radio("Grain", ["Week", "Month"], horizontal=True)
horizon = st.slider("Periods ahead", 4, 26 if grain == "Week" else 18, 12 if grain == "Week" else 6)
scoped = series[series["SEGMENT"].isin(chosen)] if chosen else series
rule = "W-MON" if grain == "Week" else "MS"
y = scoped.set_index("DATE")["VALUE"].resample(rule, label="left", closed="left").sum()
y = y.iloc[1:-1] if len(y) > 3 else y # drop partial first/last periods
min_periods = 30 if grain == "Week" else 18
if len(y) < min_periods:
st.info(f"Need at least {min_periods} {grain.lower()}s of history for a forecast (have {len(y)}).")
st.stop()
fitted, pred, sigma, resid = fit_forecast(y, grain, horizon)
# Backtest: refit without the last `horizon` periods and compare.
hold = min(horizon, len(y) // 4)
_, back, _, _ = fit_forecast(y.iloc[:-hold], grain, hold)
actual = y.iloc[-hold:]
mape = (abs(back.to_numpy() - actual.to_numpy()) / actual.replace(0, np.nan).to_numpy())
mape = np.nanmean(mape)
z = resid / resid.std() if resid.std() else resid * 0
anomalies = y[abs(z) > 2.5]
k = st.columns(4)
k[0].metric(f"Next {horizon} {grain.lower()}s", f"{pred.sum():,.0f}")
k[1].metric(f"Last {horizon} {grain.lower()}s", f"{y.iloc[-horizon:].sum():,.0f}",
f"{pred.sum() / y.iloc[-horizon:].sum() - 1:+.1%} ahead" if y.iloc[-horizon:].sum() else None)
k[2].metric("Recent accuracy", f"{1 - mape:.0%}" if np.isfinite(mape) else "–", help=f"1 − mean absolute % error over the last {hold} periods, forecast without them")
k[3].metric("Unusual periods", f"{len(anomalies)}")
band = 1.64 * sigma # ~90% interval
fig = go.Figure()
fig.add_scatter(x=y.index, y=y, name="Actual", line=dict(color="#4c78a8"))
fig.add_scatter(x=fitted.index, y=fitted, name="Model", line=dict(color="#9ecae9", dash="dot"))
fig.add_scatter(x=list(pred.index) + list(pred.index[::-1]), y=list(pred + band) + list((pred - band)[::-1]),
fill="toself", fillcolor="rgba(245,133,24,0.18)", line=dict(width=0), name="90% range", hoverinfo="skip")
fig.add_scatter(x=pred.index, y=pred, name="Forecast", line=dict(color="#f58518", width=3))
fig.add_scatter(x=anomalies.index, y=anomalies, mode="markers", name="Unusual", marker=dict(color="#d62728", size=9, symbol="x"))
fig.update_layout(title=f"{METRIC_NAME} by {grain.lower()}", legend_title_text="", margin=dict(t=50, b=10), hovermode="x unified")
st.plotly_chart(fig, width="stretch")
st.caption("Model: linear trend plus seasonality, fitted in the app. For production forecasting at scale, "
"Snowflake's SNOWFLAKE.ML.FORECAST can replace it.")
left, right = st.columns(2)
left.subheader("Forecast")
left.dataframe(pd.DataFrame({"PERIOD": pred.index, "FORECAST": pred.round(), "LOW": (pred - band).round(), "HIGH": (pred + band).round()}),
width="stretch", column_config={"PERIOD": st.column_config.DateColumn("Period")})
right.subheader("Unusual periods")
if anomalies.empty:
right.success("Nothing unusual in the history.")
else:
right.dataframe(pd.DataFrame({"PERIOD": anomalies.index, "ACTUAL": anomalies.round(), "EXPECTED": fitted[anomalies.index].round()})
.sort_values("PERIOD", ascending=False).reset_index(drop=True),
width="stretch", column_config={"PERIOD": st.column_config.DateColumn("Period")})
Questions
How much history does it need?
At least 18 months for a monthly forecast or 30 weeks for a weekly one; with less, the app says how much more it needs. Two full years give the seasonal pattern more to go on.
Can it forecast many segments at once?
It forecasts the total of the segments you pick. For a separate forecast per segment across hundreds of series, use SNOWFLAKE.ML.FORECAST, which takes a series column.
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
Data entry
A validated Streamlit form that writes rows to a Snowflake table safely with bind variables, with the latest entries and a monthly summary.
Data explorer
Browse the tables in a Snowflake schema, profile columns, filter rows, group and chart, and download what you find. A read-only Streamlit template.
Customer feedback with Cortex AI
Score reviews, tickets or survey answers with Snowflake Cortex AI, sentiment, topics and an AI summary of the complaints. A free Streamlit template.
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.