"""SOURCE render logic for TI-A-02 (REFERENCE ONLY).
This is the exact function from our pipeline. It is DB-coupled — you cannot run it without our database.
The query result it produces is materialized for you in data.csv, and the rendered output is figure.json
(load that to display the chart). This file is provided so you can understand / re-theme the logic.
"""
def render_TI_A_02(reg: dict) -> dict:
"""Momentum board - fastest-rising titles vs their own baseline, floored on weekly Demand Score."""
chart_id = "TI-A-02"
output_dir = THIS_DIR / chart_id / ROLE
conn = lib.connect_readonly()
t0 = time.time()
# Floor repointed from the retired DI scale to the official weekly Demand Score (demand_score_7d).
df = lib.run_query(conn, f"""
WITH latest AS (SELECT MAX(file_date) AS file_date FROM title_metrics_daily)
SELECT t.imdb_id, t.si::numeric AS si, r.demand_score_7d::numeric AS demand,
ROW_NUMBER() OVER (ORDER BY t.si DESC, t.imdb_id) AS rank,
l.file_date AS freshness_date
FROM title_metrics_daily t
JOIN latest l USING (file_date)
JOIN metrics_demand_rank_history r
ON r.imdb_id = t.imdb_id AND r.file_date = t.file_date AND r.geo_code = 'US'
WHERE t.geo_code = 'US' AND t.si IS NOT NULL
AND r.demand_score_7d >= {A02_DS7_FLOOR}
ORDER BY t.si DESC, t.imdb_id LIMIT 24;
""")
q_sec = time.time() - t0
if df.empty:
lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"],
f"No momentum rows above weekly Demand Score floor {A02_DS7_FLOOR}")
conn.close()
return {"status": "needs_spec_review"}
df = lib.drop_demand_orphans(df, conn) # hide in-theaters / not-yet-streaming demand-orphans
if len(df) < 12:
lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"],
f"Only {len(df)} titles clear the weekly Demand Score floor {A02_DS7_FLOOR} - board too thin")
conn.close()
return {"status": "needs_spec_review"}
df["rank"] = range(1, len(df) + 1)
titles = lib.resolve_titles(conn, df["imdb_id"].tolist())
conn.close()
df = df.merge(titles[["imdb_id", "display_title", "start_year"]], on="imdb_id", how="left")
df["display_title"] = df["display_title"].fillna(df["imdb_id"])
freshness = str(df["freshness_date"].iloc[0])
si = df["si"].astype(float)
stats = {
"top_title": df.iloc[0]["display_title"],
"gap_1_to_2": float(si.iloc[0] / si.iloc[1]) if len(si) > 1 and si.iloc[1] > 0 else 1.0,
"gap_2_to_3": float(si.iloc[1] / si.iloc[2]) if len(si) > 2 and si.iloc[2] > 0 else 1.0,
"gap_1_to_10": float(si.iloc[0] / si.iloc[9]) if len(si) > 9 and si.iloc[9] > 0 else 1.0,
"top3_share": float(si.head(3).sum() / si.sum()) if si.sum() > 0 else 0,
"top10_share": float(si.head(10).sum() / si.sum()) if si.sum() > 0 else 0,
}
lesson = lib.compute_lesson_concentration(stats, len(df))
plot_df = df.sort_values("rank", ascending=False)
plot_df["label"] = plot_df.apply(lib.title_label, axis=1)
# Class rule derived from the label's own rounding: a value whose 1-decimal print is 1.0x is
# HOLDING STEADY (neutral grey) - a 1% dip painted red overstated a flat reading. Red is
# reserved for genuine cooling (rounds below 1.0x); navy = the fastest riser ONLY.
def si_class(v: float) -> str:
r1 = round(v, 1)
if r1 > 1.0:
return "rising"
if r1 < 1.0:
return "cooling"
return "steady"
si_vals = plot_df["si"].astype(float)
classes = [si_class(v) for v in si_vals]
colors = [lib.NAVY if r == 1 else
(lib.MUTED if c == "steady" else (lib.RED if c == "cooling" else lib.PALE_BLUE))
for r, c in zip(plot_df["rank"], classes)]
def si_label(v: float) -> str:
# a value that would PRINT as the 1.0x reference while sitting off it gets a second
# decimal (0.99x / 1.04x), so the label never hides a real (if small) gap
if abs(v - 1.0) > 1e-9 and f"{v:.1f}" == "1.0":
return f"{v:,.2f}x"
return f"{v:,.1f}x"
CLASS_TAG = {"cooling": " · cooling", "steady": " · steady", "rising": ""}
bar_text = [f" {si_label(v)} baseline{CLASS_TAG[c]} · weekly Demand Score {d:,.0f}"
for v, c, d in zip(si_vals, classes, plot_df["demand"].astype(float))]
fig = go.Figure()
fig.add_trace(go.Bar(
x=plot_df["si"].astype(float), y=plot_df["label"], orientation="h",
marker=dict(color=colors, line=dict(width=0)),
cliponaxis=False, showlegend=False,
hovertemplate="%{y}
momentum %{x:.1f}x its own recent baseline",
))
# value labels as WHITE-BACKED annotations (not trace text): the dashed 1x reference line is
# drawn above the bars and was striking straight through the leading digits on every below-1x
# row - a backed annotation stays legible wherever the line crosses it
for v, lbl, txt in zip(plot_df["si"].astype(float), plot_df["label"], bar_text):
fig.add_annotation(x=v, y=lbl, xref="x", yref="y", text=txt.strip(), showarrow=False,
xanchor="left", xshift=4, yanchor="middle",
font=dict(size=10, color=lib.INK), bgcolor="rgba(255,255,255,0.88)")
fig.update_xaxes(range=lib.pad_range(si, labels=bar_text, font_px=10, fig_width=1160))
top_title = df.iloc[0]["display_title"]
top_si = float(si.iloc[0])
takeaway = (f"Among titles America is already watching, {top_title} is heating up fastest - "
f"{top_si:,.1f}x its own usual audience right now")
what = ("Each bar compares a title's audience right now with its own recent baseline: above the 1x line it is gaining, "
"right at 1x it is holding steady (grey), below it is cooling (red). Only titles with a real current audience make the board, so these are recognizable hits.")
# WHY kept short enough to fit one wrapped line plus the prefix (a longer first line ran off the canvas edge)
why = ("The weekly Demand Score says what's big; momentum says what's accelerating. Catch the movers before they peak.")
footer = lib.assemble_footer(
pc_id="PC-DP-02",
caution_labels=["CL-006 viewer panel (distinct viewers), not total plays", "CL-001 momentum is a proxy, not a forecast",
f"board floor: weekly Demand Score {A02_DS7_FLOOR:,}+"],
freshness_date=freshness, sources=["title_metrics_daily", "metrics_demand_rank_history"],
extra="")
fig.update_layout(
**lib.layout_v2(takeaway, what, width=1160, height=900),
xaxis=lib.standard_xaxis("Momentum (x its own recent baseline)"),
yaxis=lib.standard_yaxis(showgrid=False),
)
fig.layout.margin.t = int(fig.layout.margin.t) + 24 # room for the color key above the plot
fig.layout.height = int(fig.layout.height) + 24
# 1x line drawn above the bar fills; its label sits in a reserved band ABOVE the plot, anchored
# at the top of the line (inside the plot it landed on the #1 bar's ink)
vline_above(fig, 1.0)
ref_label_arrow(fig, 1.0, "1x = its usual audience")
# color key built from the classes actually drawn this week (never describes an absent class)
key_bits = [f"■ fastest riser"]
if "rising" in classes:
key_bits.append(f"■ rising (above 1x)")
if "steady" in classes:
key_bits.append(f"■ holding steady (about 1x)")
if "cooling" in classes:
key_bits.append(f"■ cooling (below 1x)")
lib.add_color_key(fig, " ".join(key_bits), y=1.052)
lib.add_why_and_footer(fig, why, footer)
lib.save_csv(df, output_dir)
lib.export_chart(fig, output_dir, width=1160, height=900)
lib.write_lesson_design(output_dir, chart_id, f"# {chart_id} - Momentum board\n\nLesson: {takeaway}\n\n{lesson['rules_applied']}\n")
write_shim(output_dir, chart_id)
lib.write_manifest(
output_dir, chart_id, "ok", reg["spec_file"], pc_id="PC-DP-02",
intended_lesson_from_spec="Fastest-rising titles (momentum vs own baseline) with weekly Demand Score floor",
rendered_lesson={"reader_title": takeaway, "reader_subtitle": what,
"claim_strength": lesson["claim_strength"],
"rules_applied": f"si desc; weekly demand_score_7d >= {A02_DS7_FLOOR}; top 24; orphans dropped"},
row_count=len(df), freshness_date=freshness,
query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec,
)
return {"status": "ok", "rows": len(df)}