feat(quant): implement Plan #72 pre-market-open daily brief & dual-calendar VPS cadence
This commit is contained in:
1 parent
3945e3648a
commit
d4b7502501
8 files changed
+165
-16
No files matched your search
@@ -187,7 +187,7 @@ MCP_TOOLS_SCHEMA: list[dict[str, Any]] = [
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"harvest_mode": {"type": "string", "enum": ["us-closing-bell", "utc-rollover"], "default": "us-closing-bell"},
|
||||
"harvest_mode": {"type": "string", "enum": ["us-pre-market-open", "us-closing-bell", "utc-rollover"], "default": "us-closing-bell"},
|
||||
"symbol_filter": {"type": "string", "default": "", "description": "Optional ticker symbol filter (e.g. 'NVDA', 'ASML', 'BTC-USD')."},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1201,7 +1201,7 @@ def reconcile_telemetry_snapshot(
|
||||
|
||||
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("--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.")
|
||||
|
||||
@@ -27,6 +27,28 @@ from hyperstitionstud_io.quant.macro import build_macro_indicators_bundle
|
||||
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
|
||||
|
||||
|
||||
SESSION_WINDOWS = ("us-pre-market-open", "us-closing-bell", "utc-rollover")
|
||||
|
||||
|
||||
def _resolve_session_window(
|
||||
session_window: str | None = None,
|
||||
now_utc: datetime.datetime | None = None,
|
||||
) -> str:
|
||||
if session_window and session_window != "auto":
|
||||
if session_window not in SESSION_WINDOWS:
|
||||
raise ValueError(f"Unsupported session_window {session_window!r}; expected one of {SESSION_WINDOWS} or 'auto'.")
|
||||
return session_window
|
||||
dt = now_utc or datetime.datetime.now(datetime.timezone.utc)
|
||||
hour = dt.hour
|
||||
if 13 <= hour <= 15:
|
||||
return "us-pre-market-open"
|
||||
if 21 <= hour <= 23:
|
||||
return "us-closing-bell"
|
||||
if 0 <= hour <= 2:
|
||||
return "utc-rollover"
|
||||
return "us-closing-bell"
|
||||
|
||||
|
||||
def _find_latest_available_bar(inst: dict[str, Any]) -> dict[str, Any] | None:
|
||||
bars = [b for b in (inst.get("bars") or []) if b.get("data_available") and b.get("close_usd") is not None]
|
||||
return bars[-1] if bars else None
|
||||
@@ -143,8 +165,10 @@ def _compute_bayesian_regime_update(
|
||||
def build_daily_portfolio_brief(
|
||||
allow_live_network: bool = False,
|
||||
write_files: bool = True,
|
||||
session_window: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
cfg = load_workspace_config()
|
||||
resolved_window = _resolve_session_window(session_window)
|
||||
ts_bundle = build_quant_timeseries_bundle(write_files=False)
|
||||
macro_bundle = build_macro_indicators_bundle(allow_live_network=allow_live_network, write_files=False)
|
||||
|
||||
@@ -288,6 +312,7 @@ def build_daily_portfolio_brief(
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:daily-portfolio-brief",
|
||||
"version": CURRENT_VERSION,
|
||||
"run_number": run_number,
|
||||
"session_window": resolved_window,
|
||||
"generated_at_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"synthetic_data_eliminated": True,
|
||||
"agenda_1_executive_summary": {
|
||||
@@ -454,32 +479,62 @@ def build_daily_portfolio_brief(
|
||||
js_body = "// Auto-generated by hyperstitionstud_io.quant.daily_brief — DO NOT EDIT MANUALLY\nwindow.HYPERSTITION_DAILY_BRIEF = " + json.dumps(brief_payload, ensure_ascii=False) + ";\n"
|
||||
out_js_path.write_text(js_body, encoding="utf-8")
|
||||
|
||||
# Update append-only Bayesian state ledger outside read-only files (deduplicating same-day identical posteriors)
|
||||
# Update append-only Bayesian state ledger outside read-only files
|
||||
# Deduplicate entries matching BOTH calendar day (generated_at_utc[:10]) AND session_window
|
||||
raw_history = list(prior_state.get("run_history") or [])
|
||||
dedup_history: list[dict[str, Any]] = []
|
||||
for entry in raw_history:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
e_dt = str(entry.get("generated_at_utc") or "")[:10]
|
||||
e_win = entry.get("session_window")
|
||||
e_post = entry.get("posterior_probabilities")
|
||||
if dedup_history and str(dedup_history[-1].get("generated_at_utc") or "")[:10] == e_dt and dedup_history[-1].get("posterior_probabilities") == e_post:
|
||||
if e_win is not None:
|
||||
match_idx = next(
|
||||
(
|
||||
i
|
||||
for i, prev in enumerate(dedup_history)
|
||||
if str(prev.get("generated_at_utc") or "")[:10] == e_dt and prev.get("session_window") == e_win
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match_idx is not None:
|
||||
dedup_history[match_idx] = entry
|
||||
else:
|
||||
dedup_history.append(entry)
|
||||
elif (
|
||||
dedup_history
|
||||
and dedup_history[-1].get("session_window") is None
|
||||
and str(dedup_history[-1].get("generated_at_utc") or "")[:10] == e_dt
|
||||
and dedup_history[-1].get("posterior_probabilities") == e_post
|
||||
):
|
||||
dedup_history[-1] = entry
|
||||
else:
|
||||
dedup_history.append(entry)
|
||||
cur_dt_10 = str(brief_payload["generated_at_utc"])[:10]
|
||||
cur_post = bayesian_block["posterior_probabilities"]
|
||||
if dedup_history and str(dedup_history[-1].get("generated_at_utc") or "")[:10] == cur_dt_10 and dedup_history[-1].get("posterior_probabilities") == cur_post:
|
||||
dedup_history[-1] = {
|
||||
"run_number": int(dedup_history[-1].get("run_number") or len(dedup_history)),
|
||||
cur_match_idx = next(
|
||||
(
|
||||
i
|
||||
for i, prev in enumerate(dedup_history)
|
||||
if str(prev.get("generated_at_utc") or "")[:10] == cur_dt_10 and prev.get("session_window") == resolved_window
|
||||
),
|
||||
None,
|
||||
)
|
||||
if cur_match_idx is not None:
|
||||
dedup_history[cur_match_idx] = {
|
||||
"run_number": int(dedup_history[cur_match_idx].get("run_number") or (cur_match_idx + 1)),
|
||||
"session_window": resolved_window,
|
||||
"generated_at_utc": brief_payload["generated_at_utc"],
|
||||
"posterior_probabilities": cur_post,
|
||||
"question_id": str(dedup_history[-1].get("question_id") or current_question["question_id"]),
|
||||
"question_id": str(dedup_history[cur_match_idx].get("question_id") or current_question["question_id"]),
|
||||
"cidv1": brief_payload["ipld_dag_json_cidv1"]["/"],
|
||||
}
|
||||
else:
|
||||
next_run_num = (int(dedup_history[-1].get("run_number") or len(dedup_history)) + 1) if dedup_history else 1
|
||||
dedup_history.append({
|
||||
"run_number": next_run_num,
|
||||
"session_window": resolved_window,
|
||||
"generated_at_utc": brief_payload["generated_at_utc"],
|
||||
"posterior_probabilities": cur_post,
|
||||
"question_id": f"Q-RUN-{next_run_num:04d}",
|
||||
@@ -492,10 +547,11 @@ def build_daily_portfolio_brief(
|
||||
new_state = {
|
||||
"version": CURRENT_VERSION,
|
||||
"run_number": effective_run_number,
|
||||
"session_window": resolved_window,
|
||||
"updated_at_utc": brief_payload["generated_at_utc"],
|
||||
"latest_posteriors": bayesian_block["posterior_probabilities"],
|
||||
"active_daily_question": current_question,
|
||||
"run_history": dedup_history[-30:],
|
||||
"run_history": dedup_history[-60:],
|
||||
}
|
||||
state_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
state_path.write_text(json.dumps(new_state, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
@@ -506,14 +562,27 @@ def build_daily_portfolio_brief(
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(prog="hs-daily-brief", description="Generate the 5-Agenda Zero-Synthetic-Data Daily Portfolio & Memetic Regime Update.")
|
||||
ap.add_argument("--live-macro", action="store_true", help="Fetch fresh FRED CSV series before computing the daily brief.")
|
||||
ap.add_argument(
|
||||
"--window",
|
||||
"--session-window",
|
||||
dest="session_window",
|
||||
choices=["auto", "us-pre-market-open", "us-closing-bell", "utc-rollover"],
|
||||
default="auto",
|
||||
help="Session window tag (default: auto-detected from UTC hour).",
|
||||
)
|
||||
args = ap.parse_args(argv)
|
||||
brief = build_daily_portfolio_brief(allow_live_network=args.live_macro, write_files=True)
|
||||
brief = build_daily_portfolio_brief(
|
||||
allow_live_network=args.live_macro,
|
||||
write_files=True,
|
||||
session_window=args.session_window,
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"ok": True,
|
||||
"version": brief["version"],
|
||||
"run_number": brief["run_number"],
|
||||
"session_window": brief["session_window"],
|
||||
"posteriors": brief["agenda_1_executive_summary"]["bayesian_regime_inference"]["posterior_probabilities"],
|
||||
"question_id": brief["agenda_5_daily_key_macro_question_and_rigor"]["active_daily_question"]["question_id"],
|
||||
"cidv1": brief["ipld_dag_json_cidv1"]["/"],
|
||||
|
||||
Reference in new issue
Block a user