Spaces:
Running
Running
Sync from GitHub (tests passed)
Browse files- app/db.py +32 -1
- app/main.py +256 -103
- app/models.py +13 -0
- app/schemas.py +8 -0
- app/tft_explain.py +314 -0
- deep_learning/inference/predictor.py +75 -5
- deep_learning/models/tft_copper.py +143 -35
- deep_learning/training/trainer.py +35 -0
- worker/tasks.py +85 -30
app/db.py
CHANGED
|
@@ -8,7 +8,7 @@ import logging
|
|
| 8 |
from contextlib import contextmanager
|
| 9 |
from typing import Generator
|
| 10 |
|
| 11 |
-
from sqlalchemy import create_engine, event, text
|
| 12 |
from sqlalchemy.orm import sessionmaker, Session, declarative_base
|
| 13 |
|
| 14 |
from app.settings import get_settings
|
|
@@ -32,6 +32,11 @@ WEEKLY_DAILY_SENTIMENT_COLUMNS = (
|
|
| 32 |
|
| 33 |
TFT_MODEL_METADATA_COLUMNS = (
|
| 34 |
("quality_gate_passed", "BOOLEAN", "BOOLEAN"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
)
|
| 36 |
|
| 37 |
PRODUCTION_FLOW_AI_COMMENTARY_COLUMNS = (
|
|
@@ -450,6 +455,32 @@ def _run_migrations(engine):
|
|
| 450 |
logger.exception("Migration failed for TFT model promotion schema")
|
| 451 |
raise
|
| 452 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
try:
|
| 454 |
_ensure_production_flow_schema(conn, is_sqlite)
|
| 455 |
conn.commit()
|
|
|
|
| 8 |
from contextlib import contextmanager
|
| 9 |
from typing import Generator
|
| 10 |
|
| 11 |
+
from sqlalchemy import create_engine, event, inspect, text
|
| 12 |
from sqlalchemy.orm import sessionmaker, Session, declarative_base
|
| 13 |
|
| 14 |
from app.settings import get_settings
|
|
|
|
| 32 |
|
| 33 |
TFT_MODEL_METADATA_COLUMNS = (
|
| 34 |
("quality_gate_passed", "BOOLEAN", "BOOLEAN"),
|
| 35 |
+
("importance_json", "TEXT", "TEXT"),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
TFT_PREDICTION_SNAPSHOT_COLUMNS = (
|
| 39 |
+
("explain_json", "JSON", "JSON"),
|
| 40 |
)
|
| 41 |
|
| 42 |
PRODUCTION_FLOW_AI_COMMENTARY_COLUMNS = (
|
|
|
|
| 455 |
logger.exception("Migration failed for TFT model promotion schema")
|
| 456 |
raise
|
| 457 |
|
| 458 |
+
# Only a missing snapshot table is tolerated (init_db creates it before
|
| 459 |
+
# migrations run, but ad-hoc migration passes must not fail on it);
|
| 460 |
+
# any other failure is a real schema error and must surface loudly.
|
| 461 |
+
try:
|
| 462 |
+
if inspect(conn).has_table("tft_prediction_snapshots"):
|
| 463 |
+
_ensure_columns(
|
| 464 |
+
conn,
|
| 465 |
+
"tft_prediction_snapshots",
|
| 466 |
+
TFT_PREDICTION_SNAPSHOT_COLUMNS,
|
| 467 |
+
is_sqlite,
|
| 468 |
+
)
|
| 469 |
+
conn.commit()
|
| 470 |
+
logger.info(
|
| 471 |
+
"Migration: Ensured TFT prediction snapshot explain schema exists"
|
| 472 |
+
)
|
| 473 |
+
else:
|
| 474 |
+
logger.debug(
|
| 475 |
+
"Migration skipped: tft_prediction_snapshots table does not exist"
|
| 476 |
+
)
|
| 477 |
+
except Exception:
|
| 478 |
+
conn.rollback()
|
| 479 |
+
logger.exception(
|
| 480 |
+
"Migration failed for TFT prediction snapshot explain schema"
|
| 481 |
+
)
|
| 482 |
+
raise
|
| 483 |
+
|
| 484 |
try:
|
| 485 |
_ensure_production_flow_schema(conn, is_sqlite)
|
| 486 |
conn.commit()
|
app/main.py
CHANGED
|
@@ -19,7 +19,7 @@ logging.getLogger("httpcore").setLevel(logging.WARNING)
|
|
| 19 |
from contextlib import asynccontextmanager
|
| 20 |
from datetime import date, datetime, timedelta, timezone
|
| 21 |
from pathlib import Path
|
| 22 |
-
from typing import Optional
|
| 23 |
|
| 24 |
from fastapi import FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect, Depends, Header, BackgroundTasks, Request, Response
|
| 25 |
from fastapi.middleware.cors import CORSMiddleware
|
|
@@ -1179,6 +1179,99 @@ def _latest_price_bar_date(session, symbol: str) -> Optional[date]:
|
|
| 1179 |
return None
|
| 1180 |
|
| 1181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1182 |
@app.get(
|
| 1183 |
"/api/analysis/tft/{symbol}",
|
| 1184 |
summary="Get TFT-ASRO deep learning analysis",
|
|
@@ -1224,22 +1317,7 @@ async def get_tft_analysis(
|
|
| 1224 |
# --- 1. Try persisted snapshot ------------------------------------------
|
| 1225 |
if source == "snapshot":
|
| 1226 |
try:
|
| 1227 |
-
from app.models import TFTPredictionSnapshot
|
| 1228 |
-
|
| 1229 |
-
def _as_utc(dt: Optional[datetime]) -> Optional[datetime]:
|
| 1230 |
-
if dt is None:
|
| 1231 |
-
return None
|
| 1232 |
-
if dt.tzinfo is None:
|
| 1233 |
-
return dt.replace(tzinfo=timezone.utc)
|
| 1234 |
-
return dt
|
| 1235 |
-
|
| 1236 |
-
def _parse_ref_date(value: Optional[str]) -> Optional[date]:
|
| 1237 |
-
if not value:
|
| 1238 |
-
return None
|
| 1239 |
-
try:
|
| 1240 |
-
return datetime.strptime(value[:10], "%Y-%m-%d").date()
|
| 1241 |
-
except Exception:
|
| 1242 |
-
return None
|
| 1243 |
|
| 1244 |
with SessionLocal() as session:
|
| 1245 |
latest_price_date = _latest_price_bar_date(session, symbol)
|
|
@@ -1251,70 +1329,24 @@ async def get_tft_analysis(
|
|
| 1251 |
)
|
| 1252 |
if latest is not None and isinstance(latest.payload_json, dict):
|
| 1253 |
payload = dict(latest.payload_json)
|
| 1254 |
-
gen_at = latest.generated_at
|
| 1255 |
-
|
| 1256 |
-
|
| 1257 |
-
# snapshot. A failed model being newer must NOT force live
|
| 1258 |
-
# inference, since that would serve a rejected checkpoint.
|
| 1259 |
-
model_meta = (
|
| 1260 |
-
session.query(TFTModelMetadata)
|
| 1261 |
-
.filter(
|
| 1262 |
-
TFTModelMetadata.symbol == symbol,
|
| 1263 |
-
TFTModelMetadata.quality_gate_passed.is_(True),
|
| 1264 |
-
)
|
| 1265 |
-
.order_by(TFTModelMetadata.trained_at.desc())
|
| 1266 |
-
.first()
|
| 1267 |
)
|
| 1268 |
-
trained_at = _as_utc(model_meta.trained_at) if model_meta else None
|
| 1269 |
-
|
| 1270 |
-
# Decide whether snapshot is still valid.
|
| 1271 |
-
should_fallback_live = False
|
| 1272 |
-
fallback_reasons: list[str] = []
|
| 1273 |
|
| 1274 |
-
if
|
| 1275 |
-
|
| 1276 |
-
|
| 1277 |
-
|
| 1278 |
-
|
| 1279 |
)
|
| 1280 |
-
|
| 1281 |
-
|
| 1282 |
-
|
| 1283 |
-
|
| 1284 |
-
|
| 1285 |
-
|
| 1286 |
-
|
| 1287 |
-
if ref_date is None:
|
| 1288 |
-
should_fallback_live = True
|
| 1289 |
-
fallback_reasons.append("snapshot reference_price_date missing")
|
| 1290 |
-
elif latest_price_date is not None and ref_date != latest_price_date:
|
| 1291 |
-
should_fallback_live = True
|
| 1292 |
-
fallback_reasons.append(
|
| 1293 |
-
"snapshot is not anchored to latest PriceBar "
|
| 1294 |
-
f"(snapshot={ref_date.isoformat()}, "
|
| 1295 |
-
f"latest_price_bar={latest_price_date.isoformat()})"
|
| 1296 |
-
)
|
| 1297 |
-
elif latest_price_date is None:
|
| 1298 |
-
# Defensive fallback for installations where PriceBar is
|
| 1299 |
-
# temporarily unavailable. Normally the exact market-bar
|
| 1300 |
-
# comparison above is authoritative and naturally handles
|
| 1301 |
-
# weekends and exchange holidays.
|
| 1302 |
-
staleness_days = (datetime.now(timezone.utc).date() - ref_date).days
|
| 1303 |
-
if staleness_days >= 3:
|
| 1304 |
-
should_fallback_live = True
|
| 1305 |
-
fallback_reasons.append(
|
| 1306 |
-
f"reference_price_date stale ({reference_price_date}, {staleness_days}d)"
|
| 1307 |
-
)
|
| 1308 |
-
|
| 1309 |
-
if not should_fallback_live:
|
| 1310 |
-
if isinstance(prediction, dict):
|
| 1311 |
-
payload.setdefault("primary_horizon", "5D")
|
| 1312 |
-
payload.setdefault("primary_forecast_return", prediction.get("weekly_return"))
|
| 1313 |
-
payload.setdefault("primary_forecast_q10", prediction.get("weekly_return_q10_calibrated"))
|
| 1314 |
-
payload.setdefault("primary_forecast_q90", prediction.get("weekly_return_q90_calibrated"))
|
| 1315 |
-
payload.setdefault("t1_return", prediction.get("predicted_return_median"))
|
| 1316 |
-
payload.setdefault("t1_impulse", payload.get("t1_impulse"))
|
| 1317 |
-
payload.setdefault("return_space", prediction.get("return_space"))
|
| 1318 |
payload["source"] = "snapshot"
|
| 1319 |
payload["snapshot_generated_at"] = (
|
| 1320 |
gen_at.isoformat() if gen_at else None
|
|
@@ -1386,6 +1418,80 @@ async def get_tft_analysis(
|
|
| 1386 |
raise HTTPException(status_code=500, detail=str(exc))
|
| 1387 |
|
| 1388 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1389 |
@app.get("/", include_in_schema=False)
|
| 1390 |
async def root_redirect():
|
| 1391 |
"""Redirect root to API docs."""
|
|
@@ -1720,6 +1826,76 @@ async def get_tft_summary(
|
|
| 1720 |
out[k] = num
|
| 1721 |
return out
|
| 1722 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1723 |
with SessionLocal() as session:
|
| 1724 |
# This endpoint describes the active/promoted model. Rejected candidate
|
| 1725 |
# metrics remain in the GitHub run artifact and must never replace the
|
|
@@ -1742,32 +1918,8 @@ async def get_tft_summary(
|
|
| 1742 |
config = _safe_json_load(meta.config_json)
|
| 1743 |
metrics_raw = _safe_json_load(meta.metrics_json)
|
| 1744 |
metrics = _numeric_map(metrics_raw)
|
| 1745 |
-
|
| 1746 |
-
# Variable importance not directly in TFTModelMetadata yet, extract from latest artifacts if available
|
| 1747 |
-
# But we can try to find it in the artifacts folder
|
| 1748 |
-
variable_importance = []
|
| 1749 |
-
try:
|
| 1750 |
-
import pathlib
|
| 1751 |
-
from .features import describe_feature
|
| 1752 |
|
| 1753 |
-
|
| 1754 |
-
mrmr_path = artifact_dir / "latest" / "mrmr_results.json"
|
| 1755 |
-
if mrmr_path.exists():
|
| 1756 |
-
mrmr_data = json.loads(mrmr_path.read_text(encoding="utf-8"))
|
| 1757 |
-
for feat, imp in mrmr_data.get("scores", {}).items():
|
| 1758 |
-
meta_desc = describe_feature(feat)
|
| 1759 |
-
variable_importance.append({
|
| 1760 |
-
"feature": feat,
|
| 1761 |
-
"importance": float(imp),
|
| 1762 |
-
"label": meta_desc["label"],
|
| 1763 |
-
"description": meta_desc["description"],
|
| 1764 |
-
"category": meta_desc["category"],
|
| 1765 |
-
"time_horizon": meta_desc.get("time_horizon", ""),
|
| 1766 |
-
})
|
| 1767 |
-
variable_importance.sort(key=lambda x: x["importance"], reverse=True)
|
| 1768 |
-
variable_importance = variable_importance[:20]
|
| 1769 |
-
except Exception as e:
|
| 1770 |
-
logger.warning(f"Could not load variable importance: {e}")
|
| 1771 |
|
| 1772 |
da = float(metrics.get("directional_accuracy", 0.5))
|
| 1773 |
sharpe = float(metrics.get("sharpe_ratio", 0.0))
|
|
@@ -1836,6 +1988,7 @@ async def get_tft_summary(
|
|
| 1836 |
"config": config,
|
| 1837 |
"metrics": metrics,
|
| 1838 |
"variable_importance": variable_importance,
|
|
|
|
| 1839 |
"quality_gate": {
|
| 1840 |
"passed": passed,
|
| 1841 |
"reasons": reasons,
|
|
|
|
| 19 |
from contextlib import asynccontextmanager
|
| 20 |
from datetime import date, datetime, timedelta, timezone
|
| 21 |
from pathlib import Path
|
| 22 |
+
from typing import Any, Dict, Optional
|
| 23 |
|
| 24 |
from fastapi import FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect, Depends, Header, BackgroundTasks, Request, Response
|
| 25 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 1179 |
return None
|
| 1180 |
|
| 1181 |
|
| 1182 |
+
def _as_utc(dt: Optional[datetime]) -> Optional[datetime]:
|
| 1183 |
+
"""Treat naive persisted timestamps as UTC."""
|
| 1184 |
+
if dt is None:
|
| 1185 |
+
return None
|
| 1186 |
+
if dt.tzinfo is None:
|
| 1187 |
+
return dt.replace(tzinfo=timezone.utc)
|
| 1188 |
+
return dt
|
| 1189 |
+
|
| 1190 |
+
|
| 1191 |
+
def _parse_ref_date(value: Optional[str]) -> Optional[date]:
|
| 1192 |
+
"""Parse a `YYYY-MM-DD` snapshot reference date, tolerating malformed values."""
|
| 1193 |
+
if not value:
|
| 1194 |
+
return None
|
| 1195 |
+
try:
|
| 1196 |
+
return datetime.strptime(value[:10], "%Y-%m-%d").date()
|
| 1197 |
+
except Exception:
|
| 1198 |
+
return None
|
| 1199 |
+
|
| 1200 |
+
|
| 1201 |
+
def _tft_snapshot_invalid_reasons(
|
| 1202 |
+
session,
|
| 1203 |
+
symbol: str,
|
| 1204 |
+
snapshot,
|
| 1205 |
+
latest_price_date: Optional[date] = None,
|
| 1206 |
+
) -> list[str]:
|
| 1207 |
+
"""
|
| 1208 |
+
Freshness reasons that make a TFT snapshot unsafe to serve.
|
| 1209 |
+
|
| 1210 |
+
Mirrors the snapshot-first contract of `/api/analysis/tft/{symbol}`: an
|
| 1211 |
+
empty list means no currently-promoted (quality-gate-passed) model is
|
| 1212 |
+
newer than the snapshot, and the snapshot is anchored to the latest
|
| 1213 |
+
PriceBar. Note this does not verify that a gate-passed model row exists at
|
| 1214 |
+
all — when the metadata table has no such row the test is vacuous by
|
| 1215 |
+
design (there is nothing newer to compare against).
|
| 1216 |
+
"""
|
| 1217 |
+
from app.models import TFTModelMetadata
|
| 1218 |
+
|
| 1219 |
+
reasons: list[str] = []
|
| 1220 |
+
gen_at = _as_utc(snapshot.generated_at)
|
| 1221 |
+
|
| 1222 |
+
# Only a quality-gate-passed model should invalidate the snapshot. A
|
| 1223 |
+
# failed model being newer must NOT force live inference, since that
|
| 1224 |
+
# would serve a rejected checkpoint.
|
| 1225 |
+
model_meta = (
|
| 1226 |
+
session.query(TFTModelMetadata)
|
| 1227 |
+
.filter(
|
| 1228 |
+
TFTModelMetadata.symbol == symbol,
|
| 1229 |
+
TFTModelMetadata.quality_gate_passed.is_(True),
|
| 1230 |
+
)
|
| 1231 |
+
.order_by(TFTModelMetadata.trained_at.desc())
|
| 1232 |
+
.first()
|
| 1233 |
+
)
|
| 1234 |
+
trained_at = _as_utc(model_meta.trained_at) if model_meta else None
|
| 1235 |
+
if trained_at and gen_at and trained_at > gen_at:
|
| 1236 |
+
reasons.append(
|
| 1237 |
+
"model trained after snapshot "
|
| 1238 |
+
f"(trained_at={trained_at.isoformat()} > snapshot_at={gen_at.isoformat()})"
|
| 1239 |
+
)
|
| 1240 |
+
|
| 1241 |
+
payload = snapshot.payload_json if isinstance(snapshot.payload_json, dict) else {}
|
| 1242 |
+
prediction = (
|
| 1243 |
+
payload.get("prediction")
|
| 1244 |
+
if isinstance(payload.get("prediction"), dict)
|
| 1245 |
+
else {}
|
| 1246 |
+
)
|
| 1247 |
+
reference_price_date = (
|
| 1248 |
+
snapshot.reference_price_date
|
| 1249 |
+
or prediction.get("reference_price_date")
|
| 1250 |
+
)
|
| 1251 |
+
ref_date = _parse_ref_date(reference_price_date)
|
| 1252 |
+
if latest_price_date is None:
|
| 1253 |
+
latest_price_date = _latest_price_bar_date(session, symbol)
|
| 1254 |
+
if ref_date is None:
|
| 1255 |
+
reasons.append("snapshot reference_price_date missing")
|
| 1256 |
+
elif latest_price_date is not None and ref_date != latest_price_date:
|
| 1257 |
+
reasons.append(
|
| 1258 |
+
"snapshot is not anchored to latest PriceBar "
|
| 1259 |
+
f"(snapshot={ref_date.isoformat()}, "
|
| 1260 |
+
f"latest_price_bar={latest_price_date.isoformat()})"
|
| 1261 |
+
)
|
| 1262 |
+
elif latest_price_date is None:
|
| 1263 |
+
# Defensive fallback for installations where PriceBar is temporarily
|
| 1264 |
+
# unavailable. Normally the exact market-bar comparison above is
|
| 1265 |
+
# authoritative and naturally handles weekends and exchange holidays.
|
| 1266 |
+
staleness_days = (datetime.now(timezone.utc).date() - ref_date).days
|
| 1267 |
+
if staleness_days >= 3:
|
| 1268 |
+
reasons.append(
|
| 1269 |
+
f"reference_price_date stale ({reference_price_date}, {staleness_days}d)"
|
| 1270 |
+
)
|
| 1271 |
+
|
| 1272 |
+
return reasons
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
@app.get(
|
| 1276 |
"/api/analysis/tft/{symbol}",
|
| 1277 |
summary="Get TFT-ASRO deep learning analysis",
|
|
|
|
| 1317 |
# --- 1. Try persisted snapshot ------------------------------------------
|
| 1318 |
if source == "snapshot":
|
| 1319 |
try:
|
| 1320 |
+
from app.models import TFTPredictionSnapshot
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1321 |
|
| 1322 |
with SessionLocal() as session:
|
| 1323 |
latest_price_date = _latest_price_bar_date(session, symbol)
|
|
|
|
| 1329 |
)
|
| 1330 |
if latest is not None and isinstance(latest.payload_json, dict):
|
| 1331 |
payload = dict(latest.payload_json)
|
| 1332 |
+
gen_at = _as_utc(latest.generated_at)
|
| 1333 |
+
fallback_reasons = _tft_snapshot_invalid_reasons(
|
| 1334 |
+
session, symbol, latest, latest_price_date=latest_price_date
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1335 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1336 |
|
| 1337 |
+
if not fallback_reasons:
|
| 1338 |
+
prediction = (
|
| 1339 |
+
payload.get("prediction")
|
| 1340 |
+
if isinstance(payload.get("prediction"), dict)
|
| 1341 |
+
else {}
|
| 1342 |
)
|
| 1343 |
+
payload.setdefault("primary_horizon", "5D")
|
| 1344 |
+
payload.setdefault("primary_forecast_return", prediction.get("weekly_return"))
|
| 1345 |
+
payload.setdefault("primary_forecast_q10", prediction.get("weekly_return_q10_calibrated"))
|
| 1346 |
+
payload.setdefault("primary_forecast_q90", prediction.get("weekly_return_q90_calibrated"))
|
| 1347 |
+
payload.setdefault("t1_return", prediction.get("predicted_return_median"))
|
| 1348 |
+
payload.setdefault("t1_impulse", payload.get("t1_impulse"))
|
| 1349 |
+
payload.setdefault("return_space", prediction.get("return_space"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1350 |
payload["source"] = "snapshot"
|
| 1351 |
payload["snapshot_generated_at"] = (
|
| 1352 |
gen_at.isoformat() if gen_at else None
|
|
|
|
| 1418 |
raise HTTPException(status_code=500, detail=str(exc))
|
| 1419 |
|
| 1420 |
|
| 1421 |
+
@app.get(
|
| 1422 |
+
"/api/explain/{symbol}",
|
| 1423 |
+
response_model=Dict[str, Any],
|
| 1424 |
+
summary="Get stored TFT-ASRO model-focus explanation",
|
| 1425 |
+
description=(
|
| 1426 |
+
"Returns the per-forecast model focus (variable-selection weights and "
|
| 1427 |
+
"temporal attention) stored with the latest TFT snapshot produced by "
|
| 1428 |
+
"the pipeline worker. Snapshot-only: unlike /api/analysis/tft, it "
|
| 1429 |
+
"never runs live inference. A missing or stale snapshot returns 404 "
|
| 1430 |
+
"with a reason so the UI can render an explicit empty state."
|
| 1431 |
+
),
|
| 1432 |
+
responses={
|
| 1433 |
+
200: {"description": "Stored per-forecast explanation payload"},
|
| 1434 |
+
404: {"description": "No fresh TFT snapshot explanation is available"},
|
| 1435 |
+
},
|
| 1436 |
+
)
|
| 1437 |
+
def get_tft_explain(symbol: str = TARGET_SYMBOL):
|
| 1438 |
+
"""
|
| 1439 |
+
Get the stored TFT-ASRO explanation for the given symbol.
|
| 1440 |
+
|
| 1441 |
+
Explanations are computed once by the pipeline worker and persisted with
|
| 1442 |
+
the snapshot (`explain_json`). This endpoint is snapshot-only like the
|
| 1443 |
+
documented contract: a missing, stale, or explanation-less snapshot is
|
| 1444 |
+
404. Declared as a sync `def` handler so the framework runs it in the
|
| 1445 |
+
threadpool — the freshness check touches three tables and must not block
|
| 1446 |
+
the event loop.
|
| 1447 |
+
"""
|
| 1448 |
+
from app.models import TFTPredictionSnapshot
|
| 1449 |
+
|
| 1450 |
+
try:
|
| 1451 |
+
with SessionLocal() as session:
|
| 1452 |
+
latest = (
|
| 1453 |
+
session.query(TFTPredictionSnapshot)
|
| 1454 |
+
.filter(TFTPredictionSnapshot.symbol == symbol)
|
| 1455 |
+
.order_by(TFTPredictionSnapshot.generated_at.desc())
|
| 1456 |
+
.first()
|
| 1457 |
+
)
|
| 1458 |
+
if latest is None:
|
| 1459 |
+
raise HTTPException(
|
| 1460 |
+
status_code=404,
|
| 1461 |
+
detail=(
|
| 1462 |
+
f"No TFT snapshot for {symbol}. Explanation will be "
|
| 1463 |
+
"available after the next pipeline refresh."
|
| 1464 |
+
),
|
| 1465 |
+
)
|
| 1466 |
+
|
| 1467 |
+
invalid_reasons = _tft_snapshot_invalid_reasons(session, symbol, latest)
|
| 1468 |
+
if invalid_reasons:
|
| 1469 |
+
raise HTTPException(
|
| 1470 |
+
status_code=404,
|
| 1471 |
+
detail=f"TFT snapshot is stale: {'; '.join(invalid_reasons)}",
|
| 1472 |
+
)
|
| 1473 |
+
|
| 1474 |
+
explain_payload = latest.explain_json
|
| 1475 |
+
if not isinstance(explain_payload, dict):
|
| 1476 |
+
raise HTTPException(
|
| 1477 |
+
status_code=404,
|
| 1478 |
+
detail=(
|
| 1479 |
+
"Explanation not available for this snapshot. Try again "
|
| 1480 |
+
"after the next pipeline refresh."
|
| 1481 |
+
),
|
| 1482 |
+
)
|
| 1483 |
+
|
| 1484 |
+
return explain_payload
|
| 1485 |
+
except HTTPException:
|
| 1486 |
+
raise
|
| 1487 |
+
except Exception as exc:
|
| 1488 |
+
logger.error("TFT explain lookup failed for %s: %s", symbol, exc, exc_info=True)
|
| 1489 |
+
raise HTTPException(
|
| 1490 |
+
status_code=503,
|
| 1491 |
+
detail="Explanation lookup failed; retry shortly.",
|
| 1492 |
+
)
|
| 1493 |
+
|
| 1494 |
+
|
| 1495 |
@app.get("/", include_in_schema=False)
|
| 1496 |
async def root_redirect():
|
| 1497 |
"""Redirect root to API docs."""
|
|
|
|
| 1826 |
out[k] = num
|
| 1827 |
return out
|
| 1828 |
|
| 1829 |
+
def _importance_entries(weights: dict) -> list[dict]:
|
| 1830 |
+
from .features import describe_feature
|
| 1831 |
+
|
| 1832 |
+
entries = []
|
| 1833 |
+
dropped: list[str] = []
|
| 1834 |
+
for feat, imp in weights.items():
|
| 1835 |
+
try:
|
| 1836 |
+
importance_value = float(imp)
|
| 1837 |
+
if not math.isfinite(importance_value):
|
| 1838 |
+
raise ValueError("non-finite importance")
|
| 1839 |
+
except (TypeError, ValueError):
|
| 1840 |
+
# One malformed entry must not discard the whole VSN map;
|
| 1841 |
+
# record it and keep the rest.
|
| 1842 |
+
dropped.append(str(feat))
|
| 1843 |
+
continue
|
| 1844 |
+
meta_desc = describe_feature(feat)
|
| 1845 |
+
entries.append({
|
| 1846 |
+
"feature": feat,
|
| 1847 |
+
"importance": importance_value,
|
| 1848 |
+
"label": meta_desc["label"],
|
| 1849 |
+
"description": meta_desc["description"],
|
| 1850 |
+
"category": meta_desc["category"],
|
| 1851 |
+
"time_horizon": meta_desc.get("time_horizon", ""),
|
| 1852 |
+
})
|
| 1853 |
+
if dropped:
|
| 1854 |
+
logger.warning(
|
| 1855 |
+
"Dropped %d malformed TFT variable-importance weight(s): %s",
|
| 1856 |
+
len(dropped),
|
| 1857 |
+
", ".join(dropped[:10]),
|
| 1858 |
+
)
|
| 1859 |
+
entries.sort(key=lambda x: x["importance"], reverse=True)
|
| 1860 |
+
return entries[:20]
|
| 1861 |
+
|
| 1862 |
+
def _build_variable_importance(meta) -> tuple[list[dict], str | None]:
|
| 1863 |
+
"""Return (entries, method) — the source that actually produced the top list.
|
| 1864 |
+
|
| 1865 |
+
VSN encoder weights and MRMR scores are different quantities that share
|
| 1866 |
+
one response field, so the method is reported explicitly
|
| 1867 |
+
(``vsn_encoder`` / ``mrmr`` / ``None`` when unavailable).
|
| 1868 |
+
"""
|
| 1869 |
+
# Prefer the VSN encoder importance persisted at promotion time; rows
|
| 1870 |
+
# from before that change (or a malformed payload) fall back to the
|
| 1871 |
+
# latest MRMR artifact.
|
| 1872 |
+
persisted_importance = _safe_json_load(meta.importance_json)
|
| 1873 |
+
encoder_importance = persisted_importance.get("encoder")
|
| 1874 |
+
if isinstance(encoder_importance, dict) and encoder_importance:
|
| 1875 |
+
try:
|
| 1876 |
+
entries = _importance_entries(encoder_importance)
|
| 1877 |
+
if entries:
|
| 1878 |
+
return entries, "vsn_encoder"
|
| 1879 |
+
except Exception as e:
|
| 1880 |
+
logger.warning(
|
| 1881 |
+
f"Could not parse persisted TFT variable importance: {e}"
|
| 1882 |
+
)
|
| 1883 |
+
|
| 1884 |
+
variable_importance = []
|
| 1885 |
+
try:
|
| 1886 |
+
import pathlib
|
| 1887 |
+
|
| 1888 |
+
artifact_dir = pathlib.Path(config.get("feature_store", {}).get("artifact_dir", "artifacts/feature_store"))
|
| 1889 |
+
mrmr_path = artifact_dir / "latest" / "mrmr_results.json"
|
| 1890 |
+
if mrmr_path.exists():
|
| 1891 |
+
mrmr_data = json.loads(mrmr_path.read_text(encoding="utf-8"))
|
| 1892 |
+
variable_importance = _importance_entries(mrmr_data.get("scores", {}))
|
| 1893 |
+
except Exception as e:
|
| 1894 |
+
logger.warning(f"Could not load variable importance: {e}")
|
| 1895 |
+
variable_importance = []
|
| 1896 |
+
method = "mrmr" if variable_importance else None
|
| 1897 |
+
return variable_importance, method
|
| 1898 |
+
|
| 1899 |
with SessionLocal() as session:
|
| 1900 |
# This endpoint describes the active/promoted model. Rejected candidate
|
| 1901 |
# metrics remain in the GitHub run artifact and must never replace the
|
|
|
|
| 1918 |
config = _safe_json_load(meta.config_json)
|
| 1919 |
metrics_raw = _safe_json_load(meta.metrics_json)
|
| 1920 |
metrics = _numeric_map(metrics_raw)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1921 |
|
| 1922 |
+
variable_importance, variable_importance_method = _build_variable_importance(meta)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1923 |
|
| 1924 |
da = float(metrics.get("directional_accuracy", 0.5))
|
| 1925 |
sharpe = float(metrics.get("sharpe_ratio", 0.0))
|
|
|
|
| 1988 |
"config": config,
|
| 1989 |
"metrics": metrics,
|
| 1990 |
"variable_importance": variable_importance,
|
| 1991 |
+
"variable_importance_method": variable_importance_method,
|
| 1992 |
"quality_gate": {
|
| 1993 |
"passed": passed,
|
| 1994 |
"reasons": reasons,
|
app/models.py
CHANGED
|
@@ -293,6 +293,8 @@ class ModelArtifact(Base):
|
|
| 293 |
sha256 = Column(String(64), nullable=False)
|
| 294 |
features_json = Column(Text, nullable=False)
|
| 295 |
metrics_json = Column(Text, nullable=False)
|
|
|
|
|
|
|
| 296 |
importance_json = Column(Text, nullable=False)
|
| 297 |
manifest_json = Column(Text, nullable=False)
|
| 298 |
trained_at = Column(DateTime(timezone=True), nullable=False, default=_utcnow, index=True)
|
|
@@ -647,6 +649,12 @@ class TFTModelMetadata(Base):
|
|
| 647 |
symbol = Column(String(20), nullable=False, unique=True, index=True)
|
| 648 |
config_json = Column(Text, nullable=True)
|
| 649 |
metrics_json = Column(Text, nullable=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 650 |
checkpoint_path = Column(String(500), nullable=True)
|
| 651 |
trained_at = Column(DateTime(timezone=True), nullable=False, default=_utcnow, index=True)
|
| 652 |
# NULL = legacy row persisted before this column was added (treat as unknown).
|
|
@@ -688,6 +696,11 @@ class TFTPredictionSnapshot(Base):
|
|
| 688 |
# Which run produced it; null on ad-hoc endpoint writes.
|
| 689 |
run_id = Column(String(80), nullable=True, index=True)
|
| 690 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 691 |
def __repr__(self):
|
| 692 |
return (
|
| 693 |
f"<TFTPredictionSnapshot(symbol={self.symbol}, "
|
|
|
|
| 293 |
sha256 = Column(String(64), nullable=False)
|
| 294 |
features_json = Column(Text, nullable=False)
|
| 295 |
metrics_json = Column(Text, nullable=False)
|
| 296 |
+
# Shape note: [{feature, importance}] list (ai_engine promotion) — see the
|
| 297 |
+
# differently-shaped TFTModelMetadata.importance_json in this file.
|
| 298 |
importance_json = Column(Text, nullable=False)
|
| 299 |
manifest_json = Column(Text, nullable=False)
|
| 300 |
trained_at = Column(DateTime(timezone=True), nullable=False, default=_utcnow, index=True)
|
|
|
|
| 649 |
symbol = Column(String(20), nullable=False, unique=True, index=True)
|
| 650 |
config_json = Column(Text, nullable=True)
|
| 651 |
metrics_json = Column(Text, nullable=True)
|
| 652 |
+
# NOTE: deliberately NOT the same shape as ModelArtifact.importance_json
|
| 653 |
+
# (models.py), despite the shared column name. That one holds a *list* of
|
| 654 |
+
# [{"feature", "importance"}] written by ai_engine promotion; this one is a
|
| 655 |
+
# JSON *object*: {"schema_version", "encoder": {feature: weight}, "trained_at",
|
| 656 |
+
# "checkpoint"} written by deep_learning.training.persist_promoted_tft_metadata.
|
| 657 |
+
importance_json = Column(Text, nullable=True)
|
| 658 |
checkpoint_path = Column(String(500), nullable=True)
|
| 659 |
trained_at = Column(DateTime(timezone=True), nullable=False, default=_utcnow, index=True)
|
| 660 |
# NULL = legacy row persisted before this column was added (treat as unknown).
|
|
|
|
| 696 |
# Which run produced it; null on ad-hoc endpoint writes.
|
| 697 |
run_id = Column(String(80), nullable=True, index=True)
|
| 698 |
|
| 699 |
+
# Per-forecast TFT-ASRO explanation (VSN weights + attention) built at
|
| 700 |
+
# inference time. NULL when explanations are disabled or unavailable;
|
| 701 |
+
# explanations are optional and must never block a snapshot write.
|
| 702 |
+
explain_json = Column(JSON, nullable=True)
|
| 703 |
+
|
| 704 |
def __repr__(self):
|
| 705 |
return (
|
| 706 |
f"<TFTPredictionSnapshot(symbol={self.symbol}, "
|
app/schemas.py
CHANGED
|
@@ -270,6 +270,14 @@ class TFTModelSummaryResponse(BaseModel):
|
|
| 270 |
config: Dict[str, Any] = Field(default_factory=dict, description="Model configuration parameters")
|
| 271 |
metrics: Dict[str, float] = Field(default_factory=dict, description="Test metrics from training")
|
| 272 |
variable_importance: List[VariableImportance] = Field(default_factory=list, description="Top feature importance scores")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
quality_gate: Optional[QualityGateResponse] = Field(None, description="Quality gate evaluation results")
|
| 274 |
|
| 275 |
|
|
|
|
| 270 |
config: Dict[str, Any] = Field(default_factory=dict, description="Model configuration parameters")
|
| 271 |
metrics: Dict[str, float] = Field(default_factory=dict, description="Test metrics from training")
|
| 272 |
variable_importance: List[VariableImportance] = Field(default_factory=list, description="Top feature importance scores")
|
| 273 |
+
variable_importance_method: Optional[str] = Field(
|
| 274 |
+
None,
|
| 275 |
+
description=(
|
| 276 |
+
"Source of `variable_importance`: `vsn_encoder` (TFT variable-selection "
|
| 277 |
+
"weights persisted at promotion) or `mrmr` (feature-selection scores from "
|
| 278 |
+
"the latest artifact); `null` when neither is available."
|
| 279 |
+
),
|
| 280 |
+
)
|
| 281 |
quality_gate: Optional[QualityGateResponse] = Field(None, description="Quality gate evaluation results")
|
| 282 |
|
| 283 |
|
app/tft_explain.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build the per-forecast TFT-ASRO explanation payload stored as ``explain_json``.
|
| 2 |
+
|
| 3 |
+
The payload enriches the raw interpretation produced by
|
| 4 |
+
:func:`deep_learning.models.tft_copper.interpret_batch` (VSN variable-selection
|
| 5 |
+
weights plus encoder attention) with human-readable feature labels, five-session
|
| 6 |
+
recent deltas and window dates. Everything returned is plain JSON data
|
| 7 |
+
(floats/strings/``None``), safe for SQLAlchemy ``JSON`` columns and for the
|
| 8 |
+
``/api/explain/{symbol}`` endpoint.
|
| 9 |
+
|
| 10 |
+
Building is best-effort: hot-path callers must use
|
| 11 |
+
:func:`try_build_explain_payload`, which never raises. An explanation is
|
| 12 |
+
optional and must never fail a pipeline run.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import hashlib
|
| 16 |
+
import logging
|
| 17 |
+
import re
|
| 18 |
+
from datetime import date, datetime, timezone
|
| 19 |
+
from typing import Any, Optional, Sequence
|
| 20 |
+
|
| 21 |
+
import pandas as pd
|
| 22 |
+
|
| 23 |
+
from app.features import describe_feature
|
| 24 |
+
from app.price_utils import finite_number
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
EXPLAIN_SCHEMA_VERSION = 1
|
| 29 |
+
TOP_RECENT = 5
|
| 30 |
+
RECENT_BASIS_SESSIONS = 5
|
| 31 |
+
# Hard cap on serialized encoder entries. A full VSN list (mrmr_top_k=80 real
|
| 32 |
+
# features with label+description+category metadata) serializes to roughly
|
| 33 |
+
# 20-40 KB per snapshot row per day — stored in Postgres, returned by every
|
| 34 |
+
# /api/explain poll, and injected into the DOM via the "Raw JSON" details.
|
| 35 |
+
# The panel renders only the top five rows, so 25 caps the stored artifact
|
| 36 |
+
# while keeping meaningful context.
|
| 37 |
+
TOP_ENCODER = 25
|
| 38 |
+
|
| 39 |
+
_HORIZON_LABEL = "5-day cumulative log return (primary)"
|
| 40 |
+
_HORIZON_DAYS = 5
|
| 41 |
+
_TOP_DAYS = 5
|
| 42 |
+
|
| 43 |
+
# Features whose five-session change reads naturally as a percentage.
|
| 44 |
+
_LEVEL_TOKENS = frozenset(
|
| 45 |
+
{
|
| 46 |
+
"price",
|
| 47 |
+
"sma",
|
| 48 |
+
"ema",
|
| 49 |
+
"close",
|
| 50 |
+
"open",
|
| 51 |
+
"high",
|
| 52 |
+
"low",
|
| 53 |
+
"stock",
|
| 54 |
+
"tonnes",
|
| 55 |
+
"inventory",
|
| 56 |
+
"warehouse",
|
| 57 |
+
"volume",
|
| 58 |
+
}
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
_NOTES = (
|
| 62 |
+
"Model focus only: variable-selection (VSN) weights and attention weights show where the "
|
| 63 |
+
"TFT-ASRO model looked inside the latest encoder window. They are raw, pre-calibration "
|
| 64 |
+
"signals and are not causal: do not read them as market drivers or investment advice."
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _json_date(value: Any) -> Optional[str]:
|
| 69 |
+
"""Normalize a date-like value to an ISO string; other values pass through ``str``."""
|
| 70 |
+
if value is None:
|
| 71 |
+
return None
|
| 72 |
+
if isinstance(value, date):
|
| 73 |
+
return value.isoformat()
|
| 74 |
+
return str(value)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _json_text(value: Any) -> Optional[str]:
|
| 78 |
+
"""Normalize an identifier value to ``str`` (JSON-safe)."""
|
| 79 |
+
if value is None:
|
| 80 |
+
return None
|
| 81 |
+
return str(value)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _sanitize_weight(value: Any) -> Optional[float]:
|
| 85 |
+
"""Return ``value`` as a finite float rounded to 6 dp, or ``None`` when unusable."""
|
| 86 |
+
weight = finite_number(value)
|
| 87 |
+
if weight is None:
|
| 88 |
+
return None
|
| 89 |
+
return round(weight, 6)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _layout_hash(feature_names: Sequence[str]) -> str:
|
| 93 |
+
"""12-char sha1 fingerprint of a model group's feature layout."""
|
| 94 |
+
joined = "\n".join(str(name) for name in feature_names)
|
| 95 |
+
return hashlib.sha1(joined.encode("utf-8")).hexdigest()[:12]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _recent_kind(feature: str, category: str) -> Optional[str]:
|
| 99 |
+
"""Return ``"pct"``/``"abs"`` for a recent-delta block, or ``None`` when none applies.
|
| 100 |
+
|
| 101 |
+
Embedding features have no meaningful signed delta; level-like features
|
| 102 |
+
(prices, averages, physical stock levels, volume) read best as percentage
|
| 103 |
+
changes; everything else uses absolute changes.
|
| 104 |
+
"""
|
| 105 |
+
lowered = (feature or "").lower()
|
| 106 |
+
if category == "Embedding" or "emb_" in lowered:
|
| 107 |
+
return None
|
| 108 |
+
tokens = re.split(r"[^a-z0-9]+", lowered)
|
| 109 |
+
if any(token in _LEVEL_TOKENS for token in tokens):
|
| 110 |
+
return "pct"
|
| 111 |
+
return "abs"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _recent_block(
|
| 115 |
+
feature: str,
|
| 116 |
+
category: str,
|
| 117 |
+
feature_frame: pd.DataFrame,
|
| 118 |
+
window_dates: Sequence[Optional[str]],
|
| 119 |
+
) -> Optional[dict]:
|
| 120 |
+
"""Five-session delta block for an encoder feature, or ``None`` when it cannot be built.
|
| 121 |
+
|
| 122 |
+
Compares the first and last finite values within the tail ``RECENT_BASIS_SESSIONS``
|
| 123 |
+
rows of ``feature_frame``; the block is skipped for embedding features, for
|
| 124 |
+
features missing from the frame, and whenever fewer than two finite values are
|
| 125 |
+
available. ``change`` is always the absolute first→last delta; ``change_pct``
|
| 126 |
+
holds the percentage delta for ``pct`` features and is ``None`` otherwise.
|
| 127 |
+
"""
|
| 128 |
+
kind = _recent_kind(feature, category)
|
| 129 |
+
if kind is None or not feature or feature not in feature_frame.columns:
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
tail = feature_frame[feature].tail(RECENT_BASIS_SESSIONS)
|
| 133 |
+
offset = len(feature_frame) - len(tail)
|
| 134 |
+
finite_values: list[tuple[int, float]] = []
|
| 135 |
+
for position, raw in enumerate(tail.tolist()):
|
| 136 |
+
value = finite_number(raw)
|
| 137 |
+
if value is not None:
|
| 138 |
+
finite_values.append((offset + position, value))
|
| 139 |
+
if len(finite_values) < 2:
|
| 140 |
+
return None
|
| 141 |
+
|
| 142 |
+
last_position, last_value = finite_values[-1]
|
| 143 |
+
first_position, first_value = finite_values[0]
|
| 144 |
+
change = finite_number(last_value - first_value)
|
| 145 |
+
if change is None:
|
| 146 |
+
return None
|
| 147 |
+
|
| 148 |
+
change_pct: Optional[float] = None
|
| 149 |
+
if kind == "pct" and first_value != 0.0:
|
| 150 |
+
raw_pct = finite_number(change / abs(first_value) * 100.0)
|
| 151 |
+
if raw_pct is None:
|
| 152 |
+
return None
|
| 153 |
+
change_pct = round(raw_pct, 6)
|
| 154 |
+
|
| 155 |
+
# Label the actual observed span, not the nominal window: when the tail rows
|
| 156 |
+
# contain missing values the comparison may span fewer sessions, and the UI
|
| 157 |
+
# prints this label verbatim.
|
| 158 |
+
basis = f"{last_position - first_position + 1} sessions"
|
| 159 |
+
|
| 160 |
+
return {
|
| 161 |
+
"basis": basis,
|
| 162 |
+
"kind": kind,
|
| 163 |
+
"last_value": round(last_value, 6),
|
| 164 |
+
"change": round(change, 6),
|
| 165 |
+
"change_pct": change_pct,
|
| 166 |
+
"as_of": window_dates[last_position],
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _entry(feature: str, weight: float) -> dict:
|
| 171 |
+
"""One variable-selection entry enriched with ``describe_feature`` metadata."""
|
| 172 |
+
description = describe_feature(feature) or {}
|
| 173 |
+
return {
|
| 174 |
+
"feature": feature,
|
| 175 |
+
"weight": weight,
|
| 176 |
+
"label": description.get("label", feature),
|
| 177 |
+
"description": description.get("description", ""),
|
| 178 |
+
"category": description.get("category", "Other"),
|
| 179 |
+
"time_horizon": description.get("time_horizon", ""),
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _group_entries(group: Sequence[dict]) -> list[dict]:
|
| 184 |
+
"""Convert one interpretation group, dropping non-finite weights."""
|
| 185 |
+
entries: list[dict] = []
|
| 186 |
+
for item in group:
|
| 187 |
+
feature = _json_text(item.get("feature")) or ""
|
| 188 |
+
weight = _sanitize_weight(item.get("weight"))
|
| 189 |
+
if weight is None:
|
| 190 |
+
continue
|
| 191 |
+
entries.append(_entry(feature, weight))
|
| 192 |
+
return entries
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _layout_names(group: Sequence[dict]) -> list[str]:
|
| 196 |
+
"""Feature names of one interpretation group, in model order."""
|
| 197 |
+
return [_json_text(item.get("feature")) or "" for item in group]
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def build_explain_payload(
|
| 201 |
+
*,
|
| 202 |
+
interpretation: dict,
|
| 203 |
+
window_dates: Sequence[Any],
|
| 204 |
+
feature_frame: pd.DataFrame,
|
| 205 |
+
reference_price_date: Any,
|
| 206 |
+
symbol: str,
|
| 207 |
+
checkpoint: Any,
|
| 208 |
+
trained_at: Any = None,
|
| 209 |
+
run_id: Any = None,
|
| 210 |
+
generated_at: Any = None,
|
| 211 |
+
attention_pred_horizon: int = 0,
|
| 212 |
+
) -> dict:
|
| 213 |
+
"""Assemble the ``explain_json`` payload for one TFT-ASRO forecast.
|
| 214 |
+
|
| 215 |
+
``interpretation`` is an :func:`interpret_batch` result; ``window_dates`` must
|
| 216 |
+
carry one date label per attention value and ``feature_frame`` must have the
|
| 217 |
+
same number of rows (positional alignment). Encoder entries are sorted by
|
| 218 |
+
descending weight and capped at ``TOP_ENCODER``; decoder/static entries keep
|
| 219 |
+
model order. Only the top ``TOP_RECENT`` encoder entries receive a
|
| 220 |
+
five-session ``recent`` block.
|
| 221 |
+
|
| 222 |
+
Raises ``ValueError`` on length mismatches; any other malformed input raises
|
| 223 |
+
the underlying error. Callers on the prediction path should prefer
|
| 224 |
+
:func:`try_build_explain_payload`.
|
| 225 |
+
"""
|
| 226 |
+
attention_raw = list(interpretation["attention"])
|
| 227 |
+
dates = [_json_date(value) for value in window_dates]
|
| 228 |
+
|
| 229 |
+
if len(dates) != len(attention_raw):
|
| 230 |
+
raise ValueError(
|
| 231 |
+
f"window_dates length ({len(dates)}) must match "
|
| 232 |
+
f"attention length ({len(attention_raw)})"
|
| 233 |
+
)
|
| 234 |
+
if len(feature_frame) != len(dates):
|
| 235 |
+
raise ValueError(
|
| 236 |
+
f"feature_frame length ({len(feature_frame)}) must match "
|
| 237 |
+
f"window_dates length ({len(dates)})"
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
encoder_entries = _group_entries(interpretation["encoder"])
|
| 241 |
+
encoder_entries.sort(key=lambda entry: entry["weight"], reverse=True)
|
| 242 |
+
for entry in encoder_entries[:TOP_RECENT]:
|
| 243 |
+
recent = _recent_block(entry["feature"], entry["category"], feature_frame, dates)
|
| 244 |
+
if recent is not None:
|
| 245 |
+
entry["recent"] = recent
|
| 246 |
+
# Cap the emitted list only after the recent blocks are attached: they belong
|
| 247 |
+
# to the top five, which always survives the cap.
|
| 248 |
+
encoder_entries = encoder_entries[:TOP_ENCODER]
|
| 249 |
+
decoder_entries = _group_entries(interpretation["decoder"])
|
| 250 |
+
static_entries = _group_entries(interpretation["static"])
|
| 251 |
+
|
| 252 |
+
series = []
|
| 253 |
+
for date_value, raw_weight in zip(dates, attention_raw):
|
| 254 |
+
weight = _sanitize_weight(raw_weight)
|
| 255 |
+
series.append({"date": date_value, "weight": 0.0 if weight is None else weight})
|
| 256 |
+
top_days = [
|
| 257 |
+
{"date": entry["date"], "weight": entry["weight"]}
|
| 258 |
+
for entry in sorted(series, key=lambda entry: entry["weight"], reverse=True)[:_TOP_DAYS]
|
| 259 |
+
]
|
| 260 |
+
|
| 261 |
+
if generated_at is None:
|
| 262 |
+
generated_at = datetime.now(timezone.utc)
|
| 263 |
+
|
| 264 |
+
return {
|
| 265 |
+
"schema_version": EXPLAIN_SCHEMA_VERSION,
|
| 266 |
+
"symbol": _json_text(symbol),
|
| 267 |
+
"reference_price_date": _json_date(reference_price_date),
|
| 268 |
+
"generated_at": _json_date(generated_at),
|
| 269 |
+
"run_id": _json_text(run_id),
|
| 270 |
+
"model": {
|
| 271 |
+
"checkpoint": _json_text(checkpoint),
|
| 272 |
+
"trained_at": _json_date(trained_at),
|
| 273 |
+
},
|
| 274 |
+
"horizon": {"label": _HORIZON_LABEL, "days": _HORIZON_DAYS},
|
| 275 |
+
"layout_hash": {
|
| 276 |
+
"encoder": _layout_hash(_layout_names(interpretation["encoder"])),
|
| 277 |
+
"decoder": _layout_hash(_layout_names(interpretation["decoder"])),
|
| 278 |
+
"static": _layout_hash(_layout_names(interpretation["static"])),
|
| 279 |
+
},
|
| 280 |
+
"variable_selection": {
|
| 281 |
+
"method": "vsn",
|
| 282 |
+
"encoder": encoder_entries,
|
| 283 |
+
"decoder": decoder_entries,
|
| 284 |
+
"static": static_entries,
|
| 285 |
+
},
|
| 286 |
+
"attention": {
|
| 287 |
+
"method": "tft_attention",
|
| 288 |
+
"step": {
|
| 289 |
+
"kind": "first_forecast_day",
|
| 290 |
+
"horizon_index": int(attention_pred_horizon),
|
| 291 |
+
},
|
| 292 |
+
"window": {
|
| 293 |
+
"start": dates[0] if dates else None,
|
| 294 |
+
"end": dates[-1] if dates else None,
|
| 295 |
+
"days": len(dates),
|
| 296 |
+
},
|
| 297 |
+
"top_days": top_days,
|
| 298 |
+
"series": series,
|
| 299 |
+
},
|
| 300 |
+
"notes": _NOTES,
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def try_build_explain_payload(**kwargs: Any) -> Optional[dict]:
|
| 305 |
+
"""Best-effort wrapper around :func:`build_explain_payload`.
|
| 306 |
+
|
| 307 |
+
Never raises: any failure is logged as a warning and yields ``None`` so an
|
| 308 |
+
explanation can never fail the prediction pipeline.
|
| 309 |
+
"""
|
| 310 |
+
try:
|
| 311 |
+
return build_explain_payload(**kwargs)
|
| 312 |
+
except Exception as exc:
|
| 313 |
+
logger.warning("TFT explain payload build failed; skipping explanation: %s", exc)
|
| 314 |
+
return None
|
deep_learning/inference/predictor.py
CHANGED
|
@@ -327,7 +327,12 @@ class TFTPredictor:
|
|
| 327 |
self._pca = load_pca(pca_path)
|
| 328 |
return self._pca
|
| 329 |
|
| 330 |
-
def predict(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
"""
|
| 332 |
Generate a TFT-ASRO prediction for the given symbol.
|
| 333 |
|
|
@@ -336,6 +341,11 @@ class TFTPredictor:
|
|
| 336 |
prevents the frontend from showing a forecast anchored to a stale
|
| 337 |
close when the weekend scheduler hasn't run or failed to catch up.
|
| 338 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
Returns a dict with:
|
| 340 |
- predicted_return_median, q10, q90
|
| 341 |
- predicted_price_median, q10, q90
|
|
@@ -346,6 +356,7 @@ class TFTPredictor:
|
|
| 346 |
- instrument: {"symbol": "HG=F", "kind": "futures", "name": ...}
|
| 347 |
- reference_price_date
|
| 348 |
- baseline_staleness_days (int, 0 = fresh)
|
|
|
|
| 349 |
"""
|
| 350 |
from deep_learning.data.feature_store import build_tft_dataframe
|
| 351 |
from deep_learning.data.future_frame import build_future_decoder_rows
|
|
@@ -605,8 +616,56 @@ class TFTPredictor:
|
|
| 605 |
result["generated_at"] = datetime.now(timezone.utc).isoformat()
|
| 606 |
result["symbol"] = symbol
|
| 607 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
return result
|
| 609 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
@staticmethod
|
| 611 |
def _degraded_retrain_required(message: str) -> Dict[str, Any]:
|
| 612 |
return {
|
|
@@ -900,16 +959,23 @@ def get_tft_predictor(cfg: Optional[TFTASROConfig] = None) -> TFTPredictor:
|
|
| 900 |
return _predictor
|
| 901 |
|
| 902 |
|
| 903 |
-
def generate_tft_analysis(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 904 |
"""
|
| 905 |
High-level API for generating a TFT-ASRO analysis report.
|
| 906 |
|
| 907 |
Designed to mirror the interface of the existing
|
| 908 |
-
``app.inference.generate_analysis_report``.
|
|
|
|
|
|
|
|
|
|
| 909 |
"""
|
| 910 |
predictor = get_tft_predictor()
|
| 911 |
|
| 912 |
-
prediction = predictor.predict(session, symbol)
|
| 913 |
if prediction.get("model_state") == "retrain_required":
|
| 914 |
prediction["symbol"] = symbol
|
| 915 |
return prediction
|
|
@@ -985,5 +1051,9 @@ def generate_tft_analysis(session, symbol: str = TARGET_SYMBOL) -> Dict[str, Any
|
|
| 985 |
"model_metadata": metadata,
|
| 986 |
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 987 |
}
|
| 988 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 989 |
return _sanitize_floats(raw_result)
|
|
|
|
| 327 |
self._pca = load_pca(pca_path)
|
| 328 |
return self._pca
|
| 329 |
|
| 330 |
+
def predict(
|
| 331 |
+
self,
|
| 332 |
+
session,
|
| 333 |
+
symbol: str = TARGET_SYMBOL,
|
| 334 |
+
include_explain: bool = False,
|
| 335 |
+
) -> Dict[str, Any]:
|
| 336 |
"""
|
| 337 |
Generate a TFT-ASRO prediction for the given symbol.
|
| 338 |
|
|
|
|
| 341 |
prevents the frontend from showing a forecast anchored to a stale
|
| 342 |
close when the weekend scheduler hasn't run or failed to catch up.
|
| 343 |
|
| 344 |
+
When ``include_explain`` is true the result additionally carries an
|
| 345 |
+
``explain`` key with the per-forecast VSN/attention payload for the
|
| 346 |
+
latest encoder window, or ``None`` when it cannot be built; building
|
| 347 |
+
an explanation is best-effort and never fails the prediction.
|
| 348 |
+
|
| 349 |
Returns a dict with:
|
| 350 |
- predicted_return_median, q10, q90
|
| 351 |
- predicted_price_median, q10, q90
|
|
|
|
| 356 |
- instrument: {"symbol": "HG=F", "kind": "futures", "name": ...}
|
| 357 |
- reference_price_date
|
| 358 |
- baseline_staleness_days (int, 0 = fresh)
|
| 359 |
+
- explain (only when include_explain=True)
|
| 360 |
"""
|
| 361 |
from deep_learning.data.feature_store import build_tft_dataframe
|
| 362 |
from deep_learning.data.future_frame import build_future_decoder_rows
|
|
|
|
| 616 |
result["generated_at"] = datetime.now(timezone.utc).isoformat()
|
| 617 |
result["symbol"] = symbol
|
| 618 |
|
| 619 |
+
if include_explain:
|
| 620 |
+
result["explain"] = self._latest_window_explain(
|
| 621 |
+
session,
|
| 622 |
+
model,
|
| 623 |
+
dl,
|
| 624 |
+
history,
|
| 625 |
+
symbol,
|
| 626 |
+
reference_price_date,
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
return result
|
| 630 |
|
| 631 |
+
def _latest_window_explain(
|
| 632 |
+
self,
|
| 633 |
+
session,
|
| 634 |
+
model,
|
| 635 |
+
dataloader,
|
| 636 |
+
history: pd.DataFrame,
|
| 637 |
+
symbol: str,
|
| 638 |
+
reference_price_date: Optional[str],
|
| 639 |
+
) -> Optional[Dict[str, Any]]:
|
| 640 |
+
"""Best-effort VSN/attention explanation for the latest encoder window.
|
| 641 |
+
|
| 642 |
+
Returns ``None`` whenever extraction or payload building fails; an
|
| 643 |
+
optional explanation must never fail the prediction path.
|
| 644 |
+
"""
|
| 645 |
+
try:
|
| 646 |
+
from app.tft_explain import try_build_explain_payload
|
| 647 |
+
from deep_learning.models.tft_copper import interpret_batch
|
| 648 |
+
|
| 649 |
+
# `_run_interpretation` (tft_copper) enforces eval mode for the
|
| 650 |
+
# forward pass and restores the original mode afterwards.
|
| 651 |
+
batch = next(iter(dataloader))
|
| 652 |
+
x = batch[0] if isinstance(batch, (tuple, list)) else batch
|
| 653 |
+
return try_build_explain_payload(
|
| 654 |
+
interpretation=interpret_batch(model, x),
|
| 655 |
+
window_dates=[self._date_label(value) for value in history.index],
|
| 656 |
+
feature_frame=history,
|
| 657 |
+
reference_price_date=reference_price_date,
|
| 658 |
+
symbol=symbol,
|
| 659 |
+
checkpoint=str(self._checkpoint_path),
|
| 660 |
+
trained_at=(self.get_model_metadata(session) or {}).get("trained_at"),
|
| 661 |
+
generated_at=datetime.now(timezone.utc),
|
| 662 |
+
)
|
| 663 |
+
except Exception as exc:
|
| 664 |
+
logger.warning(
|
| 665 |
+
"TFT explain extraction failed; skipping explanation: %s", exc
|
| 666 |
+
)
|
| 667 |
+
return None
|
| 668 |
+
|
| 669 |
@staticmethod
|
| 670 |
def _degraded_retrain_required(message: str) -> Dict[str, Any]:
|
| 671 |
return {
|
|
|
|
| 959 |
return _predictor
|
| 960 |
|
| 961 |
|
| 962 |
+
def generate_tft_analysis(
|
| 963 |
+
session,
|
| 964 |
+
symbol: str = TARGET_SYMBOL,
|
| 965 |
+
include_explain: bool = False,
|
| 966 |
+
) -> Dict[str, Any]:
|
| 967 |
"""
|
| 968 |
High-level API for generating a TFT-ASRO analysis report.
|
| 969 |
|
| 970 |
Designed to mirror the interface of the existing
|
| 971 |
+
``app.inference.generate_analysis_report``. When ``include_explain`` is
|
| 972 |
+
true the report carries an optional top-level ``explain`` payload (moved
|
| 973 |
+
out of the nested ``prediction`` block) for per-forecast XAI persistence;
|
| 974 |
+
it is absent whenever the explanation could not be built.
|
| 975 |
"""
|
| 976 |
predictor = get_tft_predictor()
|
| 977 |
|
| 978 |
+
prediction = predictor.predict(session, symbol, include_explain=include_explain)
|
| 979 |
if prediction.get("model_state") == "retrain_required":
|
| 980 |
prediction["symbol"] = symbol
|
| 981 |
return prediction
|
|
|
|
| 1051 |
"model_metadata": metadata,
|
| 1052 |
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 1053 |
}
|
| 1054 |
+
|
| 1055 |
+
explain = prediction.pop("explain", None)
|
| 1056 |
+
if explain is not None:
|
| 1057 |
+
raw_result["explain"] = explain
|
| 1058 |
+
|
| 1059 |
return _sanitize_floats(raw_result)
|
deep_learning/models/tft_copper.py
CHANGED
|
@@ -11,6 +11,7 @@ Wraps pytorch_forecasting's TemporalFusionTransformer with:
|
|
| 11 |
from __future__ import annotations
|
| 12 |
|
| 13 |
import logging
|
|
|
|
| 14 |
from pathlib import Path
|
| 15 |
from typing import Any, Dict, Optional, Sequence
|
| 16 |
|
|
@@ -829,51 +830,158 @@ def load_tft_model(
|
|
| 829 |
# Interpretation helpers
|
| 830 |
# ---------------------------------------------------------------------------
|
| 831 |
|
| 832 |
-
def
|
| 833 |
-
"""
|
| 834 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 835 |
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
|
|
|
|
|
|
| 839 |
"""
|
| 840 |
-
if val_dataloader is None:
|
| 841 |
-
return {}
|
| 842 |
try:
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 850 |
|
| 851 |
-
total = sum(importance.values())
|
| 852 |
-
if total == 0:
|
| 853 |
-
return importance
|
| 854 |
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 859 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 860 |
|
| 861 |
-
def get_attention_weights(model, dataloader) -> Optional[np.ndarray]:
|
| 862 |
-
"""
|
| 863 |
-
Extract temporal self-attention weights for interpretability.
|
| 864 |
|
| 865 |
-
|
| 866 |
-
or None if extraction fails.
|
| 867 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 868 |
try:
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 877 |
|
| 878 |
|
| 879 |
# ---------------------------------------------------------------------------
|
|
|
|
| 11 |
from __future__ import annotations
|
| 12 |
|
| 13 |
import logging
|
| 14 |
+
import math
|
| 15 |
from pathlib import Path
|
| 16 |
from typing import Any, Dict, Optional, Sequence
|
| 17 |
|
|
|
|
| 830 |
# Interpretation helpers
|
| 831 |
# ---------------------------------------------------------------------------
|
| 832 |
|
| 833 |
+
def _named_weights(names, weights) -> list[Dict[str, Any]]:
|
| 834 |
+
"""Zip variable names with a per-sample weight vector, validating the layout."""
|
| 835 |
+
if len(names) != len(weights):
|
| 836 |
+
raise ValueError(
|
| 837 |
+
f"interpretation names/weights mismatch: got {len(names)} names "
|
| 838 |
+
f"for {len(weights)} weights"
|
| 839 |
+
)
|
| 840 |
+
return [
|
| 841 |
+
{"feature": name, "weight": float(weight)}
|
| 842 |
+
for name, weight in zip(names, weights)
|
| 843 |
+
]
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def _run_interpretation(model, x: dict, attention_prediction_horizon: int):
|
| 847 |
+
"""Evaluate ``model`` on one batch and return ``(out, per-sample interpretation)``.
|
| 848 |
|
| 849 |
+
Placement and mode safety: tensors are moved to the model's device (an
|
| 850 |
+
inference model may legitimately live on GPU while the dataloader yields
|
| 851 |
+
CPU tensors — the same registration pytorch-forecasting's ``predict``
|
| 852 |
+
performs internally), eval mode is forced so dropout can never add noise
|
| 853 |
+
to the weights, and the original training mode is restored afterwards.
|
| 854 |
"""
|
|
|
|
|
|
|
| 855 |
try:
|
| 856 |
+
device = next(model.parameters()).device
|
| 857 |
+
except (AttributeError, StopIteration):
|
| 858 |
+
device = None
|
| 859 |
+
moved = {
|
| 860 |
+
key: value.to(device) if (device is not None and torch.is_tensor(value)) else value
|
| 861 |
+
for key, value in x.items()
|
| 862 |
+
}
|
| 863 |
+
was_training = bool(getattr(model, "training", False))
|
| 864 |
+
if was_training and hasattr(model, "eval"):
|
| 865 |
+
model.eval()
|
| 866 |
+
try:
|
| 867 |
+
with torch.no_grad():
|
| 868 |
+
out = model(moved)
|
| 869 |
+
finally:
|
| 870 |
+
if was_training and hasattr(model, "train"):
|
| 871 |
+
model.train()
|
| 872 |
+
|
| 873 |
+
interpretation = model.interpret_output(
|
| 874 |
+
out,
|
| 875 |
+
reduction="none",
|
| 876 |
+
attention_prediction_horizon=attention_prediction_horizon,
|
| 877 |
+
)
|
| 878 |
+
return out, interpretation
|
| 879 |
|
|
|
|
|
|
|
|
|
|
| 880 |
|
| 881 |
+
def interpret_batch(model, x: dict, attention_prediction_horizon: int = 0) -> dict:
|
| 882 |
+
"""
|
| 883 |
+
Interpret a single TFT batch: VSN selection weights plus encoder attention.
|
| 884 |
+
|
| 885 |
+
Runs the raw forward pass under ``torch.no_grad()`` (batch moved to the
|
| 886 |
+
model's device, eval mode enforced so dropout adds no noise) and reduces
|
| 887 |
+
nothing (``reduction="none"``), so every score stays per-sample; attention
|
| 888 |
+
is renormalized per sample and clipped to the encoder window
|
| 889 |
+
(``[: model.hparams.max_encoder_length]``). Group names come from
|
| 890 |
+
``model.encoder_variables`` / ``decoder_variables`` / ``static_variables``;
|
| 891 |
+
a names/weights length mismatch raises ``ValueError``.
|
| 892 |
+
"""
|
| 893 |
+
out, interpretation = _run_interpretation(model, x, attention_prediction_horizon)
|
| 894 |
|
| 895 |
+
max_encoder_length = int(model.hparams.max_encoder_length)
|
| 896 |
+
attention = (
|
| 897 |
+
interpretation["attention"][0].detach().cpu().numpy()[:max_encoder_length].tolist()
|
| 898 |
+
)
|
| 899 |
+
|
| 900 |
+
return {
|
| 901 |
+
"encoder": _named_weights(
|
| 902 |
+
model.encoder_variables,
|
| 903 |
+
interpretation["encoder_variables"][0].detach().cpu().numpy(),
|
| 904 |
+
),
|
| 905 |
+
"decoder": _named_weights(
|
| 906 |
+
model.decoder_variables,
|
| 907 |
+
interpretation["decoder_variables"][0].detach().cpu().numpy(),
|
| 908 |
+
),
|
| 909 |
+
"static": _named_weights(
|
| 910 |
+
model.static_variables,
|
| 911 |
+
interpretation["static_variables"][0].detach().cpu().numpy(),
|
| 912 |
+
),
|
| 913 |
+
"attention": attention,
|
| 914 |
+
"encoder_length": int(out["encoder_lengths"][0]),
|
| 915 |
+
}
|
| 916 |
|
|
|
|
|
|
|
|
|
|
| 917 |
|
| 918 |
+
def get_variable_importance(model, val_dataloader=None) -> Dict[str, float]:
|
|
|
|
| 919 |
"""
|
| 920 |
+
Mean encoder VSN variable importance over every validation sample.
|
| 921 |
+
|
| 922 |
+
``interpret_output(reduction="none")`` returns per-sample selection weights
|
| 923 |
+
(shape ``(batch, num_variables)``); those are pooled over *all samples of
|
| 924 |
+
every batch*, per feature. Non-finite weights are dropped per sample so a
|
| 925 |
+
single NaN/Inf batch cannot poison the whole map (an exploding checkpoint's
|
| 926 |
+
softmax weights may be NaN). The result is normalised to sum 1 and sorted in
|
| 927 |
+
descending order; an absent or empty loader yields ``{}``, and any failure
|
| 928 |
+
while extracting/averaging importance also yields ``{}``. This is
|
| 929 |
+
best-effort promotion metadata and must never raise.
|
| 930 |
+
``val_dataloader`` must be passed explicitly (``model.val_dataloader()``
|
| 931 |
+
only works inside a Lightning Trainer context and raises an error otherwise).
|
| 932 |
+
"""
|
| 933 |
+
if val_dataloader is None:
|
| 934 |
+
return {}
|
| 935 |
+
|
| 936 |
try:
|
| 937 |
+
weight_sums: Dict[str, float] = {}
|
| 938 |
+
sample_counts: Dict[str, int] = {}
|
| 939 |
+
n_samples = 0
|
| 940 |
+
for batch in val_dataloader:
|
| 941 |
+
sample = batch[0] if isinstance(batch, (tuple, list)) else batch
|
| 942 |
+
_, interpretation = _run_interpretation(model, sample, 0)
|
| 943 |
+
per_sample = interpretation["encoder_variables"].detach().cpu().numpy()
|
| 944 |
+
names = model.encoder_variables
|
| 945 |
+
if per_sample.ndim != 2 or len(names) != per_sample.shape[1]:
|
| 946 |
+
raise ValueError(
|
| 947 |
+
f"interpretation names/weights mismatch: got {len(names)} names "
|
| 948 |
+
f"for encoder variables of shape {per_sample.shape!r}"
|
| 949 |
+
)
|
| 950 |
+
for index, name in enumerate(names):
|
| 951 |
+
column = per_sample[:, index]
|
| 952 |
+
finite = column[np.isfinite(column)]
|
| 953 |
+
if finite.size == 0:
|
| 954 |
+
continue
|
| 955 |
+
weight_sums[name] = weight_sums.get(name, 0.0) + float(finite.sum())
|
| 956 |
+
sample_counts[name] = sample_counts.get(name, 0) + int(finite.size)
|
| 957 |
+
n_samples += int(per_sample.shape[0])
|
| 958 |
+
|
| 959 |
+
if n_samples == 0 or not weight_sums:
|
| 960 |
+
return {}
|
| 961 |
+
|
| 962 |
+
averaged: Dict[str, float] = {}
|
| 963 |
+
for name, total in weight_sums.items():
|
| 964 |
+
count = sample_counts.get(name, 0)
|
| 965 |
+
if count <= 0:
|
| 966 |
+
continue
|
| 967 |
+
average = total / count
|
| 968 |
+
if math.isfinite(average):
|
| 969 |
+
averaged[name] = average
|
| 970 |
+
if not averaged:
|
| 971 |
+
return {}
|
| 972 |
+
|
| 973 |
+
total_weight = sum(averaged.values())
|
| 974 |
+
if not math.isfinite(total_weight) or total_weight <= 0.0:
|
| 975 |
+
return {}
|
| 976 |
+
|
| 977 |
+
normalized = {name: weight / total_weight for name, weight in averaged.items()}
|
| 978 |
+
return dict(sorted(normalized.items(), key=lambda item: item[1], reverse=True))
|
| 979 |
+
except Exception:
|
| 980 |
+
logger.warning(
|
| 981 |
+
"Variable importance extraction failed; returning empty importance",
|
| 982 |
+
exc_info=True,
|
| 983 |
+
)
|
| 984 |
+
return {}
|
| 985 |
|
| 986 |
|
| 987 |
# ---------------------------------------------------------------------------
|
deep_learning/training/trainer.py
CHANGED
|
@@ -19,6 +19,7 @@ import argparse
|
|
| 19 |
import importlib.metadata
|
| 20 |
import json
|
| 21 |
import logging
|
|
|
|
| 22 |
import os
|
| 23 |
import platform
|
| 24 |
import sys
|
|
@@ -1559,6 +1560,36 @@ def _overlay_training_config(cfg: TFTASROConfig, params: dict) -> TFTASROConfig:
|
|
| 1559 |
return replace(cfg, model=new_model, asro=new_asro, weekly_loss=new_weekly_loss, training=new_training)
|
| 1560 |
|
| 1561 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1562 |
def persist_promoted_tft_metadata(symbol: str, result: dict) -> None:
|
| 1563 |
"""Persist the active model only after gate and Hub promotion succeed.
|
| 1564 |
|
|
@@ -1594,9 +1625,12 @@ def persist_promoted_tft_metadata(symbol: str, result: dict) -> None:
|
|
| 1594 |
TFTModelMetadata.symbol == symbol
|
| 1595 |
).first()
|
| 1596 |
|
|
|
|
|
|
|
| 1597 |
if existing:
|
| 1598 |
existing.config_json = json.dumps(result.get("config", {}))
|
| 1599 |
existing.metrics_json = json.dumps(metrics)
|
|
|
|
| 1600 |
existing.checkpoint_path = result.get("checkpoint_path", "")
|
| 1601 |
existing.trained_at = trained_at
|
| 1602 |
existing.quality_gate_passed = True
|
|
@@ -1606,6 +1640,7 @@ def persist_promoted_tft_metadata(symbol: str, result: dict) -> None:
|
|
| 1606 |
symbol=symbol,
|
| 1607 |
config_json=json.dumps(result.get("config", {})),
|
| 1608 |
metrics_json=json.dumps(metrics),
|
|
|
|
| 1609 |
checkpoint_path=result.get("checkpoint_path", ""),
|
| 1610 |
trained_at=trained_at,
|
| 1611 |
quality_gate_passed=True,
|
|
|
|
| 19 |
import importlib.metadata
|
| 20 |
import json
|
| 21 |
import logging
|
| 22 |
+
import math
|
| 23 |
import os
|
| 24 |
import platform
|
| 25 |
import sys
|
|
|
|
| 1560 |
return replace(cfg, model=new_model, asro=new_asro, weekly_loss=new_weekly_loss, training=new_training)
|
| 1561 |
|
| 1562 |
|
| 1563 |
+
def _importance_metadata_payload(result: dict) -> str:
|
| 1564 |
+
"""Serialize VSN encoder importance for informational storage at promotion.
|
| 1565 |
+
|
| 1566 |
+
Never let metadata-only concerns block promotion: missing or malformed
|
| 1567 |
+
importance degrades to an empty encoder map. Non-finite weights (exploding
|
| 1568 |
+
checkpoints can emit NaN softmax weights) are dropped — ``json.dumps``
|
| 1569 |
+
would otherwise emit ``NaN``/``Infinity`` literals, which are invalid JSON
|
| 1570 |
+
and choke strict readers of the summary endpoint.
|
| 1571 |
+
"""
|
| 1572 |
+
importance = result.get("variable_importance")
|
| 1573 |
+
if not isinstance(importance, dict):
|
| 1574 |
+
importance = {}
|
| 1575 |
+
cleaned_importance = {}
|
| 1576 |
+
for name, value in importance.items():
|
| 1577 |
+
try:
|
| 1578 |
+
weight = float(value)
|
| 1579 |
+
except (TypeError, ValueError):
|
| 1580 |
+
continue
|
| 1581 |
+
if math.isfinite(weight):
|
| 1582 |
+
cleaned_importance[name] = weight
|
| 1583 |
+
return json.dumps(
|
| 1584 |
+
{
|
| 1585 |
+
"schema_version": 1,
|
| 1586 |
+
"encoder": cleaned_importance,
|
| 1587 |
+
"trained_at": result.get("trained_at"),
|
| 1588 |
+
"checkpoint": result.get("checkpoint_path"),
|
| 1589 |
+
}
|
| 1590 |
+
)
|
| 1591 |
+
|
| 1592 |
+
|
| 1593 |
def persist_promoted_tft_metadata(symbol: str, result: dict) -> None:
|
| 1594 |
"""Persist the active model only after gate and Hub promotion succeed.
|
| 1595 |
|
|
|
|
| 1625 |
TFTModelMetadata.symbol == symbol
|
| 1626 |
).first()
|
| 1627 |
|
| 1628 |
+
importance_json = _importance_metadata_payload(result)
|
| 1629 |
+
|
| 1630 |
if existing:
|
| 1631 |
existing.config_json = json.dumps(result.get("config", {}))
|
| 1632 |
existing.metrics_json = json.dumps(metrics)
|
| 1633 |
+
existing.importance_json = importance_json
|
| 1634 |
existing.checkpoint_path = result.get("checkpoint_path", "")
|
| 1635 |
existing.trained_at = trained_at
|
| 1636 |
existing.quality_gate_passed = True
|
|
|
|
| 1640 |
symbol=symbol,
|
| 1641 |
config_json=json.dumps(result.get("config", {})),
|
| 1642 |
metrics_json=json.dumps(metrics),
|
| 1643 |
+
importance_json=importance_json,
|
| 1644 |
checkpoint_path=result.get("checkpoint_path", ""),
|
| 1645 |
trained_at=trained_at,
|
| 1646 |
quality_gate_passed=True,
|
worker/tasks.py
CHANGED
|
@@ -338,6 +338,84 @@ async def run_pipeline(
|
|
| 338 |
lock_connection.close()
|
| 339 |
|
| 340 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
async def _execute_pipeline_stages_v2(
|
| 342 |
session: Session,
|
| 343 |
run_id: str,
|
|
@@ -675,7 +753,7 @@ async def _execute_pipeline_stages_v2(
|
|
| 675 |
logger.warning(f"[run_id={run_id}] HF Hub download failed: {hub_exc}")
|
| 676 |
|
| 677 |
if ckpt.exists():
|
| 678 |
-
tft_report = generate_tft_analysis(session, "HG=F")
|
| 679 |
|
| 680 |
if "error" not in tft_report:
|
| 681 |
try:
|
|
@@ -716,36 +794,13 @@ async def _execute_pipeline_stages_v2(
|
|
| 716 |
# Persist the full report so /api/analysis/tft/{symbol}
|
| 717 |
# can serve it without re-running inference. This is the
|
| 718 |
# canonical source the frontend reads from.
|
| 719 |
-
persisted =
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
reference_price_date = prediction.get("reference_price_date")
|
| 725 |
-
|
| 726 |
-
snapshot_row = TFTPredictionSnapshot(
|
| 727 |
-
symbol="HG=F",
|
| 728 |
-
payload_json=tft_report,
|
| 729 |
-
generated_at=datetime.now(timezone.utc),
|
| 730 |
-
reference_price_date=reference_price_date,
|
| 731 |
-
run_id=str(run_id) if run_id is not None else None,
|
| 732 |
-
)
|
| 733 |
-
session.add(snapshot_row)
|
| 734 |
-
session.flush()
|
| 735 |
-
persisted = True
|
| 736 |
-
logger.info(
|
| 737 |
-
f"[run_id={run_id}] TFT prediction persisted "
|
| 738 |
-
f"(reference_price_date={reference_price_date})"
|
| 739 |
-
)
|
| 740 |
-
except Exception as persist_exc:
|
| 741 |
-
logger.error(
|
| 742 |
-
f"[run_id={run_id}] Failed to persist TFT snapshot: "
|
| 743 |
-
f"{persist_exc}",
|
| 744 |
-
exc_info=True,
|
| 745 |
-
)
|
| 746 |
-
session.rollback()
|
| 747 |
-
result["tft_persistence_error"] = str(persist_exc)
|
| 748 |
|
|
|
|
| 749 |
is_forecast_healthy = bool(tft_report.get("is_forecast_healthy", True))
|
| 750 |
result["tft_snapshot_generated"] = bool(is_forecast_healthy and persisted)
|
| 751 |
if is_forecast_healthy and persisted:
|
|
|
|
| 338 |
lock_connection.close()
|
| 339 |
|
| 340 |
|
| 341 |
+
def _persist_tft_report_snapshot(session, tft_report: dict, run_id=None):
|
| 342 |
+
"""Persist the (already enriched) TFT report as the latest snapshot row.
|
| 343 |
+
|
| 344 |
+
Moves the per-forecast ``explain`` payload out of ``tft_report`` and stores
|
| 345 |
+
it as ``explain_json`` (stamping it with the ``run_id`` so the stored
|
| 346 |
+
explanation is traceable to the run that produced it).
|
| 347 |
+
|
| 348 |
+
Fail-open contract: if persisting with ``explain_json`` fails, the failed
|
| 349 |
+
flush is rolled back and the snapshot write is retried once with
|
| 350 |
+
``explain_json=None`` so an optional explanation failure can never drop the
|
| 351 |
+
forecast snapshot.
|
| 352 |
+
|
| 353 |
+
Returns ``(explain_payload, persisted, error)`` where ``persisted`` is
|
| 354 |
+
False on a write failure and ``error`` carries its message. Persistence
|
| 355 |
+
failures never fail the pipeline stage.
|
| 356 |
+
"""
|
| 357 |
+
explain_payload = tft_report.pop("explain", None)
|
| 358 |
+
if isinstance(explain_payload, dict):
|
| 359 |
+
explain_payload["run_id"] = str(run_id) if run_id is not None else None
|
| 360 |
+
elif explain_payload is not None:
|
| 361 |
+
logger.warning(
|
| 362 |
+
f"[run_id={run_id}] Dropping non-dict TFT explain payload of type "
|
| 363 |
+
f"{type(explain_payload).__name__}"
|
| 364 |
+
)
|
| 365 |
+
explain_payload = None
|
| 366 |
+
|
| 367 |
+
prediction = tft_report.get("prediction") or {}
|
| 368 |
+
reference_price_date = prediction.get("reference_price_date")
|
| 369 |
+
normalized_run_id = str(run_id) if run_id is not None else None
|
| 370 |
+
|
| 371 |
+
def _write_row(explain_value):
|
| 372 |
+
from app.models import TFTPredictionSnapshot
|
| 373 |
+
|
| 374 |
+
snapshot_row = TFTPredictionSnapshot(
|
| 375 |
+
symbol="HG=F",
|
| 376 |
+
payload_json=tft_report,
|
| 377 |
+
generated_at=datetime.now(timezone.utc),
|
| 378 |
+
reference_price_date=reference_price_date,
|
| 379 |
+
run_id=normalized_run_id,
|
| 380 |
+
explain_json=explain_value,
|
| 381 |
+
)
|
| 382 |
+
session.add(snapshot_row)
|
| 383 |
+
session.flush()
|
| 384 |
+
|
| 385 |
+
try:
|
| 386 |
+
_write_row(explain_payload)
|
| 387 |
+
logger.info(
|
| 388 |
+
f"[run_id={run_id}] TFT prediction persisted "
|
| 389 |
+
f"(reference_price_date={reference_price_date}, "
|
| 390 |
+
f"explain={'yes' if isinstance(explain_payload, dict) else 'no'})"
|
| 391 |
+
)
|
| 392 |
+
return explain_payload, True, None
|
| 393 |
+
except Exception as persist_exc:
|
| 394 |
+
session.rollback()
|
| 395 |
+
if explain_payload is not None:
|
| 396 |
+
logger.warning(
|
| 397 |
+
f"[run_id={run_id}] Failed to persist TFT snapshot with explain_json "
|
| 398 |
+
f"({persist_exc}); retrying with explain_json=None"
|
| 399 |
+
)
|
| 400 |
+
try:
|
| 401 |
+
_write_row(None)
|
| 402 |
+
logger.info(
|
| 403 |
+
f"[run_id={run_id}] TFT prediction persisted without explain_json "
|
| 404 |
+
f"after downgrade (reference_price_date={reference_price_date})"
|
| 405 |
+
)
|
| 406 |
+
return None, True, None
|
| 407 |
+
except Exception as retry_exc:
|
| 408 |
+
persist_exc = retry_exc
|
| 409 |
+
session.rollback()
|
| 410 |
+
|
| 411 |
+
logger.error(
|
| 412 |
+
f"[run_id={run_id}] Failed to persist TFT snapshot: "
|
| 413 |
+
f"{persist_exc}",
|
| 414 |
+
exc_info=True,
|
| 415 |
+
)
|
| 416 |
+
return explain_payload, False, str(persist_exc)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
async def _execute_pipeline_stages_v2(
|
| 420 |
session: Session,
|
| 421 |
run_id: str,
|
|
|
|
| 753 |
logger.warning(f"[run_id={run_id}] HF Hub download failed: {hub_exc}")
|
| 754 |
|
| 755 |
if ckpt.exists():
|
| 756 |
+
tft_report = generate_tft_analysis(session, "HG=F", include_explain=True)
|
| 757 |
|
| 758 |
if "error" not in tft_report:
|
| 759 |
try:
|
|
|
|
| 794 |
# Persist the full report so /api/analysis/tft/{symbol}
|
| 795 |
# can serve it without re-running inference. This is the
|
| 796 |
# canonical source the frontend reads from.
|
| 797 |
+
explain_payload, persisted, persist_error = _persist_tft_report_snapshot(
|
| 798 |
+
session, tft_report, run_id
|
| 799 |
+
)
|
| 800 |
+
if persist_error is not None:
|
| 801 |
+
result["tft_persistence_error"] = persist_error
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 802 |
|
| 803 |
+
result["tft_explain_generated"] = bool(persisted and isinstance(explain_payload, dict))
|
| 804 |
is_forecast_healthy = bool(tft_report.get("is_forecast_healthy", True))
|
| 805 |
result["tft_snapshot_generated"] = bool(is_forecast_healthy and persisted)
|
| 806 |
if is_forecast_healthy and persisted:
|