#!/usr/bin/env python3 """index_reproduce.py — recompute the TG Gifts Index (TGGI) from the public open data only. Why: a reference dataset is only credible if anyone can rebuild its headline number from the files it publishes. This tool re-implements the published index method (v1.0) in pure stdlib Python, using ONLY two public files: https://tggifts.com/data/floors-daily.json (all daily floors + recent sales) https://tggifts.com/data/index.json (published series to compare against) Published method (https://tggifts.com/index#method, v1.0): * base 2026-10-18 = 100 points * a collection counts on day t if it has a floor > 0 on t-1 and on t, and max(recent_sales(t-1), recent_sales(t)) >= 15 * weights are proportional to min(recent_sales, 60), no collection above 10% (excess redistributed over the rest) * TGGI_t = TGGI_(t-1) * SUM( w_i * floor_i,t / floor_i,t-1 ), rounded to 2 decimals * the day's constituents = number of rows used that day No AI, no secrets, no writes to the site, one fetch of each file per run. Exit codes: 0 = latest value reproduced (report may still list older-day notes), 1 = real mismatch on the latest official day (or >2% of days differ), 3 = a source could not be read (UNKNOWN, never guessed), 4 = selftest failure. Usage: python3 -I radar-ceo/tools/index_reproduce.py [--offline|--json|--selftest] [--write/--no-write] [--quiet] """ import json import os import sys import urllib.request from datetime import datetime try: # Python 3.11+ from datetime import UTC except ImportError: # launchd runs /usr/bin/python3 = 3.9, which has no datetime.UTC from datetime import timezone as _tz UTC = _tz.utc BASE = "https://tggifts.com" ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) CACHE = os.path.join(ROOT, "web3-radar", "data", "channel-cache") OUT_DIR = os.path.join(ROOT, "radar-ceo", "outputs") REPORT = os.path.join(OUT_DIR, "index-reproduce-latest.md") HIST = os.path.join(ROOT, "radar-ceo", "data", "index-reproduce-history.jsonl") # Published method constants (must mirror the methodology page, not the worker code) BASE_DATE = "2026-10-18" BASE_VALUE = 100.0 MIN_SALES = 15 SALES_CAP = 60 WEIGHT_CAP = 0.10 # Tolerance: the official close is frozen on the first scan of a day while the public # floors file is rebuilt from later scans of the same day, so a few hundredths of a point # can differ. 0.05 points is 0.04% of the index — far below any rounding of the formula, # and anything beyond 0.25 points is not explainable by that and counts as a real diff. VALUE_TOL = 0.05 VALUE_TOL_NEAR = 0.25 MAX_DAYS_DIFF_SHARE = 0.02 # more than 2% of days off = real problem def now_utc(): return datetime.now(UTC) def iso(t): return t.strftime("%Y-%m-%dT%H:%M:%SZ") def get(url, timeout=60): req = urllib.request.Request(url, headers={"User-Agent": "tggifts-index-repro/1.0"}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read()) def cap_weights(raw, cap=WEIGHT_CAP): """Same published rule as the index page: proportional, then capped, excess redistributed.""" keys = [k for k in raw if raw[k] > 0] tot = sum(raw[k] for k in keys) if not tot: return {} w = {k: raw[k] / tot for k in keys} if len(keys) * cap < 1: return w for _ in range(20): over = [k for k in keys if w[k] > cap + 1e-12] if not over: break excess = sum(w[k] - cap for k in over) free = [k for k in keys if w[k] < cap - 1e-12] ft = sum(w[k] for k in free) for k in over: w[k] = cap if ft <= 0: break for k in free: w[k] += excess * w[k] / ft return w def sales_int(x): """Fragment caps the shown sales at 60; the public file may carry 60 or '60+'.""" if isinstance(x, bool): return 0 if isinstance(x, (int, float)): return int(x) if isinstance(x, str): s = x.strip().rstrip("+") try: return int(float(s)) except ValueError: return 0 return 0 def build_days(floors): """slug -> {date: [floor, sales]} plus the sorted list of dates present.""" by_slug = {} dates = set() for slug, c in (floors.get("collections") or {}).items(): d = {} for row in c.get("days") or []: try: date, floor = row[0], float(row[1]) except (TypeError, ValueError, IndexError): continue sales = sales_int(row[2] if len(row) > 2 else 0) d[date] = (floor, sales) dates.add(date) by_slug[slug] = {"name": c.get("name") or slug, "by_day": d} return by_slug, sorted(x for x in dates if x >= BASE_DATE) def reproduce(floors): """Return (series, notes) — series rows: date, value, change_pct, constituents.""" by_slug, dates = build_days(floors) series = [] prev_date = None prev_value = None for date in dates: if prev_date is None: n = sum(1 for c in by_slug.values() if date in c["by_day"] and c["by_day"][date][0] > 0 and c["by_day"][date][1] >= MIN_SALES) series.append({"date": date, "value": round(BASE_VALUE, 2), "change_pct": None, "constituents": n}) prev_date, prev_value = date, BASE_VALUE continue raw, ratios = {}, {} for slug, c in by_slug.items(): a = c["by_day"].get(prev_date) b = c["by_day"].get(date) if not a or not b or not (a[0] > 0) or not (b[0] > 0): continue liq = max(a[1], b[1]) if liq < MIN_SALES: continue raw[slug] = min(liq, SALES_CAP) ratios[slug] = b[0] / a[0] w = cap_weights(raw) if not w: # no overlap with the previous day: the published method skips the day and # chains from the last good day (an outage must not create a fake move) continue ratio = sum(w[k] * ratios[k] for k in w) value = round(prev_value * ratio, 2) change = round((value / prev_value - 1) * 100, 2) if prev_value else None series.append({"date": date, "value": value, "change_pct": change, "constituents": len(w)}) prev_date, prev_value = date, value notes = [] if not series: notes.append("no day could be reproduced (empty floors file?)") return series, notes def compare(mine, published): """Per-day comparison against the published series.""" pub = {} for row in published.get("series") or []: try: pub[row["date"]] = {"value": float(row["value"]), "constituents": row.get("constituents")} except (KeyError, TypeError, ValueError): continue mine_by_date = {r["date"]: r for r in mine} days = sorted(set(pub) | set(mine_by_date)) rows = [] for d in days: a, b = mine_by_date.get(d), pub.get(d) if b is None: rows.append({"date": d, "status": "only-in-mine", "mine": a and a["value"], "published": None}) continue if a is None: rows.append({"date": d, "status": "only-in-published", "mine": None, "published": b["value"]}) continue dev = round(a["value"] - b["value"], 4) st = "match" if abs(dev) <= VALUE_TOL else ("near" if abs(dev) <= VALUE_TOL_NEAR else "diff") rows.append({"date": d, "status": st, "mine": a["value"], "published": b["value"], "deviation": dev, "constituents_mine": a["constituents"], "constituents_published": b.get("constituents")}) latest_date = published.get("latest", {}).get("date") if published.get("latest") else (days[-1] if days else None) latest = next((r for r in rows if r["date"] == latest_date), None) n_days = len([r for r in rows if r["published"] is not None]) n_diff = len([r for r in rows if r["status"] == "diff"]) n_near = len([r for r in rows if r["status"] == "near"]) n_only = len([r for r in rows if r["status"].startswith("only-in")]) max_dev = max([abs(r.get("deviation") or 0) for r in rows], default=0) return { "latest_date": latest_date, "latest": latest, "rows": rows, "n_days": n_days, "n_diff": n_diff, "n_near": n_near, "n_only": n_only, "max_abs_deviation": max_dev, "days_diff_share": round(n_diff / n_days, 4) if n_days else None, } def verdict(cmp): if cmp["latest"] is None: return "UNKNOWN", "the published latest day is not in either side's series" if cmp["latest"]["status"] == "diff": return "MISMATCH", f"latest official day {cmp['latest_date']} does not reproduce ({cmp['latest']})" allowed = max(2, int(round((cmp["n_days"] or 0) * MAX_DAYS_DIFF_SHARE))) if cmp["n_diff"] > allowed: return "MISMATCH", f"{cmp['n_diff']} of {cmp['n_days']} days differ (allowed {allowed})" if cmp["n_diff"] or cmp["n_only"]: return "OK-WITH-NOTES", f"latest day reproduces; {cmp['n_diff']} older day(s) differ, {cmp['n_only']} unmatched" return "OK", f"every published day reproduces within {VALUE_TOL} points" def report_md(res): L = ["# بازتولید مستقل شاخص TGGI از دادهٔ باز", ""] L.append(f"> {res['generated']} · منبع: `{res['sources']}` · بدون AI (`radar-ceo/tools/index_reproduce.py`)") L.append("") L.append(f"**حکم: {res['verdict']}** — {res['verdict_reason']}") L.append("") c = res["compare"] if c["latest"]: lt = c["latest"] L.append("| | مقدار |") L.append("|---|---|") L.append(f"| روز | {lt['date']} |") L.append(f"| شاخص منتشرشده | {lt['published']} |") L.append(f"| بازتولید ما | {lt['mine']} |") L.append(f"| اختلاف | {lt.get('deviation')} |") L.append(f"| اجزا (منتشرشده / بازتولید) | {lt.get('constituents_published')} / {lt.get('constituents_mine')} |") L.append("") L.append(f"- روزهای مقایسه‌شده: **{c['n_days']}** · منطبق: {c['n_days'] - c['n_diff'] - c['n_near']} · نزدیک (≤۰٫۰۵): {c['n_near']} · اختلاف: {c['n_diff']} · یک‌طرفه: {c['n_only']}") L.append(f"- بیشترین اختلاف مطلق در کل تاریخ: **{c['max_abs_deviation']}** امتیاز") bad = [r for r in c["rows"] if r["status"] in ("diff", "near", "only-in-mine", "only-in-published")] if bad: L.append("") L.append("| روز | منتشرشده | بازتولید | اختلاف | وضعیت |") L.append("|---|---|---|---|---|") for r in bad[:15]: L.append(f"| {r['date']} | {r.get('published')} | {r.get('mine')} | {r.get('deviation')} | {r['status']} |") if len(bad) > 15: L.append(f"| … | | | | {len(bad) - 15} روز دیگر |") L.append("") L.append("") L.append("**چرا اختلاف صفر مطلق نیست:** عدد رسمی هر روز روی اولین اسکن آن روز قفل می‌شود، ولی " "`floors-daily.json` عمومی بعد از اسکن‌های بعدی همان روز بازسازی می‌شود؛ پس چند صدم امتیاز فاصله طبیعی است. " "در دو روز اول تاریخچه، شمار اجزا هم ۲ تا ۴ واحد فرق دارد (۹۵/۹۸ بازسازی‌شده در برابر ۹۳/۹۴ قفل‌شده) — " "همان چیزی که صفحهٔ شاخص در `constituents_note` توضیح داده است. حکم ما روی «آخرین روز» و «بیشترین اختلاف» است، نه روی یکسان‌بودن بیت‌به‌بیت.") L.append("") L.append("روش بازتولید: پایه ۱۰۰ در 2026-10-18؛ هر کلکسیون با کف مثبت در دو روز متوالی و ≥۱۵ فروش اخیر؛ " "وزن ∝ min(فروش,۶۰) با سقف ۱۰٪ و پخش مازاد؛ شاخص = شاخص دیروز × Σ وزن × نسبت کف. " "تنها ورودی‌ها همان دو فایل عمومی‌اند؛ هیچ عددی از داخل سیستم ما خوانده نشد.") return "\n".join(L) + "\n" def run(offline=False): src = "offline cache" if offline else BASE try: if offline: floors = json.load(open(os.path.join(CACHE, "floors-daily.json"))) published = json.load(open(os.path.join(CACHE, "index.json"))) else: floors = get(BASE + "/data/floors-daily.json") published = get(BASE + "/data/index.json") except Exception as e: # noqa: BLE001 — any read failure is "unknown", never a guess return {"generated": iso(now_utc()), "sources": src, "verdict": "UNKNOWN", "verdict_reason": f"source could not be read: {type(e).__name__}: {e}"[:300], "compare": {"latest": None}, "error": True} mine, notes = reproduce(floors) cmp = compare(mine, published) v, why = verdict(cmp) res = {"generated": iso(now_utc()), "sources": src, "verdict": v, "verdict_reason": why, "compare": cmp, "notes": notes, "floors_generated": floors.get("generated"), "index_generated": published.get("generated"), "reproduced_days": len(mine)} if notes: res["verdict_reason"] += " | " + "; ".join(notes) return res def selftest(): """Offline fixtures — no network. Every case is a published-rule case.""" ok = 0 fails = [] def chk(name, cond): nonlocal ok if cond: ok += 1 else: fails.append(name) # 1) weights: proportional, capped, excess redistributed, sum == 1 w = cap_weights({"a": 60, "b": 60, "c": 60}) chk("three equal weights", all(abs(w[k] - 1 / 3) < 1e-9 for k in w) and abs(sum(w.values()) - 1) < 1e-9) raw = {"big": 1000} raw.update({f"s{i}": 10 for i in range(9)}) w = cap_weights(raw) chk("cap enforced", abs(w["big"] - WEIGHT_CAP) < 1e-9 and abs(sum(w.values()) - 1) < 1e-6) # 3 constituents cannot all be under a 10% cap: the published rule keeps proportional weights w = cap_weights({"big": 1000, "x": 10, "y": 10}) chk("cap unsatisfiable", abs(sum(w.values()) - 1) < 1e-9 and w["big"] > WEIGHT_CAP) chk("empty weights", cap_weights({}) == {}) # 2) sales parsing: Fragment cap "60+" and ints both count as 60 chk("sales 60+", sales_int("60+") == 60 and sales_int(60) == 60 and sales_int("17") == 17) chk("sales junk", sales_int(None) == 0 and sales_int("x") == 0) # 3) a single liquid collection moving 100 -> 110 gives +10% (equal weights of one) def floors_fixture(rows): return {"collections": {s: {"name": s, "days": d} for s, d in rows.items()}} f = floors_fixture({"a": [[BASE_DATE, 100, 20], ["2026-10-19", 110, 20]], "b": [[BASE_DATE, 50, 20], ["2026-10-19", 45, 20]]}) mine, _ = reproduce(f) chk("two-day base", mine[0]["value"] == 100.0 and mine[0]["constituents"] == 2) chk("two-day ratio", abs(mine[1]["value"] - round(100 * (1.1 * 0.5 + 0.9 * 0.5), 2)) < 1e-9) # 4) eligibility: below 15 recent sales is excluded; missing a floor day is excluded f = floors_fixture({"thin": [[BASE_DATE, 10, 3], ["2026-10-19", 20, 3]], "gap": [[BASE_DATE, 10, 50]], "ok1": [[BASE_DATE, 10, 50], ["2026-10-19", 10, 50]]}) mine, _ = reproduce(f) chk("eligibility filters", mine[1]["constituents"] == 1 and mine[1]["value"] == 100.0) # 5) a day is skipped only when NO collection has a floor on both days (outage, never a fake move) f = floors_fixture({"a": [[BASE_DATE, 100, 20], ["2026-10-20", 121, 20]]}) mine, _ = reproduce(f) chk("gap day chains", [r["date"] for r in mine] == [BASE_DATE, "2026-10-20"]) chk("gap day ratio", mine[1]["value"] == 121.0) f = floors_fixture({"a": [[BASE_DATE, 100, 20]], "b": [["2026-10-19", 10, 50]]}) mine, _ = reproduce(f) chk("skip when no overlap", len(mine) == 1) # 6) compare(): exact match, 2-decimal rounding counts as match, big gap is a diff published = {"latest": {"date": "2026-10-19", "value": 121.0}, "series": [{"date": BASE_DATE, "value": 100, "constituents": 1}, {"date": "2026-10-19", "value": 121.0, "constituents": 1}]} mine = [{"date": BASE_DATE, "value": 100.0, "constituents": 1}, {"date": "2026-10-19", "value": 121.004, "constituents": 1}] c = compare(mine, published) chk("rounding is a match", c["n_diff"] == 0 and verdict(c)[0] == "OK") mine[1]["value"] = 130.0 c = compare(mine, published) chk("real gap is a mismatch", verdict(c)[0] == "MISMATCH") # 7) verdict: older-day diffs under the share limit never pass as a full OK mine = [{"date": BASE_DATE, "value": 100.0, "constituents": 1}, {"date": "2026-10-19", "value": 121.0, "constituents": 1}] published = {"latest": {"date": "2026-10-19", "value": 121.0}, "series": [{"date": BASE_DATE, "value": 90, "constituents": 1}, {"date": "2026-10-19", "value": 121.0, "constituents": 1}]} v = verdict(compare(mine, published))[0] chk("old diff is flagged", v == "OK-WITH-NOTES") for f_ in fails: print("FAIL:", f_) print(f"selftest: {ok}/{ok + len(fails)} PASS") return 0 if not fails else 4 def main(argv): if "--selftest" in argv: return selftest() offline = "--offline" in argv res = run(offline=offline) if "--quiet" not in argv: print(report_md(res)) if "--json" in argv: print(json.dumps({k: v for k, v in res.items() if k != "compare"} | {"compare": {kk: vv for kk, vv in res["compare"].items() if kk != "rows"}}, ensure_ascii=False, indent=2)) if "--no-write" not in argv and not res.get("error"): os.makedirs(OUT_DIR, exist_ok=True) open(REPORT, "w").write(report_md(res)) os.makedirs(os.path.dirname(HIST), exist_ok=True) row = {"ts": res["generated"], "verdict": res["verdict"], "latest_date": res["compare"].get("latest_date"), "latest_published": (res["compare"].get("latest") or {}).get("published"), "latest_mine": (res["compare"].get("latest") or {}).get("mine"), "n_days": res["compare"].get("n_days"), "n_diff": res["compare"].get("n_diff"), "max_abs_deviation": res["compare"].get("max_abs_deviation")} with open(HIST, "a") as fh: fh.write(json.dumps(row, ensure_ascii=False) + "\n") c = res.get("compare") or {} lt = c.get("latest") or {} print("index-repro: verdict=%s latest=%s published=%s mine=%s dev=%s days=%s diff=%s max_dev=%s" % ( res["verdict"], c.get("latest_date"), lt.get("published"), lt.get("mine"), lt.get("deviation"), c.get("n_days"), c.get("n_diff"), c.get("max_abs_deviation"))) if res.get("error"): return 3 return 0 if res["verdict"] in ("OK", "OK-WITH-NOTES") else 1 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))