Release v2.17.1: Backfill full 1-month completed closing-bell series (2026-11-30 & 2026-12-01 across all 23 public tickers), add lossless VPS telemetry snapshot/reconciliation, and enforce read-only VPS closeups/readme sync in Gate D4

This commit is contained in:
Hermes Agent committed 2026-12-02 14:26:04 +00:00
1 parent 5eca430cce
commit 52153e76f0
20 files changed
+3590 -3794

No files matched your search

+331 -66
View File
@@ -20,6 +20,7 @@ import datetime
import io
import json
import os
import re
import sys
import time
import urllib.parse
@@ -166,10 +167,29 @@ _EQ_CLOSURES_333: dict[int, list[str]] = {
}
def _fetch_yahoo_chart(symbol: str, timeout: float = 6.0) -> dict[str, Any] | None:
"""Source 1: Keyless Yahoo Finance v8 Chart JSON API (using actual prior trading day close)."""
def latest_completed_closing_bell_date_utc(now_utc: datetime.datetime | None = None) -> str:
"""
Return the latest UTC calendar date `YYYY-MM-DD` whose 16:00 EST / 21:00 UTC
US closing bell has completed. Before 21:00 UTC on day T, the latest completed
closing-bell session date is T - 1 day; at or after 21:00 UTC on day T, it is T.
"""
dt = now_utc or datetime.datetime.now(datetime.timezone.utc)
if dt.hour < 21:
dt = dt - datetime.timedelta(days=1)
return dt.strftime("%Y-%m-%d")
def _fetch_yahoo_chart_series(
symbol: str,
max_date_utc: str | None = None,
timeout: float = 6.0,
) -> dict[str, dict[str, Any]]:
"""
Fetch the full 1-month daily bar series from Yahoo Finance v8 Chart JSON API
(`?range=1mo&interval=1d`), filtered to completed closing-bell dates `<= max_date_utc`.
"""
if symbol == "ANTHR-PVT":
return None
return {}
enc_sym = urllib.parse.quote(symbol, safe="")
url = f"https://query1.finance.yahoo.com/v8/finance/chart/{enc_sym}?range=1mo&interval=1d"
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "application/json"})
@@ -179,7 +199,7 @@ def _fetch_yahoo_chart(symbol: str, timeout: float = 6.0) -> dict[str, Any] | No
data = json.loads(resp.read().decode("utf-8"))
res_list = (data.get("chart") or {}).get("result") or []
if not res_list:
return None
return {}
ts_list = res_list[0].get("timestamp") or []
quotes = (((res_list[0].get("indicators") or {}).get("quote") or [{}])[0])
raw_closes = quotes.get("close") or []
@@ -188,75 +208,124 @@ def _fetch_yahoo_chart(symbol: str, timeout: float = 6.0) -> dict[str, Any] | No
valid_pairs = [
(ts_list[i], float(raw_closes[i]), float(raw_vols[i]) if i < len(raw_vols) and raw_vols[i] is not None else None)
for i in range(min(len(ts_list), len(raw_closes)))
if raw_closes[i] is not None
if raw_closes[i] is not None and float(raw_closes[i]) > 0
]
if not valid_pairs:
return {}
out: dict[str, dict[str, Any]] = {}
for idx, (ts_val, close_usd, vol_val) in enumerate(valid_pairs):
obs_date = datetime.datetime.fromtimestamp(ts_val, datetime.timezone.utc).strftime("%Y-%m-%d")
if max_date_utc and obs_date > max_date_utc:
continue
prev_close = valid_pairs[idx - 1][1] if idx >= 1 else None
if prev_close and prev_close > 0:
chg_pct: float | None = round((close_usd - prev_close) / prev_close * 100.0, 2)
chg_bps: int | None = int(round(chg_pct * 100.0))
else:
chg_pct = None
chg_bps = None
vol_ratio: float | None = None
prior_vols = [x[2] for x in valid_pairs[max(0, idx - 20):idx] if x[2] is not None and x[2] > 0]
if vol_val is not None and vol_val > 0 and prior_vols:
avg_v = sum(prior_vols) / len(prior_vols)
if avg_v > 0:
vol_ratio = round(vol_val / avg_v, 2)
out[obs_date] = {
"date_utc": obs_date,
"observation_date_utc": obs_date,
"close_usd": round(close_usd, 2),
"change_pct": chg_pct,
"change_bps": chg_bps,
"volume_ratio_20d": vol_ratio,
"market_cap_str": None,
"feed_source": "yahoo_v8_json",
}
return out
def _fetch_yahoo_chart(symbol: str, timeout: float = 6.0) -> dict[str, Any] | None:
"""Source 1: Keyless Yahoo Finance v8 Chart JSON API (using latest completed closing-bell bar)."""
series = _fetch_yahoo_chart_series(
symbol,
max_date_utc=latest_completed_closing_bell_date_utc(),
timeout=timeout,
)
if not series:
return None
last_ts, close_usd, last_vol = valid_pairs[-1]
if close_usd <= 0:
return None
obs_date = datetime.datetime.fromtimestamp(last_ts, datetime.timezone.utc).strftime("%Y-%m-%d")
prev_close = valid_pairs[-2][1] if len(valid_pairs) >= 2 else None
if prev_close and prev_close > 0:
chg_pct: float | None = round((close_usd - prev_close) / prev_close * 100.0, 2)
chg_bps: int | None = int(round(chg_pct * 100.0))
else:
chg_pct = None
chg_bps = None
vol_ratio: float | None = None
prior_vols = [x[2] for x in valid_pairs[:-1][-20:] if x[2] is not None and x[2] > 0]
if last_vol is not None and last_vol > 0 and prior_vols:
avg_v = sum(prior_vols) / len(prior_vols)
if avg_v > 0:
vol_ratio = round(last_vol / avg_v, 2)
return {
"observation_date_utc": obs_date,
"close_usd": round(close_usd, 2),
"change_pct": chg_pct,
"change_bps": chg_bps,
"volume_ratio_20d": vol_ratio,
"market_cap_str": None,
"feed_source": "yahoo_v8_json",
}
latest_dt = sorted(series.keys())[-1]
return dict(series[latest_dt])
def _fetch_stooq_csv(symbol: str, timeout: float = 6.0) -> dict[str, Any] | None:
"""Source 2: Keyless Stooq Daily OHLCV CSV Fallback."""
def _fetch_stooq_csv_series(
symbol: str,
max_date_utc: str | None = None,
timeout: float = 6.0,
) -> dict[str, dict[str, Any]]:
"""Source 2: Keyless Stooq Daily OHLCV CSV Series Fallback."""
stooq_sym = _STOOQ_MAP.get(symbol)
if not stooq_sym:
return None
return {}
url = f"https://stooq.com/q/d/l/?s={stooq_sym}&i=d"
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
from hyperstitionstud_io.security import safe_urlopen
with safe_urlopen(req, timeout=timeout) as resp:
text = resp.read().decode("utf-8", errors="replace")
rows = list(csv.DictReader(io.StringIO(text)))
if not rows or "Close" not in rows[-1] or rows[-1]["Close"] in ("", "N/D", None):
raw_rows = [
r for r in csv.DictReader(io.StringIO(text))
if r.get("Date") and r.get("Close") not in ("", "N/D", None)
]
if not raw_rows:
return {}
out: dict[str, dict[str, Any]] = {}
start_idx = max(0, len(raw_rows) - 35)
for idx in range(start_idx, len(raw_rows)):
row = raw_rows[idx]
obs_date = str(row["Date"])
if max_date_utc and obs_date > max_date_utc:
continue
close_usd = float(row["Close"])
if close_usd <= 0:
continue
prev_close = float(raw_rows[idx - 1]["Close"]) if idx >= 1 else None
chg_pct = round((close_usd - prev_close) / prev_close * 100.0, 2) if (prev_close and prev_close > 0) else None
chg_bps = int(round(chg_pct * 100.0)) if chg_pct is not None else None
prior_vols = [
float(r["Volume"])
for r in raw_rows[max(0, idx - 20):idx]
if r.get("Volume") and str(r["Volume"]).replace(".", "").isdigit() and float(r["Volume"]) > 0
]
cur_vol_s = row.get("Volume")
cur_vol = float(cur_vol_s) if (cur_vol_s and str(cur_vol_s).replace(".", "").isdigit()) else None
vol_ratio = round(cur_vol / (sum(prior_vols) / len(prior_vols)), 2) if (cur_vol and prior_vols) else None
out[obs_date] = {
"date_utc": obs_date,
"observation_date_utc": obs_date,
"close_usd": round(close_usd, 2),
"change_pct": chg_pct,
"change_bps": chg_bps,
"volume_ratio_20d": vol_ratio,
"market_cap_str": None,
"feed_source": "stooq_csv",
}
return out
def _fetch_stooq_csv(symbol: str, timeout: float = 6.0) -> dict[str, Any] | None:
"""Source 2: Keyless Stooq Daily OHLCV CSV Fallback (latest completed closing-bell bar)."""
series = _fetch_stooq_csv_series(
symbol,
max_date_utc=latest_completed_closing_bell_date_utc(),
timeout=timeout,
)
if not series:
return None
close_usd = float(rows[-1]["Close"])
prev_close = float(rows[-2]["Close"]) if len(rows) >= 2 and rows[-2].get("Close") not in ("", "N/D", None) else None
chg_pct = round((close_usd - prev_close) / prev_close * 100.0, 2) if (prev_close and prev_close > 0) else None
chg_bps = int(round(chg_pct * 100.0)) if chg_pct is not None else None
vols = [float(r["Volume"]) for r in rows[-21:] if r.get("Volume") and r["Volume"].replace(".", "").isdigit()]
vol_ratio = None
if len(vols) >= 2:
avg_v = sum(vols[:-1]) / max(1, len(vols[:-1]))
if avg_v > 0:
vol_ratio = round(vols[-1] / avg_v, 2)
return {
"observation_date_utc": rows[-1].get("Date"),
"close_usd": round(close_usd, 2),
"change_pct": chg_pct,
"change_bps": chg_bps,
"volume_ratio_20d": vol_ratio,
"market_cap_str": None,
"feed_source": "stooq_csv",
}
latest_dt = sorted(series.keys())[-1]
return dict(series[latest_dt])
def _fetch_coingecko_crypto(timeout: float = 6.0) -> dict[str, dict[str, Any]]:
@@ -681,11 +750,19 @@ def build_financial_quant_harvest(
receipt = guard.audit_receipt()
available_count = sum(1 for x in instruments_out if x.get("data_available"))
unavailable_syms = [x["symbol"] for x in instruments_out if not x.get("data_available")]
observed_dates = sorted(
{
str(x["observation_date_utc"])
for x in instruments_out
if x.get("data_available") and x.get("observation_date_utc")
}
)
target_dt_utc = observed_dates[-1] if observed_dates else latest_completed_closing_bell_date_utc()
payload: dict[str, Any] = {
"$schema": "./schemas/v1/financial-aq-harvest.schema.json",
"$id": "urn:io:hyperstitionstud:schema:v1:financial-aq-harvest",
"version": "2.17.1",
"target_date_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d"),
"target_date_utc": target_dt_utc,
"harvest_mode": harvest_mode,
"synthetic_data_eliminated": True,
"regime_summary": {
@@ -754,11 +831,13 @@ def update_real_market_history_cache(
history_path: str | Path | None = None,
new_bars_by_symbol: dict[str, dict[str, dict[str, Any]]] | None = None,
allow_live_network: bool = False,
max_date_utc: str | None = None,
) -> dict[str, Any]:
"""
Merge new real daily exchange bars into `site/quant/real-market-history.json`.
Enforces strict Zero-Synthetic-Data honesty: `ANTHR-PVT` always remains `bars_by_date: {}`,
`data_available: False`, and closed weekend/holiday dates are never fabricated.
`data_available: False`, closed weekend/holiday dates are never fabricated, and incomplete
intraday candles from dates after `latest_completed_closing_bell_date_utc()` are excluded.
"""
from hyperstitionstud_io import __version__ as CURRENT_VERSION
@@ -769,6 +848,14 @@ def update_real_market_history_cache(
else:
doc = {"version": CURRENT_VERSION, "synthetic_data_eliminated": True, "instruments": {}}
effective_max_date = max_date_utc or (None if new_bars_by_symbol else latest_completed_closing_bell_date_utc())
cg_quotes: dict[str, dict[str, Any]] = {}
if allow_live_network and not new_bars_by_symbol:
try:
cg_quotes = _fetch_coingecko_crypto()
except Exception:
cg_quotes = {}
inst_map = doc.setdefault("instruments", {})
appended_count = 0
@@ -785,21 +872,44 @@ def update_real_market_history_cache(
entry = inst_map.setdefault(sym, {"symbol": sym, "data_available": True, "status": "ok", "bars_by_date": {}})
bars_by_dt = entry.setdefault("bars_by_date", {})
if effective_max_date:
for stale_dt in [d for d in list(bars_by_dt.keys()) if d > effective_max_date]:
del bars_by_dt[stale_dt]
if new_bars_by_symbol and sym in new_bars_by_symbol:
for dt_s, b_obj in new_bars_by_symbol[sym].items():
if effective_max_date and dt_s > effective_max_date:
continue
if b_obj and b_obj.get("close_usd") is not None:
bars_by_dt[dt_s] = b_obj
appended_count += 1
elif allow_live_network:
try:
live_b = _fetch_yahoo_chart(sym) or _fetch_stooq_csv(sym)
if live_b and live_b.get("observation_date_utc") and live_b.get("close_usd") is not None:
dt_s = live_b["observation_date_utc"]
bars_by_dt[dt_s] = live_b
appended_count += 1
series = _fetch_yahoo_chart_series(sym, max_date_utc=effective_max_date) or _fetch_stooq_csv_series(
sym, max_date_utc=effective_max_date
)
for dt_s, b_obj in sorted(series.items()):
if not b_obj or b_obj.get("close_usd") is None:
continue
prev_bar = bars_by_dt.get(dt_s)
if prev_bar is None or prev_bar.get("close_usd") is None:
if sym in cg_quotes and cg_quotes[sym].get("market_cap_str") and dt_s == effective_max_date:
b_obj = dict(b_obj)
b_obj["market_cap_str"] = cg_quotes[sym]["market_cap_str"]
bars_by_dt[dt_s] = b_obj
appended_count += 1
elif dt_s == effective_max_date:
merged_b = dict(b_obj)
if prev_bar.get("market_cap_str"):
merged_b["market_cap_str"] = prev_bar["market_cap_str"]
elif sym in cg_quotes and cg_quotes[sym].get("market_cap_str"):
merged_b["market_cap_str"] = cg_quotes[sym]["market_cap_str"]
bars_by_dt[dt_s] = merged_b
except Exception:
pass
entry["bars_by_date"] = {k: bars_by_dt[k] for k in sorted(bars_by_dt.keys())}
doc["version"] = CURRENT_VERSION
doc["synthetic_data_eliminated"] = True
h_path.parent.mkdir(parents=True, exist_ok=True)
@@ -807,17 +917,172 @@ def update_real_market_history_cache(
return {"history_path": str(h_path), "appended_bars_count": appended_count, "synthetic_data_eliminated": True}
_TELEMETRY_SNAPSHOT_FILES: tuple[str, ...] = (
"real-market-history.json",
"real-macro-indicators.json",
"daily-brief-state.json",
"financial-aq-harvest-latest.json",
)
def snapshot_local_telemetry(
snapshot_dir: str | Path,
quant_dir: str | Path | None = None,
) -> dict[str, Any]:
"""
Save a lossless copy of local `site/quant/` telemetry JSON ledgers into `snapshot_dir`
prior to pulling or resetting the Git working tree during VPS deployment sync.
"""
import shutil
cfg = load_workspace_config()
q_dir = Path(quant_dir) if quant_dir else (cfg.core_dir / "site" / "quant")
s_dir = Path(snapshot_dir)
s_dir.mkdir(parents=True, exist_ok=True)
saved: list[str] = []
for fname in _TELEMETRY_SNAPSHOT_FILES:
src = q_dir / fname
if src.is_file():
try:
json.loads(src.read_text(encoding="utf-8"))
shutil.copy2(src, s_dir / fname)
saved.append(fname)
except Exception:
continue
return {"ok": True, "snapshot_dir": str(s_dir), "saved_files": saved}
def reconcile_telemetry_snapshot(
snapshot_dir: str | Path,
quant_dir: str | Path | None = None,
max_date_utc: str | None = None,
recompile_bundles: bool = True,
) -> dict[str, Any]:
"""
Losslessly union-merge any valid completed harvest bars or FRED macro observations from
`snapshot_dir` that are absent in `quant_dir` (the newly pulled `origin/main` checkout).
If `origin/main` already contains 100% of completed observations (`merged_bars_count == 0`
and `merged_macro_obs_count == 0`), performs 0 disk writes so `git status` remains clean.
"""
cfg = load_workspace_config()
q_dir = Path(quant_dir) if quant_dir else (cfg.core_dir / "site" / "quant")
s_dir = Path(snapshot_dir)
effective_max_date = max_date_utc or latest_completed_closing_bell_date_utc()
merged_bars_count = 0
merged_macro_obs_count = 0
snap_hist_p = s_dir / "real-market-history.json"
cur_hist_p = q_dir / "real-market-history.json"
if snap_hist_p.is_file() and cur_hist_p.is_file():
try:
snap_hist = json.loads(snap_hist_p.read_text(encoding="utf-8"))
cur_hist = json.loads(cur_hist_p.read_text(encoding="utf-8"))
cur_insts = cur_hist.setdefault("instruments", {})
for sym, snap_obj in (snap_hist.get("instruments") or {}).items():
if sym == "ANTHR-PVT":
continue
cur_entry = cur_insts.setdefault(
sym, {"symbol": sym, "data_available": True, "status": "ok", "bars_by_date": {}}
)
cur_bars = cur_entry.setdefault("bars_by_date", {})
for dt_s, b_obj in (snap_obj.get("bars_by_date") or {}).items():
if not re.match(r"^\d{4}-\d{2}-\d{2}$", str(dt_s)):
continue
if dt_s > effective_max_date:
continue
if not isinstance(b_obj, dict) or b_obj.get("close_usd") is None:
continue
if dt_s not in cur_bars or cur_bars[dt_s].get("close_usd") is None:
cur_bars[dt_s] = b_obj
merged_bars_count += 1
cur_entry["bars_by_date"] = {k: cur_bars[k] for k in sorted(cur_bars.keys())}
if merged_bars_count > 0:
cur_hist_p.write_text(json.dumps(cur_hist, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
except Exception:
pass
snap_macro_p = s_dir / "real-macro-indicators.json"
cur_macro_p = q_dir / "real-macro-indicators.json"
if snap_macro_p.is_file() and cur_macro_p.is_file():
try:
snap_macro = json.loads(snap_macro_p.read_text(encoding="utf-8"))
cur_macro = json.loads(cur_macro_p.read_text(encoding="utf-8"))
cur_series = cur_macro.setdefault("series", {})
for s_key, snap_s in (snap_macro.get("series") or {}).items():
if s_key not in cur_series or not isinstance(snap_s, dict):
continue
cur_obs_list = cur_series[s_key].get("recent_observations") or []
cur_obs_by_dt = {str(o.get("date")): o for o in cur_obs_list if isinstance(o, dict) and o.get("date")}
added_here = 0
for o in snap_s.get("recent_observations") or []:
if not isinstance(o, dict) or not o.get("date") or o.get("value") is None:
continue
dt_s = str(o["date"])
if dt_s > effective_max_date:
continue
if dt_s not in cur_obs_by_dt or cur_obs_by_dt[dt_s].get("value") is None:
cur_obs_by_dt[dt_s] = o
merged_macro_obs_count += 1
added_here += 1
if added_here > 0:
sorted_obs = [cur_obs_by_dt[k] for k in sorted(cur_obs_by_dt.keys())]
cur_series[s_key]["recent_observations"] = sorted_obs
latest_valid = [x for x in sorted_obs if x.get("value") is not None]
if latest_valid:
cur_series[s_key]["latest_date"] = latest_valid[-1]["date"]
cur_series[s_key]["latest_value"] = latest_valid[-1]["value"]
if merged_macro_obs_count > 0:
cur_macro_p.write_text(json.dumps(cur_macro, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
macro_js_p = q_dir / "real-macro-indicators-data.js"
js_body = (
"// Auto-generated by hyperstitionstud_io.quant.macro — DO NOT EDIT MANUALLY\n"
f"window.HYPERSTITION_MACRO_DATA = {json.dumps(cur_macro, ensure_ascii=False)};\n"
)
macro_js_p.write_text(js_body, encoding="utf-8")
except Exception:
pass
reconciled_new_data = (merged_bars_count > 0) or (merged_macro_obs_count > 0)
if reconciled_new_data and recompile_bundles and q_dir == (cfg.core_dir / "site" / "quant"):
from hyperstitionstud_io.quant.daily_brief import build_daily_portfolio_brief
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
build_quant_timeseries_bundle(write_files=True)
build_daily_portfolio_brief(allow_live_network=False, write_files=True)
return {
"ok": True,
"reconciled_new_data": reconciled_new_data,
"merged_bars_count": merged_bars_count,
"merged_macro_obs_count": merged_macro_obs_count,
"max_date_utc": effective_max_date,
}
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="hs-quant-harvest", description="Periodic Quantitative Financial Telemetry & Contingent Meaning Collector.")
ap.add_argument("--mode", choices=["us-closing-bell", "utc-rollover"], default="us-closing-bell")
ap.add_argument("--from-snapshot", default=None, help="Optional offline JSON snapshot file.")
ap.add_argument("--live", action="store_true", help="Attempt live keyless HTTP fetch (Yahoo v8 / Stooq CSV / CoinGecko).")
ap.add_argument("--append-history", action="store_true", help="Merge newly fetched real exchange bars into site/quant/real-market-history.json.")
ap.add_argument("--snapshot-telemetry", default=None, help="Snapshot local site/quant/ telemetry JSON files into the specified directory.")
ap.add_argument("--reconcile-telemetry", default=None, help="Losslessly reconcile snapshotted telemetry JSON files from the specified directory.")
ap.add_argument("--join-news", default=None, help="Optional path to news-aq-harvest-latest.json.")
ap.add_argument("--write-dossier", default=None, help="Optional path to emit Markdown quant report.")
ap.add_argument("--out", default=None, help="Output JSON path (default: <core_dir>/site/quant/financial-aq-harvest-latest.json).")
args = ap.parse_args(argv)
if args.snapshot_telemetry:
res = snapshot_local_telemetry(args.snapshot_telemetry)
print(json.dumps(res, indent=2))
return 0
if args.reconcile_telemetry:
res = reconcile_telemetry_snapshot(args.reconcile_telemetry)
print(json.dumps(res, indent=2))
return 0
cfg = load_workspace_config()
if args.append_history:
update_real_market_history_cache(allow_live_network=args.live)