Release v2.17.1: Implement Strategies A, B & C (git/stash telemetry excavator, IPv4 parallel FRED macro backfill with YoY metrics, and 3-month Yahoo/Stooq lookback with >= 2026-11-01 scope)
This commit is contained in:
1 parent
52153e76f0
commit
91cf671000
13 files changed
+2506
-411
No files matched your search
@@ -167,6 +167,9 @@ _EQ_CLOSURES_333: dict[int, list[str]] = {
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
@@ -181,17 +184,20 @@ def latest_completed_closing_bell_date_utc(now_utc: datetime.datetime | None = N
|
||||
|
||||
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 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`.
|
||||
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=1mo&interval=1d"
|
||||
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
|
||||
|
||||
@@ -216,6 +222,8 @@ def _fetch_yahoo_chart_series(
|
||||
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
|
||||
@@ -250,6 +258,7 @@ def _fetch_yahoo_chart(symbol: str, timeout: float = 6.0) -> dict[str, Any] | No
|
||||
"""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,
|
||||
)
|
||||
@@ -261,10 +270,11 @@ def _fetch_yahoo_chart(symbol: str, timeout: float = 6.0) -> dict[str, Any] | No
|
||||
|
||||
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."""
|
||||
"""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 {}
|
||||
@@ -282,10 +292,12 @@ def _fetch_stooq_csv_series(
|
||||
return {}
|
||||
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
start_idx = max(0, len(raw_rows) - 35)
|
||||
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"])
|
||||
@@ -873,11 +885,18 @@ def update_real_market_history_cache(
|
||||
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]:
|
||||
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:
|
||||
@@ -885,10 +904,14 @@ def update_real_market_history_cache(
|
||||
appended_count += 1
|
||||
elif allow_live_network:
|
||||
try:
|
||||
series = _fetch_yahoo_chart_series(sym, max_date_utc=effective_max_date) or _fetch_stooq_csv_series(
|
||||
sym, max_date_utc=effective_max_date
|
||||
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)
|
||||
@@ -905,6 +928,12 @@ def update_real_market_history_cache(
|
||||
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
|
||||
|
||||
@@ -925,18 +954,79 @@ _TELEMETRY_SNAPSHOT_FILES: tuple[str, ...] = (
|
||||
)
|
||||
|
||||
|
||||
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()
|
||||
q_dir = Path(quant_dir) if quant_dir else (cfg.core_dir / "site" / "quant")
|
||||
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] = []
|
||||
@@ -949,6 +1039,41 @@ def snapshot_local_telemetry(
|
||||
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 = json.loads(snap_rmh_p.read_text(encoding="utf-8"))
|
||||
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}
|
||||
|
||||
|
||||
@@ -959,8 +1084,9 @@ def reconcile_telemetry_snapshot(
|
||||
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).
|
||||
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.
|
||||
"""
|
||||
@@ -989,13 +1115,20 @@ def reconcile_telemetry_snapshot(
|
||||
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:
|
||||
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")
|
||||
@@ -1013,12 +1146,16 @@ def reconcile_telemetry_snapshot(
|
||||
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")}
|
||||
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") or o.get("value") is None:
|
||||
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["date"])
|
||||
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:
|
||||
@@ -1030,7 +1167,8 @@ def reconcile_telemetry_snapshot(
|
||||
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"]
|
||||
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")
|
||||
@@ -1056,6 +1194,7 @@ def reconcile_telemetry_snapshot(
|
||||
"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,
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user