Files
hyperstitionstudio-core/src/hyperstitionstud_io/quant/collector.py
T

1269 lines
58 KiB
Python
Executable File

#!/usr/bin/env python3
"""
hyperstitionstud_io.quant.collector — Periodic Quantitative Financial Telemetry & Contingent Meaning Collector (`hs-quant-harvest`).
Strict Data Integrity Policy:
- Never synthesizes or hardcodes fake market prices, basis-point moves, or market caps.
- Uses only real market observations from Yahoo Finance v8, Stooq CSV, CoinGecko v3, or
the verified real exchange history cache (`site/quant/real-market-history.json`).
- Whenever market data is unavailable for an instrument (e.g. private entity `ANTHR-PVT`
or missing feed fields like `market_cap_str`), explicitly reports `"No data available"`
(`data_available = False`, numeric fields `None`).
"""
from __future__ import annotations
import argparse
import concurrent.futures
import csv
import datetime
import io
import json
import os
import re
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
_SRC_DIR = Path(__file__).resolve().parents[2]
if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from hyperstitionstud_io.ciphers import ( # noqa: E402
compute_aq,
expand_quant_spoken,
int_to_spoken_words,
is_repdigit_37,
prime_rank,
)
from hyperstitionstud_io.config import load_json_cached, load_workspace_config # noqa: E402
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard # noqa: E402
from hyperstitionstud_io.ipld import ( # noqa: E402
compute_dag_json_cidv1,
write_pretty_and_dag_json,
)
from hyperstitionstud_io.phonetics import translate_batch # noqa: E402
os.environ["TZ"] = "UTC"
if hasattr(time, "tzset"):
time.tzset()
NO_DATA_AVAILABLE = "No data available"
S1_S6_SIGNATURE_RINGS: dict[int, list[str]] = {
292: ["S1: shizohnalizis / abstrakt masheen / sinthetik dayta", "S6: asset management [Gen 0]"],
260: ["S3: teknohkapital / kiler rohbots"],
256: ["S2: akselerayshan / hai-freekwansee", "S6: sovran welth"],
246: ["S1: transformer [Iso]"],
237: ["S6: kansorsheeam [Iso]"],
222: ["S1: danyela amodai", "S6: enterpraiz"],
215: ["S3: jensan hwang / hohlee grayl"],
211: ["S3: wor masheen / koper waier", "S2/Q0: siks bilyan"],
197: ["S3: lathografee", "S6: monopoly [Gen 0]"],
193: ["S1: anthropik / Dario Amodei [Gen 0]", "S2: flash krash"],
191: ["S2: derivativ", "S6: lajistiks"],
189: ["S2: likwidatee / hangkerchif / imerjansee"],
183: ["S2: ruhnaway / tempaleks / laytansee", "S6: alakayshan"],
166: ["S2: order buk / noo flesh"],
163: ["S6: manopalee / masheenz"],
160: ["S6: kapasatee / truhst / rohbots / kriptoh / straiks"],
153: ["S6: aperatas / serplas", "S2: raizohm / reealatee [Iso]"],
137: ["S1: daireeoh", "S3: envideea", "M1: hawlts / inersha"],
136: ["S6: charter [Iso] / portal [Iso]", "M1: slohth"],
135: ["S1: dilooz / asemblaj / tenser"],
133: ["S1: wayts / sworm", "S6: ekwatee"],
129: ["S3: blakwel / ruhsha", "M7+: awflain"],
128: ["S3: nik land / masheen / serkat"],
125: ["S6: kapatal [Iso] / kapcher", "S2: fohldz / saires"],
115: ["S1: proof [Iso]"],
96: ["S1: klawd / failam / dayta"],
95: ["S2: lejer / faiber", "S5: flesh / huks"],
91: ["S3: tsmc [Iso] / laws"],
81: ["S3: asml [Iso]", "S6: aset"],
71: ["S3: gpu [Iso]"],
}
# Static watchlist metadata ONLY — zero hardcoded or synthesized prices/moves/caps.
CANONICAL_WATCHLIST_24: list[dict[str, Any]] = [
{"symbol": "NVDA", "entity_eng": "Nvidia", "guilds": ["S1", "S3"]},
{"symbol": "ASML", "entity_eng": "ASML", "guilds": ["S3", "S6"]},
{"symbol": "TSM", "entity_eng": "TSMC", "guilds": ["S3", "S6"]},
{"symbol": "ANTHR-PVT", "entity_eng": "Anthropic", "guilds": ["S1", "S2"]},
{"symbol": "MSFT", "entity_eng": "Microsoft", "guilds": ["S1", "S6"]},
{"symbol": "GOOGL", "entity_eng": "Alphabet", "guilds": ["S1", "S6"]},
{"symbol": "META", "entity_eng": "Meta", "guilds": ["S1", "S6"]},
{"symbol": "ORCL", "entity_eng": "Oracle", "guilds": ["S1", "S6"]},
{"symbol": "AVGO", "entity_eng": "Broadcom", "guilds": ["S3", "S6"]},
{"symbol": "ARM", "entity_eng": "Arm", "guilds": ["S3", "S1"]},
{"symbol": "AMD", "entity_eng": "AMD", "guilds": ["S3", "S1"]},
{"symbol": "PLTR", "entity_eng": "Palantir", "guilds": ["S3", "S6"]},
{"symbol": "LMT", "entity_eng": "Lockheed", "guilds": ["S3"]},
{"symbol": "RTX", "entity_eng": "Raytheon", "guilds": ["S3"]},
{"symbol": "HG=F", "entity_eng": "Copper", "guilds": ["S3", "S2"]},
{"symbol": "^VIX", "entity_eng": "VIX", "guilds": ["S2"]},
{"symbol": "BTC-USD", "entity_eng": "Bitcoin", "guilds": ["S2", "S6"]},
{"symbol": "ETH-USD", "entity_eng": "Ethereum", "guilds": ["S2"]},
{"symbol": "SOL-USD", "entity_eng": "Solana", "guilds": ["S2"]},
{"symbol": "COIN", "entity_eng": "Coinbase", "guilds": ["S2", "S6"]},
{"symbol": "CEG", "entity_eng": "Constellation", "guilds": ["S4", "S3"]},
{"symbol": "LLY", "entity_eng": "Eli Lilly", "guilds": ["S5", "S6"]},
{"symbol": "^TNX", "entity_eng": "Treasury", "guilds": ["S6", "S2"]},
{"symbol": "BLK", "entity_eng": "BlackRock", "guilds": ["S6"]},
]
_USER_AGENT = "Mozilla/5.0 (compatible; HyperstitionStudioQuantCollector/2.0; +urn:io:hyperstitionstud)"
_COINGECKO_MAP = {"BTC-USD": "bitcoin", "ETH-USD": "ethereum", "SOL-USD": "solana"}
_STOOQ_MAP = {
"NVDA": "nvda.us", "ASML": "asml.us", "TSM": "tsm.us", "MSFT": "msft.us",
"GOOGL": "googl.us", "META": "meta.us", "ORCL": "orcl.us", "AVGO": "avgo.us",
"ARM": "arm.us", "AMD": "amd.us", "PLTR": "pltr.us", "LMT": "lmt.us",
"RTX": "rtx.us", "COIN": "coin.us", "CEG": "ceg.us", "LLY": "lly.us", "BLK": "blk.us",
}
_EQ_CLOSURES_333: dict[int, list[str]] = {
71: [
"envideea (137) + fohldz (125) + gpu (71) = 333",
"daireeoh (137) + fohldz (125) + gpu (71) = 333",
],
81: [
"asml (81) + chaildz (126) + chaildz (126) = 333",
],
91: [
"tsmc (91) + fohldz (125) + tekst (117) = 333",
],
125: [
"envideea (137) + fohldz (125) + gpu (71) = 333",
],
137: [
"envideea (137) + fohldz (125) + gpu (71) = 333",
"daireeoh (137) + fohldz (125) + gpu (71) = 333",
],
163: [
"manopalee (163) + in (41) + blakwel (129) = 333",
],
191: [
"derivativ (191) + aiern (92) + tab (50) = 333",
"lajistiks (191) + aiern (92) + tab (50) = 333",
],
193: [
"anthropik (193) + koinbays (140) = 333",
"flash krash (193) + koinbays (140) = 333",
],
211: [
"lap (56) + for (66) + siks bilyan (211) = 333",
"lap (56) + for (66) + koper waier (211) = 333",
],
256: [
"akselerayshan (256) + in (41) + ai (36) = 333",
"sovran welth (256) + in (41) + ai (36) = 333",
],
292: [
"abstrakt masheen (292) + in (41) = 333",
"sinthetik dayta (292) + in (41) = 333",
],
}
MIN_SCOPE_DATE_UTC = "2026-11-01"
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,
min_date_utc: str | None = MIN_SCOPE_DATE_UTC,
max_date_utc: str | None = None,
timeout: float = 6.0,
) -> dict[str, dict[str, Any]]:
"""
Fetch the 3-month daily bar series from Yahoo Finance v8 Chart JSON API
(`?range=3mo&interval=1d`) so early-November bars always have a full 20-trading-day
trailing volume lookback window, while filtering emitted bars strictly to
`min_date_utc <= obs_date <= max_date_utc` (pre-Nov 1 out of scope).
"""
if symbol == "ANTHR-PVT":
return {}
enc_sym = urllib.parse.quote(symbol, safe="")
url = f"https://query1.finance.yahoo.com/v8/finance/chart/{enc_sym}?range=3mo&interval=1d"
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "application/json"})
from hyperstitionstud_io.security import safe_urlopen
with safe_urlopen(req, timeout=timeout) as resp:
data = json.loads(resp.read().decode("utf-8"))
res_list = (data.get("chart") or {}).get("result") or []
if not res_list:
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 []
raw_vols = quotes.get("volume") or []
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 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 min_date_utc and obs_date < min_date_utc:
continue
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,
min_date_utc=MIN_SCOPE_DATE_UTC,
max_date_utc=latest_completed_closing_bell_date_utc(),
timeout=timeout,
)
if not series:
return None
latest_dt = sorted(series.keys())[-1]
return dict(series[latest_dt])
def _fetch_stooq_csv_series(
symbol: str,
min_date_utc: str | None = MIN_SCOPE_DATE_UTC,
max_date_utc: str | None = None,
timeout: float = 6.0,
) -> dict[str, dict[str, Any]]:
"""Source 2: Keyless Stooq Daily OHLCV CSV Series Fallback (with 75-row lookback for 20d volume)."""
stooq_sym = _STOOQ_MAP.get(symbol)
if not stooq_sym:
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")
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) - 75)
for idx in range(start_idx, len(raw_rows)):
row = raw_rows[idx]
obs_date = str(row["Date"])
if min_date_utc and obs_date < min_date_utc:
continue
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
latest_dt = sorted(series.keys())[-1]
return dict(series[latest_dt])
def _fetch_coingecko_crypto(timeout: float = 6.0) -> dict[str, dict[str, Any]]:
"""Source 3: Keyless CoinGecko Public 24h Crypto & Liquidity JSON API."""
ids = ",".join(_COINGECKO_MAP.values())
url = f"https://api.coingecko.com/api/v3/simple/price?ids={ids}&vs_currencies=usd&include_24hr_change=true&include_market_cap=true"
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "application/json"})
from hyperstitionstud_io.security import safe_urlopen
with safe_urlopen(req, timeout=timeout) as resp:
data = json.loads(resp.read().decode("utf-8"))
out: dict[str, dict[str, Any]] = {}
for sym, cg_id in _COINGECKO_MAP.items():
if cg_id in data and "usd" in data[cg_id]:
c_usd = float(data[cg_id]["usd"])
chg_raw = data[cg_id].get("usd_24h_change")
chg_pct = round(float(chg_raw), 2) if chg_raw is not None else None
mcap = float(data[cg_id].get("usd_market_cap") or 0.0)
mcap_str = f"${mcap / 1e12:.2f}T" if mcap >= 1e12 else (f"${int(round(mcap / 1e9))}B" if mcap >= 1e9 else None)
out[sym] = {
"close_usd": round(c_usd, 2),
"change_pct": chg_pct,
"change_bps": int(round(chg_pct * 100.0)) if chg_pct is not None else None,
"market_cap_str": mcap_str,
"feed_source": "coingecko_v3_json",
}
return out
def _load_real_history_latest_bars() -> dict[str, dict[str, Any]]:
"""
Read the latest real exchange bar per symbol from `site/quant/real-market-history.json`
(populated strictly from real Yahoo Finance v8 / CoinGecko responses; never synthesized).
"""
cfg = load_workspace_config()
hist_path = cfg.core_dir / "site" / "quant" / "real-market-history.json"
if not hist_path.is_file():
return {}
try:
raw = load_json_cached(hist_path, copy_result=False)
out: dict[str, dict[str, Any]] = {}
for sym, sym_obj in (raw.get("instruments") or {}).items():
bars_by_date = sym_obj.get("bars_by_date") or {}
if bars_by_date:
latest_dt = sorted(bars_by_date.keys())[-1]
bar = dict(bars_by_date[latest_dt])
bar["observation_date_utc"] = latest_dt
out[sym] = bar
return out
except Exception:
return {}
def fetch_live_watchlist(
base_watchlist: list[dict[str, Any]] | None = None,
timeout: float = 6.0,
allow_live_network: bool = True,
) -> list[dict[str, Any]]:
"""
Resolve real market observations for the 24 watchlist instruments.
Never invents or synthesizes missing data: if an instrument has no real exchange observation
(e.g. private company `ANTHR-PVT`), its numeric fields remain `None` and `status` is
`"No data available"`.
"""
watchlist = [dict(x) for x in (base_watchlist or CANONICAL_WATCHLIST_24)]
cached_latest = _load_real_history_latest_bars()
cg_quotes: dict[str, dict[str, Any]] = {}
if allow_live_network:
try:
cg_quotes = _fetch_coingecko_crypto(timeout=timeout)
except Exception:
cg_quotes = {}
def _resolve_one(item: dict[str, Any]) -> dict[str, Any]:
sym = item["symbol"]
merged = {
"symbol": sym,
"entity_eng": item["entity_eng"],
"guilds": list(item["guilds"]),
"data_available": False,
"status": NO_DATA_AVAILABLE,
"feed_source": None,
"observation_date_utc": None,
"close_usd": None,
"change_pct": None,
"change_bps": None,
"volume_ratio_20d": None,
"market_cap_str": None,
}
if sym == "ANTHR-PVT":
merged["status"] = "No data available (private entity — not publicly traded)"
return merged
if allow_live_network:
for fetcher in (_fetch_yahoo_chart, _fetch_stooq_csv):
try:
q = fetcher(sym, timeout=timeout)
if q and q.get("close_usd") is not None:
merged.update(q)
if sym in cg_quotes and cg_quotes[sym].get("market_cap_str"):
merged["market_cap_str"] = cg_quotes[sym]["market_cap_str"]
merged["data_available"] = True
merged["status"] = "ok"
return merged
except Exception:
continue
if sym in cg_quotes and cg_quotes[sym].get("close_usd") is not None:
merged.update(cg_quotes[sym])
merged["data_available"] = True
merged["status"] = "ok"
return merged
if sym in cached_latest and cached_latest[sym].get("close_usd") is not None:
merged.update(cached_latest[sym])
merged["data_available"] = True
merged["status"] = "ok"
return merged
return merged
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
return list(pool.map(_resolve_one, watchlist))
def build_financial_quant_harvest(
harvest_mode: str = "us-closing-bell",
snapshot_path: str | Path | None = None,
join_news_path: str | Path | None = None,
live_fetch: bool = False,
) -> dict[str, Any]:
cfg = load_workspace_config()
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
if snapshot_path and Path(snapshot_path).is_file():
raw_watchlist = load_json_cached(snapshot_path, copy_result=False)
else:
raw_watchlist = fetch_live_watchlist(
CANONICAL_WATCHLIST_24,
allow_live_network=bool(live_fetch),
)
phrases_to_translate: list[str] = []
for item in raw_watchlist:
phrases_to_translate.append(item["entity_eng"])
if item.get("close_usd") is not None:
close_int = int(round(float(item["close_usd"])))
phrases_to_translate.append(int_to_spoken_words(close_int))
if item.get("change_bps") is not None:
bps_abs = abs(int(item["change_bps"]))
phrases_to_translate.append(int_to_spoken_words(bps_abs))
mcap_raw = item.get("market_cap_str")
if mcap_raw and mcap_raw != NO_DATA_AVAILABLE:
phrases_to_translate.append(expand_quant_spoken(str(mcap_raw)))
ing_map = translate_batch(phrases_to_translate)
effective_news_path = Path(join_news_path) if join_news_path else (cfg.archive_dir / "news-aq-harvest-latest.json")
news_entities: dict[str, list[str]] = {}
if effective_news_path.is_file():
try:
news_obj = load_json_cached(effective_news_path, copy_result=False)
headline_records: list[str] = []
for st in news_obj.get("stories", news_obj.get("headlines", [])):
if isinstance(st, dict):
hl = st.get("headline_eng") or st.get("title") or ""
if hl:
headline_records.append(str(hl))
for st in news_obj.get("twin_prime_headlines", []):
if isinstance(st, dict) and st.get("headline_eng"):
headline_records.append(str(st["headline_eng"]))
for _, group in (news_obj.get("shared_prime_attractors") or {}).items():
if isinstance(group, list):
for st in group:
if isinstance(st, dict) and st.get("headline_eng"):
headline_records.append(str(st["headline_eng"]))
for ent_item in news_obj.get("candidate_entities", []):
if isinstance(ent_item, dict) and ent_item.get("eng"):
headline_records.append(str(ent_item["eng"]))
for item in raw_watchlist:
sym = item["symbol"]
ent_low = item["entity_eng"].lower()
sym_clean = sym.split("-")[0].replace("^", "").replace("=F", "").lower()
matched_hls: list[str] = []
for hl in headline_records:
hl_low = hl.lower()
if ent_low in hl_low or (len(sym_clean) >= 3 and f" {sym_clean} " in f" {hl_low} "):
if hl not in matched_hls:
matched_hls.append(hl)
if matched_hls:
news_entities[sym] = matched_hls[:3]
except Exception:
news_entities = {}
instruments_out: list[dict[str, Any]] = []
active_memetic_states: set[str] = set()
emergent_m7_quant_triggers: list[dict[str, Any]] = []
vix_close_val: float | None = None
us10y_yield_val: float | None = None
for item in raw_watchlist:
sym = item["symbol"]
sym_clean = sym.split("-")[0].replace("^", "").replace("=F", "")
sym_eng_aq = compute_aq(sym_clean)
sym_ing = ing_map.get(sym_clean, sym_clean.lower())
sym_ing_aq = compute_aq(sym_ing)
ent_eng = item["entity_eng"]
ent_ing = ing_map.get(ent_eng, ent_eng.lower())
ent_eng_aq = compute_aq(ent_eng)
ent_ing_aq = compute_aq(ent_ing)
co_present = sym in news_entities
has_price = item.get("close_usd") is not None
if not has_price:
instruments_out.append({
"symbol": sym,
"symbol_clean": sym_clean,
"symbol_eng_aq": sym_eng_aq,
"symbol_ing": sym_ing,
"symbol_ing_aq": sym_ing_aq,
"entity_eng": ent_eng,
"entity_ing": ent_ing,
"entity_eng_aq": ent_eng_aq,
"entity_ing_aq": ent_ing_aq,
"guilds": item["guilds"],
"data_available": False,
"status": item.get("status") or NO_DATA_AVAILABLE,
"feed_source": None,
"observation_date_utc": None,
"co_present_in_news_wire": co_present,
"metrics": {
"close_usd": None,
"change_pct": None,
"change_bps": None,
"volume_ratio_20d": None,
"market_cap_str": NO_DATA_AVAILABLE,
},
"quant_encodings": {
"status": NO_DATA_AVAILABLE,
"close_digit_aq": None,
"close_spoken_eng": NO_DATA_AVAILABLE,
"close_spoken_eng_aq": None,
"close_spoken_ing": NO_DATA_AVAILABLE,
"close_spoken_ing_aq": None,
"close_spoken_prime_rank": None,
"scaled_cap_spoken_eng": NO_DATA_AVAILABLE,
"scaled_cap_spoken_eng_aq": None,
"scaled_cap_spoken_ing": NO_DATA_AVAILABLE,
"scaled_cap_spoken_ing_aq": None,
"bps_digit_aq": None,
"bps_spoken_eng": NO_DATA_AVAILABLE,
"bps_spoken_eng_aq": None,
"bps_spoken_ing": NO_DATA_AVAILABLE,
"bps_spoken_ing_aq": None,
},
"contingent_locks": [],
})
continue
close_val = float(item["close_usd"])
if sym == "^VIX":
vix_close_val = close_val
elif sym == "^TNX":
us10y_yield_val = close_val
close_int = int(round(close_val))
close_sp_eng = int_to_spoken_words(close_int)
close_sp_eng_aq = compute_aq(close_sp_eng)
close_sp_ing = ing_map.get(close_sp_eng, close_sp_eng)
close_dig_aq = compute_aq(str(close_int))
close_sp_aq = compute_aq(close_sp_ing)
chg_bps_raw = item.get("change_bps")
chg_pct_raw = item.get("change_pct")
if chg_bps_raw is not None:
bps_abs: int | None = abs(int(chg_bps_raw))
bps_sp_eng = int_to_spoken_words(bps_abs)
bps_sp_eng_aq: int | None = compute_aq(bps_sp_eng)
bps_sp_ing = ing_map.get(bps_sp_eng, bps_sp_eng)
bps_dig_aq: int | None = compute_aq(str(bps_abs))
bps_sp_aq: int | None = compute_aq(bps_sp_ing)
else:
bps_abs = None
bps_sp_eng = NO_DATA_AVAILABLE
bps_sp_eng_aq = None
bps_sp_ing = NO_DATA_AVAILABLE
bps_dig_aq = None
bps_sp_aq = None
mcap_raw = item.get("market_cap_str")
if mcap_raw and mcap_raw != NO_DATA_AVAILABLE:
mcap_s = str(mcap_raw)
mcap_sp_eng = expand_quant_spoken(mcap_s)
mcap_sp_eng_aq: int | None = compute_aq(mcap_sp_eng)
mcap_sp_ing = ing_map.get(mcap_sp_eng, mcap_sp_eng)
mcap_sp_aq: int | None = compute_aq(mcap_sp_ing)
else:
mcap_s = NO_DATA_AVAILABLE
mcap_sp_eng = NO_DATA_AVAILABLE
mcap_sp_eng_aq = None
mcap_sp_ing = NO_DATA_AVAILABLE
mcap_sp_aq = None
locks: list[dict[str, Any]] = []
if close_int == ent_ing_aq or close_int == ent_eng_aq:
locks.append({
"scope": "SCOPE1_INTRA_INSTRUMENT_SELF_LOCK",
"description": f"{sym} integer close (${close_int}) equals its own AQ coordinate ({ent_ing}={ent_ing_aq}).",
"verified_equations": list(_EQ_CLOSURES_333.get(close_int, [])),
})
if close_int == sym_eng_aq or close_int == sym_ing_aq:
locks.append({
"scope": "SCOPE1_SYMBOL_SELF_LOCK",
"description": f"{sym} integer close (${close_int}) equals its own ticker symbol AQ ({sym_clean}={sym_eng_aq}).",
"verified_equations": list(_EQ_CLOSURES_333.get(close_int, [])),
})
if is_repdigit_37(close_sp_aq) or is_repdigit_37(close_sp_eng_aq) or is_repdigit_37(close_int):
rep_val = close_sp_aq if is_repdigit_37(close_sp_aq) else (close_sp_eng_aq if is_repdigit_37(close_sp_eng_aq) else close_int)
locks.append({
"scope": "SCOPE1_SPOKEN_REPDIGIT_ATTRACTOR",
"description": f"{sym} close ${close_int} ('{close_sp_ing}') locks onto repdigit attractor {rep_val}.",
"verified_equations": [f"{close_sp_ing} = {close_sp_aq}"],
})
if bps_abs is not None and (bps_abs == ent_ing_aq or bps_abs == ent_eng_aq or bps_abs == sym_eng_aq):
locks.append({
"scope": "SCOPE1_BPS_ISOMETRIC_SELF_LOCK",
"description": f"{sym} basis-point move ({bps_abs} bps) equals its own AQ coordinate ({ent_ing}={ent_ing_aq} / {sym_clean}={sym_eng_aq}).",
"verified_equations": list(_EQ_CLOSURES_333.get(bps_abs, [])),
})
coord_checks: list[tuple[int, str]] = [
(close_int, "close_int"),
(close_sp_eng_aq, "close_spoken_eng_aq"),
(close_sp_aq, "close_spoken_ing_aq"),
]
if bps_abs is not None:
coord_checks.append((bps_abs, "change_bps"))
if bps_sp_eng_aq is not None:
coord_checks.append((bps_sp_eng_aq, "bps_spoken_eng_aq"))
if bps_sp_aq is not None:
coord_checks.append((bps_sp_aq, "bps_spoken_ing_aq"))
seen_ring_coords: set[int] = set()
for coord_val, label_mode in coord_checks:
if coord_val in S1_S6_SIGNATURE_RINGS and coord_val not in seen_ring_coords:
seen_ring_coords.add(coord_val)
locks.append({
"scope": "SCOPE2_S1_S6_RING_MIGRATION",
"metric_mode": label_mode,
"coordinate": coord_val,
"ring_partners": S1_S6_SIGNATURE_RINGS[coord_val],
"verified_equations": list(_EQ_CLOSURES_333.get(coord_val, [])),
})
if coord_val == 129:
emergent_m7_quant_triggers.append({
"symbol": sym,
"coordinate": 129,
"metric_mode": label_mode,
"partners": S1_S6_SIGNATURE_RINGS[129],
})
vol_ratio = float(item["volume_ratio_20d"]) if item.get("volume_ratio_20d") is not None else None
chg_pct = float(chg_pct_raw) if chg_pct_raw is not None else None
if vol_ratio is not None and chg_pct is not None and vol_ratio < 0.45 and abs(chg_pct) < 0.10:
active_memetic_states.add("M1_ENTROPIC_STAGNATION")
if (chg_pct is not None and chg_pct <= -5.0) or (vol_ratio is not None and vol_ratio >= 2.5) or (sym == "^VIX" and close_int >= 25):
active_memetic_states.add("M2_FLASH_CRASH_TEMPLEX_SURGE")
if mcap_s.endswith("T"):
active_memetic_states.add("M3_LEVIATHAN_TRILLION_CAP_CONCENTRATION")
if co_present and locks:
locks.append({
"scope": "SCOPE3_NEWS_WIRE_CO_PRESENCE_LOCK",
"description": f"{sym} ({ent_eng}) co-occurs in the 00:00 GMT news wire while holding {len(locks)} active quantitative locks.",
"matched_headlines": news_entities[sym],
})
instruments_out.append({
"symbol": sym,
"symbol_clean": sym_clean,
"symbol_eng_aq": sym_eng_aq,
"symbol_ing": sym_ing,
"symbol_ing_aq": sym_ing_aq,
"entity_eng": ent_eng,
"entity_ing": ent_ing,
"entity_eng_aq": ent_eng_aq,
"entity_ing_aq": ent_ing_aq,
"guilds": item["guilds"],
"data_available": True,
"status": "ok",
"feed_source": item.get("feed_source") or "real_market_cache",
"observation_date_utc": item.get("observation_date_utc"),
"co_present_in_news_wire": co_present,
"metrics": {
"close_usd": close_val,
"change_pct": chg_pct,
"change_bps": int(chg_bps_raw) if chg_bps_raw is not None else None,
"volume_ratio_20d": vol_ratio,
"market_cap_str": mcap_s,
},
"quant_encodings": {
"status": "ok",
"close_digit_aq": close_dig_aq,
"close_spoken_eng": close_sp_eng,
"close_spoken_eng_aq": close_sp_eng_aq,
"close_spoken_ing": close_sp_ing,
"close_spoken_ing_aq": close_sp_aq,
"close_spoken_prime_rank": prime_rank(close_sp_aq),
"scaled_cap_spoken_eng": mcap_sp_eng,
"scaled_cap_spoken_eng_aq": mcap_sp_eng_aq,
"scaled_cap_spoken_ing": mcap_sp_ing,
"scaled_cap_spoken_ing_aq": mcap_sp_aq,
"bps_digit_aq": bps_dig_aq,
"bps_spoken_eng": bps_sp_eng,
"bps_spoken_eng_aq": bps_sp_eng_aq,
"bps_spoken_ing": bps_sp_ing,
"bps_spoken_ing_aq": bps_sp_aq,
},
"contingent_locks": locks,
})
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": target_dt_utc,
"harvest_mode": harvest_mode,
"synthetic_data_eliminated": True,
"regime_summary": {
"instrument_count": len(instruments_out),
"instruments_with_data_count": available_count,
"instruments_without_data": unavailable_syms,
"total_contingent_locks": sum(len(x["contingent_locks"]) for x in instruments_out),
"vix_close": vix_close_val if vix_close_val is not None else NO_DATA_AVAILABLE,
"us10y_yield_pct": us10y_yield_val if us10y_yield_val is not None else NO_DATA_AVAILABLE,
"news_wire_co_present_symbols": sorted(news_entities.keys()),
"active_memetic_states": sorted(active_memetic_states),
"emergent_m7_quant_triggers": emergent_m7_quant_triggers,
},
"instruments": instruments_out,
"anchor_revisions_detected": [],
"isolation_receipt": receipt,
}
payload["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(payload)}
return payload
def synthesize_quant_dossier_markdown(payload: dict[str, Any]) -> str:
"""Format a Markdown report strictly from real observed harvest data (stating 'No data available' when absent)."""
dt = payload["target_date_utc"]
mode = payload["harvest_mode"]
cid = payload["ipld_dag_json_cidv1"]["/"]
reg = payload["regime_summary"]
lines = [
f"# Dossier: Quantitative Financial Telemetry & Contingent Meaning (`{dt}` • `{mode}`)",
"",
f"- **Target Date (UTC):** `{dt}`",
f"- **Harvest Mode:** `{mode}`",
f"- **Instruments Audited:** `{reg['instrument_count']}` (`{reg.get('instruments_with_data_count', 0)}` with market data; `{', '.join(reg.get('instruments_without_data', [])) or 'none'}`: No data available)",
f"- **Total Contingent Locks:** `{reg['total_contingent_locks']}`",
f"- **Active Memetic States:** `{', '.join(reg['active_memetic_states']) or 'None'}`",
f"- **IPLD `dag-json` `CIDv1`:** `{cid}`",
"",
"## 1. Instrument Telemetry & Observed Locks",
"",
"| Symbol | Entity (`Gen 0 -> Gen 1`) | Close (USD) | Spoken Close (`Gen 1` AQ) | Change (bps) | Status / Active Contingent Locks |",
"| :--- | :--- | :---: | :--- | :---: | :--- |",
]
for inst in payload["instruments"]:
if not inst.get("data_available"):
lines.append(
f"| `{inst['symbol']}` | `{inst['entity_eng']} -> {inst['entity_ing']}` (`{inst['entity_eng_aq']}->{inst['entity_ing_aq']}`) | "
f"*{NO_DATA_AVAILABLE}* | *{NO_DATA_AVAILABLE}* | *{NO_DATA_AVAILABLE}* | {inst.get('status', NO_DATA_AVAILABLE)} |"
)
continue
q = inst["quant_encodings"]
lock_strs = "; ".join(
l.get("description") or f"{l['scope']} ({l.get('coordinate')} -> {', '.join(l.get('ring_partners', []))})"
for l in inst["contingent_locks"]
) or "No locks triggered"
bps_disp = inst["metrics"]["change_bps"] if inst["metrics"]["change_bps"] is not None else NO_DATA_AVAILABLE
lines.append(
f"| `{inst['symbol']}` | `{inst['entity_eng']} -> {inst['entity_ing']}` (`{inst['entity_eng_aq']}->{inst['entity_ing_aq']}`) | "
f"`${inst['metrics']['close_usd']}` | `{q['close_spoken_ing']}` (`{q['close_spoken_ing_aq']}`) | "
f"`{bps_disp}` | {lock_strs} |"
)
lines.append("")
return "\n".join(lines)
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`, 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
cfg = load_workspace_config()
h_path = Path(history_path) if history_path else (cfg.core_dir / "site" / "quant" / "real-market-history.json")
if h_path.is_file():
doc = load_json_cached(h_path, copy_result=True)
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
for item in CANONICAL_WATCHLIST_24:
sym = item["symbol"]
if sym == "ANTHR-PVT":
inst_map[sym] = {
"symbol": sym,
"data_available": False,
"status": NO_DATA_AVAILABLE,
"bars_by_date": {},
}
continue
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 < MIN_SCOPE_DATE_UTC or d > effective_max_date
]:
del bars_by_dt[stale_dt]
else:
for stale_dt in [d for d in list(bars_by_dt.keys()) if d < MIN_SCOPE_DATE_UTC]:
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 dt_s < MIN_SCOPE_DATE_UTC:
continue
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:
series = _fetch_yahoo_chart_series(
sym, min_date_utc=MIN_SCOPE_DATE_UTC, max_date_utc=effective_max_date
) or _fetch_stooq_csv_series(
sym, min_date_utc=MIN_SCOPE_DATE_UTC, max_date_utc=effective_max_date
)
for dt_s, b_obj in sorted(series.items()):
if dt_s < MIN_SCOPE_DATE_UTC:
continue
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
else:
if prev_bar.get("volume_ratio_20d") is None and b_obj.get("volume_ratio_20d") is not None:
prev_bar["volume_ratio_20d"] = b_obj["volume_ratio_20d"]
if prev_bar.get("change_pct") is None and b_obj.get("change_pct") is not None:
prev_bar["change_pct"] = b_obj["change_pct"]
prev_bar["change_bps"] = b_obj["change_bps"]
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)
h_path.write_text(json.dumps(doc, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
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 _excavate_git_json_versions(
repo_dir: Path,
rel_path: str,
max_commits: int = 35,
) -> list[dict[str, Any]]:
"""
Excavate valid JSON versions of `rel_path` from all Git stashes (`stash@{0..N}` and
untracked stash parents `stash@{i}^3`) and recent Git commits (`git log --all`).
"""
import subprocess
if not (repo_dir / ".git").exists():
return []
revs: list[str] = []
try:
stash_out = subprocess.run(
["git", "-C", str(repo_dir), "stash", "list", "--format=%gd"],
capture_output=True,
text=True,
check=False,
).stdout
for s_ref in [ln.strip() for ln in stash_out.splitlines() if ln.strip()]:
revs.append(s_ref)
revs.append(f"{s_ref}^3")
except Exception:
pass
try:
log_out = subprocess.run(
["git", "-C", str(repo_dir), "log", "--all", f"-n{max_commits}", "--format=%H", "--", rel_path],
capture_output=True,
text=True,
check=False,
).stdout
for sha in [ln.strip() for ln in log_out.splitlines() if ln.strip()]:
if sha not in revs:
revs.append(sha)
except Exception:
pass
docs: list[dict[str, Any]] = []
for rev in revs:
try:
proc = subprocess.run(
["git", "-C", str(repo_dir), "show", f"{rev}:{rel_path}"],
capture_output=True,
text=True,
check=False,
)
if proc.returncode == 0 and proc.stdout.strip():
obj = json.loads(proc.stdout)
if isinstance(obj, dict):
docs.append(obj)
except Exception:
continue
return docs
def snapshot_local_telemetry(
snapshot_dir: str | Path,
quant_dir: str | Path | None = None,
excavate_git: bool = True,
) -> 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.
When `excavate_git=True` on the repository's `site/quant` directory, also excavates
any observations present in `git stash list` or `git log --all` (`>= 2026-11-01`).
"""
import shutil
cfg = load_workspace_config()
default_q_dir = cfg.core_dir / "site" / "quant"
q_dir = Path(quant_dir) if quant_dir else default_q_dir
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:
load_json_cached(src, copy_result=False)
shutil.copy2(src, s_dir / fname)
saved.append(fname)
except Exception:
continue
if excavate_git and q_dir.resolve() == default_q_dir.resolve() and (cfg.core_dir / ".git").exists():
max_dt = latest_completed_closing_bell_date_utc()
# 1. Excavate stashed/committed real-market-history.json bars (>= 2026-11-01)
snap_rmh_p = s_dir / "real-market-history.json"
if snap_rmh_p.is_file():
try:
base_rmh = load_json_cached(snap_rmh_p, copy_result=True)
insts = base_rmh.setdefault("instruments", {})
for hist_doc in _excavate_git_json_versions(cfg.core_dir, "site/quant/real-market-history.json"):
for sym, s_obj in (hist_doc.get("instruments") or {}).items():
if sym == "ANTHR-PVT" or not isinstance(s_obj, dict):
continue
t_entry = insts.setdefault(
sym, {"symbol": sym, "data_available": True, "status": "ok", "bars_by_date": {}}
)
t_bars = t_entry.setdefault("bars_by_date", {})
for dt_s, b_obj in (s_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 < MIN_SCOPE_DATE_UTC or dt_s > max_dt:
continue
if not isinstance(b_obj, dict) or b_obj.get("close_usd") is None:
continue
if dt_s not in t_bars or t_bars[dt_s].get("close_usd") is None:
t_bars[dt_s] = b_obj
else:
if not t_bars[dt_s].get("market_cap_str") and b_obj.get("market_cap_str"):
t_bars[dt_s]["market_cap_str"] = b_obj["market_cap_str"]
if t_bars[dt_s].get("volume_ratio_20d") is None and b_obj.get("volume_ratio_20d") is not None:
t_bars[dt_s]["volume_ratio_20d"] = b_obj["volume_ratio_20d"]
snap_rmh_p.write_text(json.dumps(base_rmh, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
except Exception:
pass
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
(`>= 2026-11-01` and `<= max_date_utc`) 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 = load_json_cached(snap_hist_p, copy_result=False)
cur_hist = load_json_cached(cur_hist_p, copy_result=True)
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 < MIN_SCOPE_DATE_UTC or 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
else:
if not cur_bars[dt_s].get("market_cap_str") and b_obj.get("market_cap_str"):
cur_bars[dt_s]["market_cap_str"] = b_obj["market_cap_str"]
merged_bars_count += 1
if cur_bars[dt_s].get("volume_ratio_20d") is None and b_obj.get("volume_ratio_20d") is not None:
cur_bars[dt_s]["volume_ratio_20d"] = b_obj["volume_ratio_20d"]
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 = load_json_cached(snap_macro_p, copy_result=False)
cur_macro = load_json_cached(cur_macro_p, copy_result=True)
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_utc") or o.get("date")): o
for o in cur_obs_list
if isinstance(o, dict) and (o.get("date_utc") or 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_utc") or o.get("date")) or o.get("value") is None:
continue
dt_s = str(o.get("date_utc") or o.get("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:
last_dt = latest_valid[-1].get("date_utc") or latest_valid[-1].get("date")
cur_series[s_key]["latest_date_utc"] = last_dt
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,
"min_scope_date_utc": MIN_SCOPE_DATE_UTC,
"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-pre-market-open", "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)
out_path = Path(args.out) if args.out else (cfg.core_dir / "site" / "quant" / "financial-aq-harvest-latest.json")
join_news = args.join_news or str(cfg.archive_dir / "news-aq-harvest-latest.json")
payload = build_financial_quant_harvest(
harvest_mode=args.mode,
snapshot_path=args.from_snapshot,
join_news_path=join_news,
live_fetch=args.live,
)
info = write_pretty_and_dag_json(out_path, payload)
if args.write_dossier:
d_path = Path(args.write_dossier)
d_path.parent.mkdir(parents=True, exist_ok=True)
d_path.write_text(synthesize_quant_dossier_markdown(payload), encoding="utf-8")
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
ts_bundle = build_quant_timeseries_bundle(write_files=True)
print(
json.dumps(
{
"output_path": str(out_path),
"harvest_mode": payload["harvest_mode"],
"instrument_count": payload["regime_summary"]["instrument_count"],
"instruments_with_data_count": payload["regime_summary"]["instruments_with_data_count"],
"instruments_without_data": payload["regime_summary"]["instruments_without_data"],
"total_contingent_locks": payload["regime_summary"]["total_contingent_locks"],
"news_wire_co_present_symbols": payload["regime_summary"]["news_wire_co_present_symbols"],
"active_memetic_states": payload["regime_summary"]["active_memetic_states"],
"dag_json_cidv1": info["cidv1"],
"timeseries_cidv1": ts_bundle["ipld_dag_json_cidv1"]["/"],
"isolation_all_unchanged": payload["isolation_receipt"]["all_unchanged"],
},
indent=2,
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main())