590 lines
30 KiB
Python
590 lines
30 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
hyperstitionstud_io.quant.cards
|
||
One-Shot Ticker Stats Card Generator (`.png` + `.json`) — Pokémon / Sports Card / TCG / TierZoo Hybrid
|
||
rendered in the Group 3 ("Stealth Basalt Plate & Micro-Pip Signal Ribbon") `haiperdohp-jemaytreeah × hyperstitionstud.io`
|
||
design system (`900 × 1260 px`, `5:7` TCG Portrait).
|
||
Enforces 100% real exchange & news-wire observations (`None`/`null` -> `"No data available"` when absent)
|
||
and `draw_fitted_text()` / `draw_centered_in_box()` bounding-box clamping (`0` border breaches).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import base64
|
||
import hashlib
|
||
import io
|
||
import json
|
||
import os
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from hyperstitionstud_io import __version__ as CURRENT_VERSION
|
||
from hyperstitionstud_io.ciphers import compute_aq, prime_rank
|
||
from hyperstitionstud_io.config import load_workspace_config
|
||
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
|
||
from hyperstitionstud_io.ipld import compute_dag_json_cidv1
|
||
from hyperstitionstud_io.publishing.fonts import load_pillow_font
|
||
from hyperstitionstud_io.quant.collector import NO_DATA_AVAILABLE, _EQ_CLOSURES_333
|
||
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
|
||
|
||
|
||
def char_value_aq(ch: str) -> int:
|
||
c = ch.lower()
|
||
if "0" <= c <= "9":
|
||
return ord(c) - 48
|
||
if "a" <= c <= "z":
|
||
return ord(c) - 87
|
||
return 0
|
||
|
||
|
||
def compute_english_ordinal(text: str) -> int:
|
||
return sum((ord(c) - 96) for c in text.lower() if "a" <= c <= "z")
|
||
|
||
|
||
def compute_full_reduction(text: str) -> int:
|
||
return sum(((ord(c) - 97) % 9) + 1 for c in text.lower() if "a" <= c <= "z")
|
||
|
||
CARD_WIDTH = 900
|
||
CARD_HEIGHT = 1260
|
||
|
||
# Group 3 Preferred Default Palette Tokens (90% Quiet Matte Basalt / 7% #38bdf8 Interactive / 3% Explicit Lock Beacons)
|
||
BG_VOID = (2, 6, 23) # #020617
|
||
BG_WELL = (7, 13, 27) # #070d1b
|
||
BG_ODD = (12, 19, 36) # #0c1324
|
||
BG_EVEN = (17, 26, 46) # #111a2e
|
||
BG_BEZEL = (24, 35, 56) # #182338
|
||
BORDER_MUTED = (38, 52, 77) # #26344d
|
||
TXT_PRI = (226, 232, 240) # #e2e8f0
|
||
TXT_SEC = (148, 163, 184) # #94a3b8
|
||
TXT_DIM = (100, 116, 139) # #64748b
|
||
CYAN = (56, 189, 248) # #38bdf8
|
||
GOLD = (245, 158, 11) # #f59e0b
|
||
EMERALD = (16, 185, 129) # #10b981
|
||
ROSE = (244, 63, 94) # #f43f5e
|
||
|
||
|
||
def _chamfer_pts(x0: int, y0: int, x1: int, y1: int, ctl: int = 10, ctr: int = 10, cbr: int = 4, cbl: int = 4) -> list[tuple[int, int]]:
|
||
return [
|
||
(x0 + ctl, y0),
|
||
(x1 - ctr, y0),
|
||
(x1, y0 + ctr),
|
||
(x1, y1 - cbr),
|
||
(x1 - cbr, y1),
|
||
(x0 + cbl, y1),
|
||
(x0, y1 - cbl),
|
||
(x0, y0 + ctl),
|
||
]
|
||
|
||
|
||
def _draw_group3_plate(
|
||
draw: Any,
|
||
box: tuple[int, int, int, int],
|
||
fill: tuple[int, int, int],
|
||
attention_color: tuple[int, int, int] | None = None,
|
||
pip_color: tuple[int, int, int] | None = None,
|
||
) -> None:
|
||
x0, y0, x1, y1 = box
|
||
out_col = attention_color if attention_color else BORDER_MUTED
|
||
pts = _chamfer_pts(x0, y0, x1, y1, 10, 10, 4, 4)
|
||
draw.polygon(pts, fill=fill, outline=out_col)
|
||
band_h = min(y1 - y0, 28)
|
||
for y in range(y0 + 3, y0 + band_h, 3):
|
||
for x in range(x0 + 8 + (y % 2) * 3, x1 - 8, 6):
|
||
draw.point((x, y), fill=(22, 33, 54))
|
||
draw.polygon([(x0 + 10, y0 + 1), (x1 - 10, y0 + 1), (x1 - 7, y0 + 4), (x0 + 7, y0 + 4)], fill=BG_BEZEL)
|
||
pcol = attention_color or pip_color or (71, 85, 105)
|
||
draw.rectangle((x0 + 14, y0 + 1, x0 + 48, y0 + 4), fill=pcol)
|
||
|
||
|
||
def _draw_fitted_text(
|
||
draw: Any,
|
||
x: int,
|
||
y: int,
|
||
text: str,
|
||
fill: tuple[int, int, int],
|
||
fonts: list[Any],
|
||
max_x: int,
|
||
) -> None:
|
||
chosen = fonts[-1]
|
||
for f in fonts:
|
||
bx0, by0, bx1, by1 = draw.textbbox((x, y), text, font=f)
|
||
if bx1 <= max_x:
|
||
chosen = f
|
||
break
|
||
if draw.textbbox((x, y), text, font=chosen)[2] > max_x:
|
||
while len(text) > 3 and draw.textbbox((x, y), text + "...", font=chosen)[2] > max_x:
|
||
text = text[:-1]
|
||
text = text + "..."
|
||
draw.text((x, y), text, fill=fill, font=chosen)
|
||
|
||
|
||
def _draw_centered_in_box(
|
||
draw: Any,
|
||
cx: float,
|
||
cy: float,
|
||
text: str,
|
||
fill: tuple[int, int, int],
|
||
font: Any,
|
||
) -> None:
|
||
bx0, by0, bx1, by1 = draw.textbbox((0, 0), text, font=font)
|
||
tx = round(cx - (bx0 + bx1) / 2.0)
|
||
ty = round(cy - (by0 + by1) / 2.0)
|
||
draw.text((tx, ty), text, fill=fill, font=font)
|
||
|
||
|
||
def build_ticker_stats_card_json(
|
||
symbol: str,
|
||
lens: str = "tierzoo_ecology",
|
||
date_utc: str | None = None,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
Build the 5-zone One-Shot Ticker Stats Card JSON strictly from real exchange observations
|
||
and dated 00:00 UTC news dossiers (`None` / `null` when unavailable).
|
||
"""
|
||
cfg = load_workspace_config()
|
||
ts_json_path = cfg.core_dir / "site" / "quant" / "quant-timeseries.json"
|
||
if ts_json_path.is_file():
|
||
ts_bundle = json.loads(ts_json_path.read_text(encoding="utf-8"))
|
||
else:
|
||
ts_bundle = build_quant_timeseries_bundle(write_files=False)
|
||
|
||
q_up = symbol.strip().upper()
|
||
q_digits = q_up.replace("DEX", "").replace("#", "").strip()
|
||
target_inst: dict[str, Any] | None = None
|
||
for inst in ts_bundle["instruments"]:
|
||
if inst["symbol"].upper() == q_up or inst["symbol_clean"].upper() == q_up:
|
||
target_inst = inst
|
||
break
|
||
if q_digits.isdigit() and int(q_digits) in (inst["entity_ing_aq"], inst["entity_eng_aq"], inst["symbol_eng_aq"]):
|
||
target_inst = inst
|
||
break
|
||
|
||
if target_inst is None:
|
||
raise ValueError(f"Unknown watchlist symbol or DEX coordinate: {symbol!r}")
|
||
|
||
sym = target_inst["symbol"]
|
||
ent_eng = target_inst["entity_eng"]
|
||
ent_ing = target_inst["entity_ing"]
|
||
ent_eng_aq = int(target_inst["entity_eng_aq"])
|
||
ent_ing_aq = int(target_inst["entity_ing_aq"])
|
||
|
||
# Select target bar (either requested `date_utc` or latest available real trading session)
|
||
bars = target_inst.get("bars") or []
|
||
selected_bar: dict[str, Any] | None = None
|
||
if date_utc:
|
||
for b in bars:
|
||
if b.get("date_utc") == date_utc:
|
||
selected_bar = b
|
||
break
|
||
if selected_bar is None:
|
||
raise ValueError(f"Date {date_utc!r} is outside the 30-day window for {sym}.")
|
||
else:
|
||
avail_bars = [b for b in bars if b.get("data_available") and b.get("close_usd") is not None]
|
||
selected_bar = avail_bars[-1] if avail_bars else (bars[-1] if bars else None)
|
||
|
||
word_letters_ing = [ch for ch in ent_ing if ch.isalnum()]
|
||
word_values_aq = [char_value_aq(ch) for ch in word_letters_ing]
|
||
|
||
pkx = target_inst.get("pokedex_profile") or {}
|
||
ts_mom = target_inst.get("timeseries_moments") or {}
|
||
q_prof = ts_mom.get("ts_quantile_profile") or {}
|
||
|
||
bar_avail = bool(selected_bar and selected_bar.get("data_available") and selected_bar.get("close_usd") is not None)
|
||
mcap_val = selected_bar.get("market_cap_str") if selected_bar else None
|
||
if mcap_val == NO_DATA_AVAILABLE:
|
||
mcap_val = None
|
||
|
||
sig_eqs = _EQ_CLOSURES_333.get(ent_ing_aq) or _EQ_CLOSURES_333.get(ent_eng_aq) or [f"{ent_ing} = {ent_ing_aq} (Base-36 AQ Coordinate)"]
|
||
|
||
card_obj: dict[str, Any] = {
|
||
"$schema": "./schemas/v1/ticker-stats-card.schema.json",
|
||
"$id": "urn:io:hyperstitionstud:schema:v1:ticker-stats-card",
|
||
"version": CURRENT_VERSION,
|
||
"synthetic_data_eliminated": True,
|
||
"visual_style": "group_3_stealth_basalt_plate_and_micro_pip",
|
||
"card_identity": {
|
||
"symbol": sym,
|
||
"symbol_clean": target_inst["symbol_clean"],
|
||
"symbol_eng_aq": target_inst["symbol_eng_aq"],
|
||
"symbol_ing": target_inst["symbol_ing"],
|
||
"symbol_ing_aq": target_inst["symbol_ing_aq"],
|
||
"entity_eng": ent_eng,
|
||
"entity_ing": ent_ing,
|
||
"dex_number": pkx.get("dex_number") or f"DEX #{ent_ing_aq:03d}",
|
||
"guilds": target_inst["guilds"],
|
||
"tier_band": ((target_inst.get("lens_projections") or {}).get("tierzoo_ecology") or {}).get("tier_band") or "Tier A",
|
||
"evolution_stage": pkx.get("evolution_stage") or "Stage 2 (Guild Specialist)",
|
||
"composite_eti_score": target_inst["composite_score"],
|
||
"selected_lens": lens,
|
||
"tradingview_symbol": target_inst["tradingview_symbol"],
|
||
"tradingview_url": target_inst["tradingview_url"],
|
||
},
|
||
"cipher_breakdown": {
|
||
"word_letters_ing": word_letters_ing,
|
||
"word_values_aq": word_values_aq,
|
||
"eng_aq": ent_eng_aq,
|
||
"ing_aq": ent_ing_aq,
|
||
"eng_prime_rank": prime_rank(ent_eng_aq),
|
||
"ing_prime_rank": prime_rank(ent_ing_aq),
|
||
"eng_ordinal": compute_english_ordinal(ent_eng),
|
||
"ing_ordinal": compute_english_ordinal(ent_ing),
|
||
"eng_reduction": compute_full_reduction(ent_eng),
|
||
"ing_reduction": compute_full_reduction(ent_ing),
|
||
"phonemic_drift_delta": ent_ing_aq - ent_eng_aq,
|
||
"is_isometric": bool(ent_eng_aq == ent_ing_aq),
|
||
},
|
||
"tierzoo_base_stats_6": dict(target_inst["structural_vector"]),
|
||
"sports_card_box_score": {
|
||
"observation_date_utc": selected_bar["date_utc"] if selected_bar else None,
|
||
"data_available": bar_avail,
|
||
"status": "ok" if bar_avail else NO_DATA_AVAILABLE,
|
||
"available_trading_days": ts_mom.get("available_trading_days", 0),
|
||
"missing_trading_days": ts_mom.get("missing_trading_days", 30),
|
||
"close_usd": selected_bar["close_usd"] if bar_avail and selected_bar else None,
|
||
"change_pct": selected_bar["change_pct"] if bar_avail and selected_bar else None,
|
||
"change_bps": selected_bar["change_bps"] if bar_avail and selected_bar else None,
|
||
"volume_ratio_20d": selected_bar["volume_ratio_20d"] if bar_avail and selected_bar else None,
|
||
"market_cap_str": mcap_val,
|
||
"close_spoken_eng": selected_bar.get("close_spoken_eng") if bar_avail and selected_bar else None,
|
||
"close_spoken_eng_aq": selected_bar.get("close_spoken_eng_aq") if bar_avail and selected_bar else None,
|
||
"close_spoken_ing": selected_bar.get("close_spoken_ing") if bar_avail and selected_bar else None,
|
||
"close_spoken_ing_aq": selected_bar.get("close_spoken_ing_aq") if bar_avail and selected_bar else None,
|
||
"bps_spoken_eng": selected_bar.get("bps_spoken_eng") if bar_avail and selected_bar else None,
|
||
"bps_spoken_eng_aq": selected_bar.get("bps_spoken_eng_aq") if bar_avail and selected_bar else None,
|
||
"bps_spoken_ing": selected_bar.get("bps_spoken_ing") if bar_avail and selected_bar else None,
|
||
"bps_spoken_ing_aq": selected_bar.get("bps_spoken_ing_aq") if bar_avail and selected_bar else None,
|
||
"scope1_locks": selected_bar.get("scope1_locks", []) if bar_avail and selected_bar else [],
|
||
"scope2_ring_coordinates": selected_bar.get("scope2_ring_coordinates", []) if bar_avail and selected_bar else [],
|
||
"shared_dossier_coordinates": selected_bar.get("shared_dossier_coordinates", []) if bar_avail and selected_bar else [],
|
||
"confluence_dose": selected_bar.get("confluence_dose") if bar_avail and selected_bar else None,
|
||
"dose_taxon_label": selected_bar.get("dose_taxon_label") if bar_avail and selected_bar else None,
|
||
"duty_cycle_snap_pct": ts_mom.get("ts_duty_cycle_pct"),
|
||
"wopr_resonance": ts_mom.get("ts_weighted_resonance"),
|
||
"war_30d_excess": ts_mom.get("ts_excess_over_replacement"),
|
||
"quantile_profile": q_prof,
|
||
"optimal_lag_days": ts_mom.get("ts_optimal_lag_days"),
|
||
"sparkline_30d": ts_mom.get("ts_sparkline_30d"),
|
||
"real_close_series_30d": [b["close_usd"] if b.get("data_available") else None for b in bars],
|
||
"real_dose_series_30d": [b.get("confluence_dose") if b.get("data_available") else None for b in bars],
|
||
},
|
||
"tcg_abilities_and_moves": {
|
||
"nature": pkx.get("nature") or ("Calm (Isometric Invariant)" if ent_eng_aq == ent_ing_aq else "Modest (+SPA / -ATK • Harmonic Resonator)"),
|
||
"archetype": pkx.get("competitive_role") or "Multi-Factor Keystone Core",
|
||
"passive_ability": pkx.get("ability") or "Cross-Species Dossier Lock",
|
||
"ev_yield": pkx.get("ev_yield") or "+2 SPE, +1 SPA",
|
||
"signature_equation": sig_eqs[0],
|
||
"doc_references": target_inst.get("doc_references") or {},
|
||
},
|
||
"artifacts": {
|
||
"png_mime_type": "image/png",
|
||
"png_dimensions": [CARD_WIDTH, CARD_HEIGHT],
|
||
},
|
||
}
|
||
card_obj["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(card_obj)}
|
||
return card_obj
|
||
|
||
|
||
def render_ticker_stats_card_png_bytes(card_json: dict[str, Any]) -> bytes:
|
||
"""
|
||
Render the 5-zone `900 × 1260 px` (`5:7` TCG Portrait) Ticker Stats Card PNG in memory
|
||
using Group 3 ("Stealth Basalt Plate & Micro-Pip Signal Ribbon") and strict `draw_fitted_text()` clamping.
|
||
"""
|
||
from PIL import Image, ImageDraw
|
||
|
||
img = Image.new("RGB", (CARD_WIDTH, CARD_HEIGHT), BG_VOID)
|
||
draw = ImageDraw.Draw(img)
|
||
|
||
f_title = load_pillow_font("DejaVuSansMono-Bold.ttf", 22)
|
||
f_b18 = load_pillow_font("DejaVuSansMono-Bold.ttf", 18)
|
||
f_b15 = load_pillow_font("DejaVuSansMono-Bold.ttf", 15)
|
||
f_b13 = load_pillow_font("DejaVuSansMono-Bold.ttf", 13)
|
||
f_m13 = load_pillow_font("DejaVuSansMono.ttf", 13)
|
||
f_m12 = load_pillow_font("DejaVuSansMono.ttf", 12)
|
||
f_m11 = load_pillow_font("DejaVuSansMono.ttf", 11)
|
||
f_m10 = load_pillow_font("DejaVuSansMono.ttf", 10)
|
||
|
||
# Subtle Layer 0 basalt grid underlay
|
||
for y in range(0, CARD_HEIGHT, 32):
|
||
draw.line((0, y, CARD_WIDTH, y), fill=(7, 12, 24), width=1)
|
||
for x in range(0, CARD_WIDTH, 32):
|
||
draw.line((x, 0, x, CARD_HEIGHT), fill=(7, 12, 24), width=1)
|
||
|
||
# Outer Card Chassis (Group 3 10px/4px 45-Deg Chamfered Basalt Plate)
|
||
_draw_group3_plate(draw, (16, 16, CARD_WIDTH - 16, CARD_HEIGHT - 16), BG_ODD, pip_color=GOLD)
|
||
|
||
ident = card_json["card_identity"]
|
||
ciph = card_json["cipher_breakdown"]
|
||
stats6 = card_json["tierzoo_base_stats_6"]
|
||
box = card_json["sports_card_box_score"]
|
||
tcg = card_json["tcg_abilities_and_moves"]
|
||
|
||
# ZONE 1: Pokémon TCG / Gen IV Pokédex Header (34, 34, 866, 144)
|
||
_draw_group3_plate(draw, (34, 34, 866, 144), BG_WELL, pip_color=GOLD)
|
||
hdr_left = f"[{ident['evolution_stage'].split('(')[0].strip().upper()}] {ident['symbol']} // {ident['entity_eng']} -> {ident['entity_ing']}"
|
||
_draw_fitted_text(draw, 52, 48, hdr_left, TXT_PRI, [f_title, f_b18, f_b15], max_x=630)
|
||
# Tier Badge on top right
|
||
_draw_group3_plate(draw, (644, 44, 850, 84), BG_ODD, attention_color=GOLD, pip_color=GOLD)
|
||
_draw_centered_in_box(draw, 747, 64, f"{ident['tier_band'].split('(')[0].strip()} | {ident['composite_eti_score']} ETI", GOLD, f_b13)
|
||
|
||
pr_ing = f"[{ciph['ing_prime_rank']}th PRIME]" if ciph.get("ing_prime_rank") else ("Isometric Δ=0" if ciph.get("is_isometric") else f"Δ={ciph['phonemic_drift_delta']:+d}")
|
||
sub_hdr = f"★ {ident['dex_number']} ({pr_ing}) • Symbol AQ: {ident['symbol_eng_aq']} • Guilds: {','.join(ident['guilds'])} • {ident['tradingview_symbol']}"
|
||
_draw_fitted_text(draw, 52, 102, sub_hdr, GOLD, [f_m13, f_m12, f_m11], max_x=848)
|
||
|
||
# ZONE 2: haiperdohp-jemaytreeah #BreakdownSpot (Left) + #ChartSpot 30d Real Tape (Right) (34, 160, 866, 446)
|
||
_draw_group3_plate(draw, (34, 160, 456, 446), BG_WELL, pip_color=CYAN)
|
||
_draw_fitted_text(draw, 50, 174, "ZONE 2A: #BreakdownSpot (haiperdohp Ciphers)", TXT_SEC, [f_b13, f_m12], max_x=442)
|
||
letters = ciph["word_letters_ing"][:10]
|
||
vals = ciph["word_values_aq"][:10]
|
||
if letters:
|
||
cell_w = min(38, max(26, 380 // len(letters)))
|
||
lx = 50
|
||
for ch, v in zip(letters, vals):
|
||
is_pk = (v == max(vals))
|
||
draw.rectangle((lx, 202, lx + cell_w - 3, 250), fill=BG_ODD, outline=CYAN if is_pk else BORDER_MUTED)
|
||
_draw_centered_in_box(draw, lx + (cell_w - 3) / 2.0, 216, ch, CYAN if is_pk else TXT_PRI, f_b13)
|
||
_draw_centered_in_box(draw, lx + (cell_w - 3) / 2.0, 238, str(v), GOLD if is_pk else TXT_DIM, f_m10)
|
||
lx += cell_w
|
||
|
||
c_rows = [
|
||
("CIPHER", "GEN 0 (ENG)", "GEN 1 (ING)", "DELTA / RANK"),
|
||
("Base-36 AQ", str(ciph["eng_aq"]), str(ciph["ing_aq"]), pr_ing),
|
||
("Eng. Ordinal", str(ciph["eng_ordinal"]), str(ciph["ing_ordinal"]), f"{ciph['ing_ordinal'] - ciph['eng_ordinal']:+d}"),
|
||
("Full Reduction", str(ciph["eng_reduction"]), str(ciph["ing_reduction"]), f"{ciph['ing_reduction'] - ciph['eng_reduction']:+d}"),
|
||
("Ticker Symbol", ident["symbol_clean"], str(ident["symbol_eng_aq"]), f"Ing: {ident['symbol_ing_aq']}"),
|
||
]
|
||
cy = 264
|
||
for r_i, crow in enumerate(c_rows):
|
||
rbg = BG_VOID if r_i == 0 else (BG_ODD if r_i % 2 == 1 else BG_EVEN)
|
||
draw.rectangle((50, cy, 440, cy + 32), fill=rbg, outline=BORDER_MUTED)
|
||
fg = TXT_SEC if r_i == 0 else (GOLD if r_i == 1 else TXT_PRI)
|
||
_draw_fitted_text(draw, 58, cy + 9, crow[0], fg, [f_m11], max_x=168)
|
||
_draw_fitted_text(draw, 174, cy + 9, crow[1], fg, [f_m11], max_x=258)
|
||
_draw_fitted_text(draw, 264, cy + 9, crow[2], fg, [f_m11], max_x=342)
|
||
_draw_fitted_text(draw, 348, cy + 9, crow[3], fg, [f_m11, f_m10], max_x=434)
|
||
cy += 33
|
||
|
||
# Zone 2B: #ChartSpot 30-Day Real Closing-Bell Trajectory
|
||
_draw_group3_plate(draw, (472, 160, 866, 446), BG_WELL, pip_color=GOLD)
|
||
_draw_fitted_text(draw, 488, 174, "ZONE 2B: #ChartSpot (30d Real Exchange Tape)", TXT_SEC, [f_b13, f_m12], max_x=852)
|
||
closes_30d = box.get("real_close_series_30d") or []
|
||
doses_30d = box.get("real_dose_series_30d") or []
|
||
valid_closes = [float(c) for c in closes_30d if c is not None]
|
||
if valid_closes:
|
||
c_min, c_max = min(valid_closes), max(valid_closes)
|
||
c_span = max(1e-6, c_max - c_min)
|
||
draw.rectangle((488, 206, 850, 376), fill=BG_VOID, outline=BORDER_MUTED)
|
||
for gy in range(230, 370, 35):
|
||
draw.line((490, gy, 848, gy), fill=(13, 22, 41), width=1)
|
||
pts_line: list[tuple[int, int]] = []
|
||
dose_markers: list[tuple[int, int, int]] = []
|
||
n_bars = max(1, len(closes_30d) - 1)
|
||
for idx, c_val in enumerate(closes_30d):
|
||
if c_val is None:
|
||
continue
|
||
px = int(502 + (idx / n_bars) * 334)
|
||
py = int(358 - ((float(c_val) - c_min) / c_span) * 134)
|
||
pts_line.append((px, py))
|
||
d_v = int(doses_30d[idx] or 0) if idx < len(doses_30d) and doses_30d[idx] is not None else 0
|
||
if d_v >= 2:
|
||
dose_markers.append((px, py, d_v))
|
||
if len(pts_line) >= 2:
|
||
draw.line(pts_line, fill=TXT_SEC, width=2)
|
||
for mx, my, dv in dose_markers:
|
||
mcol = ROSE if dv >= 3 else EMERALD
|
||
draw.ellipse((mx - 5, my - 5, mx + 5, my + 5), fill=mcol, outline=TXT_PRI)
|
||
_draw_fitted_text(draw, 488, 386, f"Range: ${c_min:.2f} .. ${c_max:.2f} ({box['available_trading_days']}/30 Real Sessions)", TXT_PRI, [f_m11], max_x=852)
|
||
_draw_fitted_text(draw, 488, 410, f"Closed/Holiday Days: {box['missing_trading_days']} = null (● D2 Pin / ▲ D3 Surge)", TXT_DIM, [f_m11, f_m10], max_x=852)
|
||
else:
|
||
draw.rectangle((488, 206, 850, 376), fill=BG_VOID, outline=BORDER_MUTED)
|
||
_draw_centered_in_box(draw, 669, 276, "NO MARKET DATA AVAILABLE", TXT_SEC, f_b15)
|
||
_draw_centered_in_box(draw, 669, 306, "(Private Entity — 0 Synthetic Bars)", TXT_DIM, f_m12)
|
||
_draw_fitted_text(draw, 488, 396, "All price/volume/moment fields are strictly null.", TXT_DIM, [f_m11], max_x=852)
|
||
|
||
# ZONE 3: TierZoo 6-Base-Stat Ecological Scorecard (34, 462, 866, 718)
|
||
_draw_group3_plate(draw, (34, 462, 866, 718), BG_WELL)
|
||
_draw_fitted_text(draw, 52, 476, "ZONE 3: TIERZOO 6-BASE-STAT ECOLOGICAL SCORECARD (0-100 SCALE • >=90 PEAK LIT)", TXT_SEC, [f_b13, f_m12], max_x=848)
|
||
stat_rows = [
|
||
("ARM (Isometric Chokepoint Armor)", float(stats6["struct_isometric_armor"])),
|
||
("VEL (Phonemic Signal Velocity) ", float(stats6["struct_drift_velocity"])),
|
||
("COL (Vector G1 Variance Collapse)", float(stats6["struct_variance_collapse"])),
|
||
("CAP (S×S6 Trophic Capture Reach)", float(stats6["struct_trophic_capture"])),
|
||
("PRM (Prime & Twin-Prime IQ) ", float(stats6["struct_prime_density"])),
|
||
("RES (Repricing & State Ward) ", float(stats6["struct_repricing_resilience"])),
|
||
]
|
||
sy = 508
|
||
for slbl, sval in stat_rows:
|
||
is_peak = (sval >= 90.0)
|
||
bcol = GOLD if is_peak else (62, 84, 118)
|
||
_draw_fitted_text(draw, 52, sy, slbl, TXT_PRI if is_peak else TXT_SEC, [f_m12, f_m11], max_x=340)
|
||
draw.rectangle((350, sy + 2, 770, sy + 18), fill=BG_VOID, outline=BORDER_MUTED)
|
||
fill_w = int(4.2 * max(0.0, min(100.0, sval)))
|
||
draw.rectangle((350, sy + 2, 350 + fill_w, sy + 18), fill=bcol)
|
||
_draw_fitted_text(draw, 784, sy, f"{sval:5.1f}", GOLD if is_peak else TXT_PRI, [f_b13, f_m12], max_x=852)
|
||
sy += 33
|
||
|
||
# ZONE 4: Sports-Card Back-of-Card Real Season Box Score (.HistoryTable Zebra Grid) (34, 734, 866, 978)
|
||
dose_v = box.get("confluence_dose")
|
||
z4_attn = ROSE if (dose_v is not None and dose_v >= 3) else (EMERALD if dose_v == 2 else None)
|
||
_draw_group3_plate(draw, (34, 734, 866, 978), BG_WELL, attention_color=z4_attn, pip_color=z4_attn)
|
||
_draw_fitted_text(draw, 52, 748, f"ZONE 4: SPORTS-CARD REAL SEASON BOX SCORE (OBS DATE: {box['observation_date_utc'] or 'No data available'})", TXT_SEC, [f_b13, f_m12], max_x=848)
|
||
|
||
close_s = f"${box['close_usd']:.2f}" if box.get("close_usd") is not None else "No data available"
|
||
bps_s = f"{box['change_bps']:+d} bps" if box.get("change_bps") is not None else "No data available"
|
||
vol_s = f"{box['volume_ratio_20d']:.2f}x" if box.get("volume_ratio_20d") is not None else "No data available"
|
||
snap_s = f"{box['duty_cycle_snap_pct']:.1f}%" if box.get("duty_cycle_snap_pct") is not None else "N/A"
|
||
wopr_s = f"{box['wopr_resonance']:.1f}" if box.get("wopr_resonance") is not None else "N/A"
|
||
war_s = f"{box['war_30d_excess']:+.2f}" if box.get("war_30d_excess") is not None else "N/A"
|
||
dose_s = f"D{dose_v}/4" if dose_v is not None else "N/A"
|
||
|
||
headers_z4 = ["SESSIONS", "LAST CLOSE", "MOVE (BPS)", "VOL20D", "SNAP%", "WOPR", "WAR_30d", "DOSE"]
|
||
vals_z4 = [f"{box['available_trading_days']}/30", close_s, bps_s, vol_s, snap_s, wopr_s, war_s, dose_s]
|
||
zx = [50, 142, 272, 396, 488, 574, 658, 756, 850]
|
||
|
||
draw.rectangle((50, 778, 850, 810), fill=BG_VOID, outline=BORDER_MUTED)
|
||
draw.rectangle((50, 810, 850, 846), fill=BG_EVEN, outline=BORDER_MUTED)
|
||
for ci in range(len(headers_z4)):
|
||
draw.line((zx[ci], 778, zx[ci], 846), fill=BORDER_MUTED, width=1)
|
||
_draw_fitted_text(draw, zx[ci] + 6, 787, headers_z4[ci], TXT_SEC, [f_m11, f_m10], max_x=zx[ci + 1] - 4)
|
||
v_fg = z4_attn if (ci == 7 and z4_attn) else (TXT_DIM if "No data" in vals_z4[ci] or vals_z4[ci] == "N/A" else TXT_PRI)
|
||
_draw_fitted_text(draw, zx[ci] + 6, 820, vals_z4[ci], v_fg, [f_b13, f_m11, f_m10], max_x=zx[ci + 1] - 4)
|
||
|
||
# Spoken encodings & quantile row inside Zone 4
|
||
draw.rectangle((50, 856, 850, 910), fill=BG_ODD, outline=BORDER_MUTED)
|
||
sp_close_line = (
|
||
f"Close Spoken: '{box['close_spoken_eng']}' (Gen 0={box['close_spoken_eng_aq']}) -> '{box['close_spoken_ing']}' (Gen 1={box['close_spoken_ing_aq']})"
|
||
if box.get("close_spoken_ing_aq") is not None
|
||
else "Close Spoken: No data available (null)"
|
||
)
|
||
sp_bps_line = (
|
||
f"Move Spoken: '{box['bps_spoken_eng']}' (Gen 0={box['bps_spoken_eng_aq']}) -> '{box['bps_spoken_ing']}' (Gen 1={box['bps_spoken_ing_aq']}) | {box.get('dose_taxon_label') or ''}"
|
||
if box.get("bps_spoken_ing_aq") is not None
|
||
else "Move Spoken: No data available (null)"
|
||
)
|
||
_draw_fitted_text(draw, 60, 864, sp_close_line, TXT_PRI if box.get("close_spoken_ing_aq") else TXT_DIM, [f_m11, f_m10], max_x=842)
|
||
_draw_fitted_text(draw, 60, 886, sp_bps_line, z4_attn or (TXT_SEC if box.get("bps_spoken_ing_aq") else TXT_DIM), [f_m11, f_m10], max_x=842)
|
||
|
||
draw.rectangle((50, 918, 850, 962), fill=BG_EVEN, outline=BORDER_MUTED)
|
||
qp = box.get("quantile_profile") or {}
|
||
p20_s = f"{qp['p20_floor']:.1f}" if qp.get("p20_floor") is not None else "No data available"
|
||
p90_s = f"{qp['p90_ceiling']:.1f}" if qp.get("p90_ceiling") is not None else "No data available"
|
||
lag_s = f"{box['optimal_lag_days']:+d}d" if box.get("optimal_lag_days") is not None else "N/A"
|
||
mcap_disp = box.get("market_cap_str") or "No data available"
|
||
_draw_fitted_text(
|
||
draw, 60, 932,
|
||
f"P20 FLOOR: {p20_s} | P90 CEILING: {p90_s} | OPTIMAL LAG τ*: {lag_s} | MKT CAP: {mcap_disp}",
|
||
TXT_SEC, [f_m11, f_m10], max_x=842,
|
||
)
|
||
|
||
# ZONE 5: TCG Passive Ability, Signature 333/666/777 Move & Provenance Footer (34, 994, 866, 1226)
|
||
_draw_group3_plate(draw, (34, 994, 866, 1226), BG_WELL, pip_color=GOLD)
|
||
_draw_fitted_text(draw, 52, 1008, "ZONE 5: TCG PASSIVE ABILITY, SIGNATURE EQUATION MOVE & GROUNDED PROVENANCE", TXT_SEC, [f_b13, f_m12], max_x=848)
|
||
_draw_fitted_text(draw, 52, 1038, f"• [NATURE & ARCHETYPE]: {tcg['nature']} • {tcg['archetype']}", TXT_PRI, [f_m12, f_m11], max_x=848)
|
||
_draw_fitted_text(draw, 52, 1064, f"• [PASSIVE ABILITY]: {tcg['passive_ability']} (EV Yield: {tcg['ev_yield']})", EMERALD, [f_m12, f_m11], max_x=848)
|
||
|
||
draw.rectangle((52, 1094, 848, 1158), fill=BG_ODD, outline=GOLD)
|
||
_draw_fitted_text(draw, 64, 1104, "★ [SIGNATURE 333 / ARCHIVE EQUATION MOVE]:", GOLD, [f_b13, f_m12], max_x=836)
|
||
_draw_fitted_text(draw, 64, 1130, tcg["signature_equation"], CYAN, [f_b13, f_m12, f_m11], max_x=836)
|
||
|
||
cid_str = card_json["ipld_dag_json_cidv1"]["/"]
|
||
_draw_fitted_text(draw, 52, 1172, f"URN: urn:io:hyperstitionstud:card:{ident['symbol']}:{CURRENT_VERSION} • Zero Synthetic Data", TXT_DIM, [f_m11, f_m10], max_x=848)
|
||
_draw_fitted_text(draw, 52, 1196, f"IPLD dag-json CIDv1: {cid_str[:46]}... • Made with ♥ by Lemurs.", TXT_DIM, [f_m11, f_m10], max_x=848)
|
||
|
||
buf = io.BytesIO()
|
||
img.save(buf, format="PNG")
|
||
return buf.getvalue()
|
||
|
||
|
||
def _resolve_default_cards_dir() -> Path:
|
||
tmp_dir = Path("/tmp")
|
||
if tmp_dir.is_dir() and os.access(tmp_dir, os.W_OK):
|
||
return tmp_dir / "hyperstition-cards"
|
||
state_dir = Path("/var/lib/hyperstitionstud.io")
|
||
if state_dir.is_dir() and os.access(state_dir, os.W_OK):
|
||
return state_dir / "cards"
|
||
return Path("/tmp/hyperstition-cards")
|
||
|
||
|
||
def export_ticker_stats_card_pair(
|
||
symbol: str,
|
||
out_dir: str | Path | None = None,
|
||
lens: str = "tierzoo_ecology",
|
||
date_utc: str | None = None,
|
||
include_base64_png: bool = True,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
Generate both `<symbol>-stats-card.png` and `<symbol>-stats-card.json` in one shot
|
||
and return the complete Chatbot REST / MCP tool response payload.
|
||
Gracefully handles read-only filesystems (e.g. systemd ProtectSystem=strict) by
|
||
returning the in-memory `png_base64` and JSON payload even when disk caching is unavailable.
|
||
"""
|
||
cfg = load_workspace_config()
|
||
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
|
||
card_json = build_ticker_stats_card_json(symbol=symbol, lens=lens, date_utc=date_utc)
|
||
png_bytes = render_ticker_stats_card_png_bytes(card_json)
|
||
png_sha256 = hashlib.sha256(png_bytes).hexdigest()
|
||
|
||
target_dir = Path(out_dir) if out_dir is not None else _resolve_default_cards_dir()
|
||
out_p = target_dir.resolve()
|
||
sym_slug = card_json["card_identity"]["symbol_clean"].upper()
|
||
png_file = out_p / f"{sym_slug}-stats-card.png"
|
||
json_file = out_p / f"{sym_slug}-stats-card.json"
|
||
|
||
card_json["artifacts"] = {
|
||
"png_file_path": str(png_file),
|
||
"json_file_path": str(json_file),
|
||
"png_mime_type": "image/png",
|
||
"png_dimensions": [CARD_WIDTH, CARD_HEIGHT],
|
||
"png_byte_size": len(png_bytes),
|
||
"png_sha256": png_sha256,
|
||
}
|
||
if include_base64_png:
|
||
card_json["artifacts"]["png_base64"] = base64.b64encode(png_bytes).decode("ascii")
|
||
|
||
try:
|
||
out_p.mkdir(parents=True, exist_ok=True)
|
||
png_file.write_bytes(png_bytes)
|
||
json_file.write_text(json.dumps(card_json, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||
card_json["artifacts"]["persisted_to_disk"] = True
|
||
except OSError:
|
||
card_json["artifacts"]["persisted_to_disk"] = False
|
||
|
||
card_json["read_only_isolation_receipt"] = guard.audit_receipt()
|
||
return card_json
|
||
|
||
|
||
def main(argv: list[str] | None = None) -> int:
|
||
ap = argparse.ArgumentParser(prog="hs-ticker-card", description="Generate a one-shot .png + .json Ticker Stats Card.")
|
||
ap.add_argument("--symbol", default="NVDA", help="Ticker symbol or DEX coordinate (e.g., NVDA, PLTR, SOL-USD, ANTHR-PVT, 137).")
|
||
ap.add_argument("--lens", default="tierzoo_ecology")
|
||
ap.add_argument("--date", default=None, help="Optional YYYY-MM-DD UTC date.")
|
||
ap.add_argument("--out-dir", default="/tmp/hyperstition-cards")
|
||
args = ap.parse_args(argv)
|
||
res = export_ticker_stats_card_pair(
|
||
symbol=args.symbol,
|
||
out_dir=args.out_dir,
|
||
lens=args.lens,
|
||
date_utc=args.date,
|
||
include_base64_png=False,
|
||
)
|
||
print(
|
||
json.dumps(
|
||
{
|
||
"ok": True,
|
||
"symbol": res["card_identity"]["symbol"],
|
||
"data_available": res["sports_card_box_score"]["data_available"],
|
||
"png_file_path": res["artifacts"]["png_file_path"],
|
||
"json_file_path": res["artifacts"]["json_file_path"],
|
||
"png_byte_size": res["artifacts"]["png_byte_size"],
|
||
"png_sha256": res["artifacts"]["png_sha256"],
|
||
"cidv1": res["ipld_dag_json_cidv1"]["/"],
|
||
},
|
||
indent=2,
|
||
)
|
||
)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|