Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
78efa34
1
Parent(s): 8e5c3f3
feat(tracker): implement Module E.1 shadow counterfactual veto tracking & isolated veto_effectiveness
Browse files- backend/database/db.py +62 -19
- backend/database/memory_store.py +46 -3
- backend/database/models.py +3 -1
- backend/engine/outcome_evaluator.py +36 -8
- backend/engine/signal_engine.py +40 -0
- backend/main.py +2 -0
- backend/routers/signals.py +2 -0
- frontend/src/types/index.ts +10 -0
- tests/test_five_exchange_whale_pov.py +282 -0
backend/database/db.py
CHANGED
|
@@ -47,6 +47,8 @@ _LEGACY_ALTER_COLUMNS_SQL = """
|
|
| 47 |
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS failure_tag TEXT;
|
| 48 |
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS exit_price DOUBLE PRECISION;
|
| 49 |
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS holding_duration_seconds INTEGER;
|
|
|
|
|
|
|
| 50 |
"""
|
| 51 |
|
| 52 |
|
|
@@ -426,15 +428,19 @@ def db_get_stale_active_pairs(limit: int | None = None) -> list[dict]:
|
|
| 426 |
# ---------------------------------------------------------------------------
|
| 427 |
|
| 428 |
def db_save_signal(symbol: str, timeframe: str, direction: str, conviction: int, signal_data: dict) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
if not DATABASE_URL:
|
| 430 |
-
_mem.save_signal(symbol, timeframe, direction, conviction,
|
| 431 |
return
|
| 432 |
with get_connection() as conn:
|
| 433 |
with conn.cursor() as cur:
|
| 434 |
cur.execute(
|
| 435 |
"""INSERT INTO signals (symbol, timeframe, direction, conviction, signal_data)
|
| 436 |
VALUES (%s, %s, %s, %s, %s)""",
|
| 437 |
-
(symbol, timeframe, direction, conviction, _safe_json_dumps(
|
| 438 |
)
|
| 439 |
|
| 440 |
|
|
@@ -995,6 +1001,8 @@ def _ensure_predictions_table(cur: Any, conn: Any) -> None:
|
|
| 995 |
if _predictions_table_ensured:
|
| 996 |
return
|
| 997 |
cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE)
|
|
|
|
|
|
|
| 998 |
cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX)
|
| 999 |
cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX)
|
| 1000 |
conn.commit()
|
|
@@ -1012,9 +1020,10 @@ def db_insert_signal_prediction(data: dict) -> dict:
|
|
| 1012 |
"""
|
| 1013 |
INSERT INTO signal_predictions (
|
| 1014 |
symbol, horizon, direction, conviction, regime, sniper_grade,
|
| 1015 |
-
entry_price, stop_loss, tp1, tp2, factor_scores, outcome, expires_at
|
|
|
|
| 1016 |
)
|
| 1017 |
-
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, 'PENDING', %s)
|
| 1018 |
RETURNING *;
|
| 1019 |
""",
|
| 1020 |
(
|
|
@@ -1030,6 +1039,8 @@ def db_insert_signal_prediction(data: dict) -> dict:
|
|
| 1030 |
float(data.get("tp2", 0.0)),
|
| 1031 |
_safe_json_dumps(data.get("factor_scores") or {}),
|
| 1032 |
data.get("expires_at"),
|
|
|
|
|
|
|
| 1033 |
),
|
| 1034 |
)
|
| 1035 |
row = cur.fetchone()
|
|
@@ -1089,28 +1100,56 @@ def db_get_recent_prediction(
|
|
| 1089 |
horizon: str,
|
| 1090 |
direction: str,
|
| 1091 |
cooldown_hours: int,
|
|
|
|
|
|
|
| 1092 |
) -> dict | None:
|
| 1093 |
"""Return an active PENDING prediction or a same-direction prediction within cooldown_hours."""
|
| 1094 |
if not DATABASE_URL:
|
| 1095 |
-
return _mem.get_recent_prediction(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1096 |
sym = symbol.upper()
|
| 1097 |
with get_connection() as conn:
|
| 1098 |
with conn.cursor() as cur:
|
| 1099 |
_ensure_predictions_table(cur, conn)
|
| 1100 |
-
|
| 1101 |
-
|
| 1102 |
-
|
| 1103 |
-
|
| 1104 |
-
|
| 1105 |
-
|
| 1106 |
-
|
| 1107 |
-
|
| 1108 |
-
|
| 1109 |
-
|
| 1110 |
-
|
| 1111 |
-
|
| 1112 |
-
|
| 1113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1114 |
row = cur.fetchone()
|
| 1115 |
return _format_row(row) if row else None
|
| 1116 |
|
|
@@ -1173,6 +1212,8 @@ async def async_get_recent_prediction(
|
|
| 1173 |
horizon: str,
|
| 1174 |
direction: str,
|
| 1175 |
cooldown_hours: int,
|
|
|
|
|
|
|
| 1176 |
) -> dict | None:
|
| 1177 |
return await asyncio.to_thread(
|
| 1178 |
db_get_recent_prediction,
|
|
@@ -1180,6 +1221,8 @@ async def async_get_recent_prediction(
|
|
| 1180 |
horizon,
|
| 1181 |
direction,
|
| 1182 |
cooldown_hours,
|
|
|
|
|
|
|
| 1183 |
)
|
| 1184 |
|
| 1185 |
|
|
|
|
| 47 |
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS failure_tag TEXT;
|
| 48 |
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS exit_price DOUBLE PRECISION;
|
| 49 |
ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS holding_duration_seconds INTEGER;
|
| 50 |
+
ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS is_shadow BOOLEAN DEFAULT FALSE;
|
| 51 |
+
ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS veto_reason TEXT;
|
| 52 |
"""
|
| 53 |
|
| 54 |
|
|
|
|
| 428 |
# ---------------------------------------------------------------------------
|
| 429 |
|
| 430 |
def db_save_signal(symbol: str, timeframe: str, direction: str, conviction: int, signal_data: dict) -> None:
|
| 431 |
+
clean_signal_data = signal_data
|
| 432 |
+
if isinstance(signal_data, dict) and "_shadow_trade_levels" in signal_data:
|
| 433 |
+
clean_signal_data = dict(signal_data)
|
| 434 |
+
clean_signal_data.pop("_shadow_trade_levels", None)
|
| 435 |
if not DATABASE_URL:
|
| 436 |
+
_mem.save_signal(symbol, timeframe, direction, conviction, clean_signal_data)
|
| 437 |
return
|
| 438 |
with get_connection() as conn:
|
| 439 |
with conn.cursor() as cur:
|
| 440 |
cur.execute(
|
| 441 |
"""INSERT INTO signals (symbol, timeframe, direction, conviction, signal_data)
|
| 442 |
VALUES (%s, %s, %s, %s, %s)""",
|
| 443 |
+
(symbol, timeframe, direction, conviction, _safe_json_dumps(clean_signal_data)),
|
| 444 |
)
|
| 445 |
|
| 446 |
|
|
|
|
| 1001 |
if _predictions_table_ensured:
|
| 1002 |
return
|
| 1003 |
cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE)
|
| 1004 |
+
cur.execute("ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS is_shadow BOOLEAN DEFAULT FALSE;")
|
| 1005 |
+
cur.execute("ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS veto_reason TEXT;")
|
| 1006 |
cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX)
|
| 1007 |
cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX)
|
| 1008 |
conn.commit()
|
|
|
|
| 1020 |
"""
|
| 1021 |
INSERT INTO signal_predictions (
|
| 1022 |
symbol, horizon, direction, conviction, regime, sniper_grade,
|
| 1023 |
+
entry_price, stop_loss, tp1, tp2, factor_scores, outcome, expires_at,
|
| 1024 |
+
is_shadow, veto_reason
|
| 1025 |
)
|
| 1026 |
+
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, 'PENDING', %s, %s, %s)
|
| 1027 |
RETURNING *;
|
| 1028 |
""",
|
| 1029 |
(
|
|
|
|
| 1039 |
float(data.get("tp2", 0.0)),
|
| 1040 |
_safe_json_dumps(data.get("factor_scores") or {}),
|
| 1041 |
data.get("expires_at"),
|
| 1042 |
+
bool(data.get("is_shadow", False)),
|
| 1043 |
+
data.get("veto_reason"),
|
| 1044 |
),
|
| 1045 |
)
|
| 1046 |
row = cur.fetchone()
|
|
|
|
| 1100 |
horizon: str,
|
| 1101 |
direction: str,
|
| 1102 |
cooldown_hours: int,
|
| 1103 |
+
is_shadow: bool = False,
|
| 1104 |
+
veto_reason: str | None = None,
|
| 1105 |
) -> dict | None:
|
| 1106 |
"""Return an active PENDING prediction or a same-direction prediction within cooldown_hours."""
|
| 1107 |
if not DATABASE_URL:
|
| 1108 |
+
return _mem.get_recent_prediction(
|
| 1109 |
+
symbol,
|
| 1110 |
+
horizon,
|
| 1111 |
+
direction,
|
| 1112 |
+
cooldown_hours,
|
| 1113 |
+
is_shadow=is_shadow,
|
| 1114 |
+
veto_reason=veto_reason,
|
| 1115 |
+
)
|
| 1116 |
sym = symbol.upper()
|
| 1117 |
with get_connection() as conn:
|
| 1118 |
with conn.cursor() as cur:
|
| 1119 |
_ensure_predictions_table(cur, conn)
|
| 1120 |
+
if not is_shadow:
|
| 1121 |
+
cur.execute(
|
| 1122 |
+
"""
|
| 1123 |
+
SELECT * FROM signal_predictions
|
| 1124 |
+
WHERE symbol = %s
|
| 1125 |
+
AND horizon = %s
|
| 1126 |
+
AND COALESCE(is_shadow, FALSE) = FALSE
|
| 1127 |
+
AND (
|
| 1128 |
+
outcome = 'PENDING'
|
| 1129 |
+
OR (direction = %s AND created_at >= NOW() - (%s * INTERVAL '1 hour'))
|
| 1130 |
+
)
|
| 1131 |
+
ORDER BY id DESC
|
| 1132 |
+
LIMIT 1;
|
| 1133 |
+
""",
|
| 1134 |
+
(sym, horizon, direction, int(cooldown_hours)),
|
| 1135 |
+
)
|
| 1136 |
+
else:
|
| 1137 |
+
cur.execute(
|
| 1138 |
+
"""
|
| 1139 |
+
SELECT * FROM signal_predictions
|
| 1140 |
+
WHERE symbol = %s
|
| 1141 |
+
AND horizon = %s
|
| 1142 |
+
AND is_shadow = TRUE
|
| 1143 |
+
AND veto_reason = %s
|
| 1144 |
+
AND (
|
| 1145 |
+
outcome = 'PENDING'
|
| 1146 |
+
OR (direction = %s AND created_at >= NOW() - (%s * INTERVAL '1 hour'))
|
| 1147 |
+
)
|
| 1148 |
+
ORDER BY id DESC
|
| 1149 |
+
LIMIT 1;
|
| 1150 |
+
""",
|
| 1151 |
+
(sym, horizon, veto_reason, direction, int(cooldown_hours)),
|
| 1152 |
+
)
|
| 1153 |
row = cur.fetchone()
|
| 1154 |
return _format_row(row) if row else None
|
| 1155 |
|
|
|
|
| 1212 |
horizon: str,
|
| 1213 |
direction: str,
|
| 1214 |
cooldown_hours: int,
|
| 1215 |
+
is_shadow: bool = False,
|
| 1216 |
+
veto_reason: str | None = None,
|
| 1217 |
) -> dict | None:
|
| 1218 |
return await asyncio.to_thread(
|
| 1219 |
db_get_recent_prediction,
|
|
|
|
| 1221 |
horizon,
|
| 1222 |
direction,
|
| 1223 |
cooldown_hours,
|
| 1224 |
+
is_shadow,
|
| 1225 |
+
veto_reason,
|
| 1226 |
)
|
| 1227 |
|
| 1228 |
|
backend/database/memory_store.py
CHANGED
|
@@ -246,6 +246,10 @@ class InMemoryDatabaseStore:
|
|
| 246 |
conviction: int,
|
| 247 |
signal_data: dict[str, Any],
|
| 248 |
) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
sym = symbol.upper()
|
| 250 |
with self._lock:
|
| 251 |
self._signal_seq += 1
|
|
@@ -255,7 +259,7 @@ class InMemoryDatabaseStore:
|
|
| 255 |
"timeframe": timeframe,
|
| 256 |
"direction": direction,
|
| 257 |
"conviction": int(conviction),
|
| 258 |
-
"signal_data": copy.deepcopy(
|
| 259 |
"created_at": _utc_now_iso(),
|
| 260 |
}
|
| 261 |
bucket = self._signals.setdefault(sym, [])
|
|
@@ -486,6 +490,8 @@ class InMemoryDatabaseStore:
|
|
| 486 |
"created_at": data.get("created_at") or now_iso,
|
| 487 |
"expires_at": data.get("expires_at") or now_iso,
|
| 488 |
"evaluated_at": data.get("evaluated_at"),
|
|
|
|
|
|
|
| 489 |
}
|
| 490 |
self._predictions[row["id"]] = row
|
| 491 |
return copy.deepcopy(row)
|
|
@@ -519,6 +525,8 @@ class InMemoryDatabaseStore:
|
|
| 519 |
horizon: str,
|
| 520 |
direction: str,
|
| 521 |
cooldown_hours: int,
|
|
|
|
|
|
|
| 522 |
) -> dict[str, Any] | None:
|
| 523 |
sym = symbol.upper()
|
| 524 |
now_dt = datetime.now(timezone.utc)
|
|
@@ -527,6 +535,13 @@ class InMemoryDatabaseStore:
|
|
| 527 |
r for r in self._predictions.values()
|
| 528 |
if r.get("symbol") == sym and r.get("horizon") == horizon
|
| 529 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
candidates.sort(key=lambda r: r["id"], reverse=True)
|
| 531 |
for r in candidates:
|
| 532 |
if r.get("outcome") == "PENDING":
|
|
@@ -569,8 +584,12 @@ class InMemoryDatabaseStore:
|
|
| 569 |
|
| 570 |
def compute_accuracy_summary_from_rows(rows: list[dict[str, Any]], days: int = 30) -> dict[str, Any]:
|
| 571 |
"""Compute unified accuracy summary from signal_predictions rows (shared by DB and memory_store)."""
|
| 572 |
-
|
| 573 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
total_evaluated = len(eval_rows)
|
| 575 |
expired_count = sum(1 for r in eval_rows if r.get("outcome") == "EXPIRED")
|
| 576 |
|
|
@@ -644,6 +663,29 @@ def compute_accuracy_summary_from_rows(rows: list[dict[str, Any]], days: int = 3
|
|
| 644 |
"opposing_avg_r": op_avg,
|
| 645 |
}
|
| 646 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 647 |
return {
|
| 648 |
"window_days": int(days),
|
| 649 |
"total_evaluated": total_evaluated,
|
|
@@ -659,6 +701,7 @@ def compute_accuracy_summary_from_rows(rows: list[dict[str, Any]], days: int = 3
|
|
| 659 |
"sniper_a_plus": _stats(sniper_rows),
|
| 660 |
"non_sniper": _stats(non_sniper_rows),
|
| 661 |
"by_factor": by_factor,
|
|
|
|
| 662 |
}
|
| 663 |
|
| 664 |
|
|
|
|
| 246 |
conviction: int,
|
| 247 |
signal_data: dict[str, Any],
|
| 248 |
) -> None:
|
| 249 |
+
clean_signal_data = signal_data
|
| 250 |
+
if isinstance(signal_data, dict) and "_shadow_trade_levels" in signal_data:
|
| 251 |
+
clean_signal_data = dict(signal_data)
|
| 252 |
+
clean_signal_data.pop("_shadow_trade_levels", None)
|
| 253 |
sym = symbol.upper()
|
| 254 |
with self._lock:
|
| 255 |
self._signal_seq += 1
|
|
|
|
| 259 |
"timeframe": timeframe,
|
| 260 |
"direction": direction,
|
| 261 |
"conviction": int(conviction),
|
| 262 |
+
"signal_data": copy.deepcopy(clean_signal_data),
|
| 263 |
"created_at": _utc_now_iso(),
|
| 264 |
}
|
| 265 |
bucket = self._signals.setdefault(sym, [])
|
|
|
|
| 490 |
"created_at": data.get("created_at") or now_iso,
|
| 491 |
"expires_at": data.get("expires_at") or now_iso,
|
| 492 |
"evaluated_at": data.get("evaluated_at"),
|
| 493 |
+
"is_shadow": bool(data.get("is_shadow", False)),
|
| 494 |
+
"veto_reason": data.get("veto_reason"),
|
| 495 |
}
|
| 496 |
self._predictions[row["id"]] = row
|
| 497 |
return copy.deepcopy(row)
|
|
|
|
| 525 |
horizon: str,
|
| 526 |
direction: str,
|
| 527 |
cooldown_hours: int,
|
| 528 |
+
is_shadow: bool = False,
|
| 529 |
+
veto_reason: str | None = None,
|
| 530 |
) -> dict[str, Any] | None:
|
| 531 |
sym = symbol.upper()
|
| 532 |
now_dt = datetime.now(timezone.utc)
|
|
|
|
| 535 |
r for r in self._predictions.values()
|
| 536 |
if r.get("symbol") == sym and r.get("horizon") == horizon
|
| 537 |
]
|
| 538 |
+
if not is_shadow:
|
| 539 |
+
candidates = [r for r in candidates if not r.get("is_shadow")]
|
| 540 |
+
else:
|
| 541 |
+
candidates = [
|
| 542 |
+
r for r in candidates
|
| 543 |
+
if r.get("is_shadow") and r.get("veto_reason") == veto_reason
|
| 544 |
+
]
|
| 545 |
candidates.sort(key=lambda r: r["id"], reverse=True)
|
| 546 |
for r in candidates:
|
| 547 |
if r.get("outcome") == "PENDING":
|
|
|
|
| 584 |
|
| 585 |
def compute_accuracy_summary_from_rows(rows: list[dict[str, Any]], days: int = 30) -> dict[str, Any]:
|
| 586 |
"""Compute unified accuracy summary from signal_predictions rows (shared by DB and memory_store)."""
|
| 587 |
+
# Exclude all is_shadow=True rows from primary metrics
|
| 588 |
+
live_rows = [r for r in rows if not r.get("is_shadow")]
|
| 589 |
+
shadow_rows = [r for r in rows if bool(r.get("is_shadow"))]
|
| 590 |
+
|
| 591 |
+
pending_count = sum(1 for r in live_rows if r.get("outcome") == "PENDING")
|
| 592 |
+
eval_rows = [r for r in live_rows if r.get("outcome") and r.get("outcome") != "PENDING" and r.get("r_multiple") is not None]
|
| 593 |
total_evaluated = len(eval_rows)
|
| 594 |
expired_count = sum(1 for r in eval_rows if r.get("outcome") == "EXPIRED")
|
| 595 |
|
|
|
|
| 663 |
"opposing_avg_r": op_avg,
|
| 664 |
}
|
| 665 |
|
| 666 |
+
# Isolated veto_effectiveness grouped by veto_reason
|
| 667 |
+
shadow_eval_rows = [
|
| 668 |
+
r for r in shadow_rows
|
| 669 |
+
if r.get("outcome") and r.get("outcome") != "PENDING" and r.get("r_multiple") is not None
|
| 670 |
+
]
|
| 671 |
+
veto_groups: dict[str, list[dict[str, Any]]] = {}
|
| 672 |
+
for r in shadow_eval_rows:
|
| 673 |
+
vr = str(r.get("veto_reason") or "UNKNOWN")
|
| 674 |
+
veto_groups.setdefault(vr, []).append(r)
|
| 675 |
+
|
| 676 |
+
veto_effectiveness: dict[str, dict[str, Any]] = {}
|
| 677 |
+
for vr, subset in sorted(veto_groups.items()):
|
| 678 |
+
n = len(subset)
|
| 679 |
+
wins = sum(1 for r in subset if float(r.get("r_multiple") or 0.0) > 0.0)
|
| 680 |
+
losses = sum(1 for r in subset if float(r.get("r_multiple") or 0.0) < 0.0)
|
| 681 |
+
avg_r = sum(float(r.get("r_multiple") or 0.0) for r in subset) / n if n > 0 else 0.0
|
| 682 |
+
veto_effectiveness[vr] = {
|
| 683 |
+
"total": n,
|
| 684 |
+
"would_have_won_pct": round((wins / n) * 100.0, 1) if n > 0 else 0.0,
|
| 685 |
+
"avg_shadow_r": round(avg_r, 3),
|
| 686 |
+
"saved_loss_rate_pct": round((losses / n) * 100.0, 1) if n > 0 else 0.0,
|
| 687 |
+
}
|
| 688 |
+
|
| 689 |
return {
|
| 690 |
"window_days": int(days),
|
| 691 |
"total_evaluated": total_evaluated,
|
|
|
|
| 701 |
"sniper_a_plus": _stats(sniper_rows),
|
| 702 |
"non_sniper": _stats(non_sniper_rows),
|
| 703 |
"by_factor": by_factor,
|
| 704 |
+
"veto_effectiveness": veto_effectiveness,
|
| 705 |
}
|
| 706 |
|
| 707 |
|
backend/database/models.py
CHANGED
|
@@ -129,7 +129,9 @@ CREATE TABLE IF NOT EXISTS signal_predictions (
|
|
| 129 |
r_multiple DOUBLE PRECISION,
|
| 130 |
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
| 131 |
expires_at TIMESTAMPTZ NOT NULL,
|
| 132 |
-
evaluated_at TIMESTAMPTZ
|
|
|
|
|
|
|
| 133 |
);
|
| 134 |
"""
|
| 135 |
|
|
|
|
| 129 |
r_multiple DOUBLE PRECISION,
|
| 130 |
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
| 131 |
expires_at TIMESTAMPTZ NOT NULL,
|
| 132 |
+
evaluated_at TIMESTAMPTZ,
|
| 133 |
+
is_shadow BOOLEAN DEFAULT FALSE,
|
| 134 |
+
veto_reason TEXT
|
| 135 |
);
|
| 136 |
"""
|
| 137 |
|
backend/engine/outcome_evaluator.py
CHANGED
|
@@ -162,8 +162,9 @@ async def async_log_prediction_if_new(signal: dict[str, Any]) -> list[dict[str,
|
|
| 162 |
"""
|
| 163 |
Independently log intraday and/or swing predictions when direction is LONG/SHORT,
|
| 164 |
conviction meets config.SIGNAL_LONG_THRESHOLD, trade_levels is present, and no active PENDING or cooldown duplicate exists.
|
|
|
|
| 165 |
"""
|
| 166 |
-
if not signal
|
| 167 |
return []
|
| 168 |
|
| 169 |
symbol = str(signal.get("symbol", "")).upper()
|
|
@@ -180,11 +181,34 @@ async def async_log_prediction_if_new(signal: dict[str, Any]) -> list[dict[str,
|
|
| 180 |
h_data = horizons.get(h_name)
|
| 181 |
if not isinstance(h_data, dict):
|
| 182 |
continue
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
try:
|
| 190 |
entry_raw = trade_levels.get("entry_price", trade_levels.get("entry"))
|
|
@@ -207,8 +231,10 @@ async def async_log_prediction_if_new(signal: dict[str, Any]) -> list[dict[str,
|
|
| 207 |
recent = await async_get_recent_prediction(
|
| 208 |
symbol=symbol,
|
| 209 |
horizon=h_name,
|
| 210 |
-
direction=
|
| 211 |
cooldown_hours=int(cfg["cooldown_hours"]),
|
|
|
|
|
|
|
| 212 |
)
|
| 213 |
if recent is not None:
|
| 214 |
continue
|
|
@@ -217,7 +243,7 @@ async def async_log_prediction_if_new(signal: dict[str, Any]) -> list[dict[str,
|
|
| 217 |
row = await async_insert_signal_prediction({
|
| 218 |
"symbol": symbol,
|
| 219 |
"horizon": h_name,
|
| 220 |
-
"direction":
|
| 221 |
"conviction": conviction,
|
| 222 |
"regime": str(h_data.get("regime", "ranging")),
|
| 223 |
"sniper_grade": sniper_grade,
|
|
@@ -226,6 +252,8 @@ async def async_log_prediction_if_new(signal: dict[str, Any]) -> list[dict[str,
|
|
| 226 |
"tp1": tp1,
|
| 227 |
"tp2": tp2,
|
| 228 |
"factor_scores": h_data.get("factor_scores") or {},
|
|
|
|
|
|
|
| 229 |
"created_at": now_dt.isoformat(),
|
| 230 |
"expires_at": expires_dt.isoformat(),
|
| 231 |
})
|
|
|
|
| 162 |
"""
|
| 163 |
Independently log intraday and/or swing predictions when direction is LONG/SHORT,
|
| 164 |
conviction meets config.SIGNAL_LONG_THRESHOLD, trade_levels is present, and no active PENDING or cooldown duplicate exists.
|
| 165 |
+
Also logs is_shadow=True counterfactual predictions per horizon veto (using vetoed_from and shadow trade levels).
|
| 166 |
"""
|
| 167 |
+
if not signal:
|
| 168 |
return []
|
| 169 |
|
| 170 |
symbol = str(signal.get("symbol", "")).upper()
|
|
|
|
| 181 |
h_data = horizons.get(h_name)
|
| 182 |
if not isinstance(h_data, dict):
|
| 183 |
continue
|
| 184 |
+
|
| 185 |
+
h_veto_reason = h_data.get("veto_reason") or signal.get("veto_reason")
|
| 186 |
+
if h_veto_reason:
|
| 187 |
+
# Shadow counterfactual tracking
|
| 188 |
+
vetoed_from = str(h_data.get("vetoed_from") or signal.get("vetoed_from") or "").upper()
|
| 189 |
+
if vetoed_from not in ("LONG", "SHORT"):
|
| 190 |
+
continue
|
| 191 |
+
trade_levels = (
|
| 192 |
+
(signal.get("_shadow_trade_levels") or {}).get(h_name)
|
| 193 |
+
or h_data.get("_shadow_trade_levels")
|
| 194 |
+
or h_data.get("trade_levels")
|
| 195 |
+
)
|
| 196 |
+
if not isinstance(trade_levels, dict):
|
| 197 |
+
continue
|
| 198 |
+
conviction = int(h_data.get("conviction") or signal.get("conviction") or min_conviction)
|
| 199 |
+
conviction = max(min_conviction, conviction)
|
| 200 |
+
pred_direction = vetoed_from
|
| 201 |
+
pred_veto_reason = str(h_veto_reason)
|
| 202 |
+
is_shadow = True
|
| 203 |
+
else:
|
| 204 |
+
# Live prediction
|
| 205 |
+
pred_direction = str(h_data.get("direction", "NEUTRAL")).upper()
|
| 206 |
+
conviction = int(h_data.get("conviction") or 0)
|
| 207 |
+
trade_levels = h_data.get("trade_levels")
|
| 208 |
+
if pred_direction not in ("LONG", "SHORT") or conviction < min_conviction or not isinstance(trade_levels, dict):
|
| 209 |
+
continue
|
| 210 |
+
pred_veto_reason = None
|
| 211 |
+
is_shadow = False
|
| 212 |
|
| 213 |
try:
|
| 214 |
entry_raw = trade_levels.get("entry_price", trade_levels.get("entry"))
|
|
|
|
| 231 |
recent = await async_get_recent_prediction(
|
| 232 |
symbol=symbol,
|
| 233 |
horizon=h_name,
|
| 234 |
+
direction=pred_direction,
|
| 235 |
cooldown_hours=int(cfg["cooldown_hours"]),
|
| 236 |
+
is_shadow=is_shadow,
|
| 237 |
+
veto_reason=pred_veto_reason,
|
| 238 |
)
|
| 239 |
if recent is not None:
|
| 240 |
continue
|
|
|
|
| 243 |
row = await async_insert_signal_prediction({
|
| 244 |
"symbol": symbol,
|
| 245 |
"horizon": h_name,
|
| 246 |
+
"direction": pred_direction,
|
| 247 |
"conviction": conviction,
|
| 248 |
"regime": str(h_data.get("regime", "ranging")),
|
| 249 |
"sniper_grade": sniper_grade,
|
|
|
|
| 252 |
"tp1": tp1,
|
| 253 |
"tp2": tp2,
|
| 254 |
"factor_scores": h_data.get("factor_scores") or {},
|
| 255 |
+
"is_shadow": is_shadow,
|
| 256 |
+
"veto_reason": pred_veto_reason,
|
| 257 |
"created_at": now_dt.isoformat(),
|
| 258 |
"expires_at": expires_dt.isoformat(),
|
| 259 |
})
|
backend/engine/signal_engine.py
CHANGED
|
@@ -3333,6 +3333,42 @@ class SignalEngine:
|
|
| 3333 |
if k != "fake_detector"
|
| 3334 |
}
|
| 3335 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3336 |
horizons_payload = {
|
| 3337 |
"intraday": {
|
| 3338 |
"timeframe": "15m-4h",
|
|
@@ -3341,6 +3377,7 @@ class SignalEngine:
|
|
| 3341 |
"conviction": intraday_conf["conviction"],
|
| 3342 |
"regime": regime_name,
|
| 3343 |
"veto_reason": intraday_conf.get("veto_reason"),
|
|
|
|
| 3344 |
"unconfirmed_single_factor": intraday_conf.get("unconfirmed_single_factor", False),
|
| 3345 |
"factor_scores": _extract_scores(factors_intraday),
|
| 3346 |
"stretch_atr": intra_ac["stretch_atr"],
|
|
@@ -3356,6 +3393,7 @@ class SignalEngine:
|
|
| 3356 |
"conviction": swing_conf["conviction"],
|
| 3357 |
"regime": regime_name,
|
| 3358 |
"veto_reason": swing_conf.get("veto_reason"),
|
|
|
|
| 3359 |
"unconfirmed_single_factor": swing_conf.get("unconfirmed_single_factor", False),
|
| 3360 |
"factor_scores": _extract_scores(factors_swing),
|
| 3361 |
"stretch_atr": swing_ac["stretch_atr"],
|
|
@@ -3371,6 +3409,7 @@ class SignalEngine:
|
|
| 3371 |
"conviction": primary_conf["conviction"],
|
| 3372 |
"regime": regime_name,
|
| 3373 |
"veto_reason": primary_conf.get("veto_reason"),
|
|
|
|
| 3374 |
"unconfirmed_single_factor": primary_conf.get("unconfirmed_single_factor", False),
|
| 3375 |
"factor_scores": _extract_scores(factors_primary),
|
| 3376 |
"stretch_atr": primary_ac["stretch_atr"],
|
|
@@ -3427,6 +3466,7 @@ class SignalEngine:
|
|
| 3427 |
"action": plan["action"],
|
| 3428 |
"quick_verdict": plan["quick_verdict"],
|
| 3429 |
"trade_levels": plan["trade_levels"],
|
|
|
|
| 3430 |
"anticipation": predictive_data["anticipation"],
|
| 3431 |
"predictive": predictive_data,
|
| 3432 |
"breakout_radar": breakout_radar_data,
|
|
|
|
| 3333 |
if k != "fake_detector"
|
| 3334 |
}
|
| 3335 |
|
| 3336 |
+
# Transient shadow trade levels for counterfactual outcome tracking
|
| 3337 |
+
shadow_trade_levels: dict[str, Any] = {}
|
| 3338 |
+
intra_vetoed_from = intraday_conf.get("vetoed_from")
|
| 3339 |
+
if intra_vetoed_from in ("LONG", "SHORT") and intraday_conf.get("veto_reason"):
|
| 3340 |
+
shadow_intra_plan = _compute_trade_plan(
|
| 3341 |
+
direction=intra_vetoed_from,
|
| 3342 |
+
mark_price=mark_price,
|
| 3343 |
+
ohlcv_1h=intraday_candles,
|
| 3344 |
+
spot_futures_score=sf_score,
|
| 3345 |
+
conviction=max(3, int(intraday_conf.get("conviction") or 3)),
|
| 3346 |
+
predictive_data=predictive_data,
|
| 3347 |
+
is_fake=False,
|
| 3348 |
+
sl_min_pct=0.008,
|
| 3349 |
+
sl_max_pct=0.04,
|
| 3350 |
+
sl_fallback_max_pct=0.035,
|
| 3351 |
+
)
|
| 3352 |
+
if shadow_intra_plan.get("trade_levels"):
|
| 3353 |
+
shadow_trade_levels["intraday"] = shadow_intra_plan["trade_levels"]
|
| 3354 |
+
|
| 3355 |
+
swing_vetoed_from = swing_conf.get("vetoed_from")
|
| 3356 |
+
if swing_vetoed_from in ("LONG", "SHORT") and swing_conf.get("veto_reason"):
|
| 3357 |
+
shadow_swing_plan = _compute_trade_plan(
|
| 3358 |
+
direction=swing_vetoed_from,
|
| 3359 |
+
mark_price=mark_price,
|
| 3360 |
+
ohlcv_1h=swing_candles,
|
| 3361 |
+
spot_futures_score=sf_score,
|
| 3362 |
+
conviction=max(3, int(swing_conf.get("conviction") or 3)),
|
| 3363 |
+
predictive_data=predictive_data,
|
| 3364 |
+
is_fake=False,
|
| 3365 |
+
sl_min_pct=0.015,
|
| 3366 |
+
sl_max_pct=0.08,
|
| 3367 |
+
sl_fallback_max_pct=0.06,
|
| 3368 |
+
)
|
| 3369 |
+
if shadow_swing_plan.get("trade_levels"):
|
| 3370 |
+
shadow_trade_levels["swing"] = shadow_swing_plan["trade_levels"]
|
| 3371 |
+
|
| 3372 |
horizons_payload = {
|
| 3373 |
"intraday": {
|
| 3374 |
"timeframe": "15m-4h",
|
|
|
|
| 3377 |
"conviction": intraday_conf["conviction"],
|
| 3378 |
"regime": regime_name,
|
| 3379 |
"veto_reason": intraday_conf.get("veto_reason"),
|
| 3380 |
+
"vetoed_from": intraday_conf.get("vetoed_from"),
|
| 3381 |
"unconfirmed_single_factor": intraday_conf.get("unconfirmed_single_factor", False),
|
| 3382 |
"factor_scores": _extract_scores(factors_intraday),
|
| 3383 |
"stretch_atr": intra_ac["stretch_atr"],
|
|
|
|
| 3393 |
"conviction": swing_conf["conviction"],
|
| 3394 |
"regime": regime_name,
|
| 3395 |
"veto_reason": swing_conf.get("veto_reason"),
|
| 3396 |
+
"vetoed_from": swing_conf.get("vetoed_from"),
|
| 3397 |
"unconfirmed_single_factor": swing_conf.get("unconfirmed_single_factor", False),
|
| 3398 |
"factor_scores": _extract_scores(factors_swing),
|
| 3399 |
"stretch_atr": swing_ac["stretch_atr"],
|
|
|
|
| 3409 |
"conviction": primary_conf["conviction"],
|
| 3410 |
"regime": regime_name,
|
| 3411 |
"veto_reason": primary_conf.get("veto_reason"),
|
| 3412 |
+
"vetoed_from": primary_conf.get("vetoed_from"),
|
| 3413 |
"unconfirmed_single_factor": primary_conf.get("unconfirmed_single_factor", False),
|
| 3414 |
"factor_scores": _extract_scores(factors_primary),
|
| 3415 |
"stretch_atr": primary_ac["stretch_atr"],
|
|
|
|
| 3466 |
"action": plan["action"],
|
| 3467 |
"quick_verdict": plan["quick_verdict"],
|
| 3468 |
"trade_levels": plan["trade_levels"],
|
| 3469 |
+
"_shadow_trade_levels": shadow_trade_levels,
|
| 3470 |
"anticipation": predictive_data["anticipation"],
|
| 3471 |
"predictive": predictive_data,
|
| 3472 |
"breakout_radar": breakout_radar_data,
|
backend/main.py
CHANGED
|
@@ -211,6 +211,8 @@ async def _process_pair(
|
|
| 211 |
await async_log_prediction_if_new(signal)
|
| 212 |
except Exception as exc:
|
| 213 |
logger.debug("[%s] Failed to log forward prediction: %s", symbol, exc)
|
|
|
|
|
|
|
| 214 |
|
| 215 |
# Persist market snapshots in a single batch roundtrip
|
| 216 |
snapshots_to_save = []
|
|
|
|
| 211 |
await async_log_prediction_if_new(signal)
|
| 212 |
except Exception as exc:
|
| 213 |
logger.debug("[%s] Failed to log forward prediction: %s", symbol, exc)
|
| 214 |
+
finally:
|
| 215 |
+
signal.pop("_shadow_trade_levels", None)
|
| 216 |
|
| 217 |
# Persist market snapshots in a single batch roundtrip
|
| 218 |
snapshots_to_save = []
|
backend/routers/signals.py
CHANGED
|
@@ -338,6 +338,8 @@ async def refresh_signal(symbol: str, request: Request):
|
|
| 338 |
await async_log_prediction_if_new(signal)
|
| 339 |
except Exception as exc:
|
| 340 |
logger.debug("[%s] Failed to log forward prediction: %s", sym, exc)
|
|
|
|
|
|
|
| 341 |
|
| 342 |
# Persist market snapshots in a single batch
|
| 343 |
snapshots_to_save = []
|
|
|
|
| 338 |
await async_log_prediction_if_new(signal)
|
| 339 |
except Exception as exc:
|
| 340 |
logger.debug("[%s] Failed to log forward prediction: %s", sym, exc)
|
| 341 |
+
finally:
|
| 342 |
+
signal.pop("_shadow_trade_levels", None)
|
| 343 |
|
| 344 |
# Persist market snapshots in a single batch
|
| 345 |
snapshots_to_save = []
|
frontend/src/types/index.ts
CHANGED
|
@@ -236,6 +236,8 @@ export interface SignalHorizon {
|
|
| 236 |
conviction: number;
|
| 237 |
regime?: string;
|
| 238 |
veto_reason?: string | null;
|
|
|
|
|
|
|
| 239 |
factor_scores?: Record<string, number>;
|
| 240 |
stretch_atr: number;
|
| 241 |
anti_chasing_status: 'CLEAN' | 'ANTI_CHASING_PENALTY' | 'ANTI_CHASING_EXTREME' | string;
|
|
@@ -257,6 +259,13 @@ export interface AccuracyHorizonStats {
|
|
| 257 |
avg_r: number;
|
| 258 |
}
|
| 259 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
export interface AccuracySummary {
|
| 261 |
window_days: number;
|
| 262 |
total_evaluated: number;
|
|
@@ -282,6 +291,7 @@ export interface AccuracySummary {
|
|
| 282 |
opposing_avg_r: number;
|
| 283 |
}
|
| 284 |
>;
|
|
|
|
| 285 |
}
|
| 286 |
|
| 287 |
export interface Signal {
|
|
|
|
| 236 |
conviction: number;
|
| 237 |
regime?: string;
|
| 238 |
veto_reason?: string | null;
|
| 239 |
+
vetoed_from?: Direction | string | null;
|
| 240 |
+
unconfirmed_single_factor?: boolean;
|
| 241 |
factor_scores?: Record<string, number>;
|
| 242 |
stretch_atr: number;
|
| 243 |
anti_chasing_status: 'CLEAN' | 'ANTI_CHASING_PENALTY' | 'ANTI_CHASING_EXTREME' | string;
|
|
|
|
| 259 |
avg_r: number;
|
| 260 |
}
|
| 261 |
|
| 262 |
+
export interface VetoEffectivenessStats {
|
| 263 |
+
total: number;
|
| 264 |
+
would_have_won_pct: number;
|
| 265 |
+
avg_shadow_r: number;
|
| 266 |
+
saved_loss_rate_pct: number;
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
export interface AccuracySummary {
|
| 270 |
window_days: number;
|
| 271 |
total_evaluated: number;
|
|
|
|
| 291 |
opposing_avg_r: number;
|
| 292 |
}
|
| 293 |
>;
|
| 294 |
+
veto_effectiveness?: Record<string, VetoEffectivenessStats>;
|
| 295 |
}
|
| 296 |
|
| 297 |
export interface Signal {
|
tests/test_five_exchange_whale_pov.py
CHANGED
|
@@ -1261,4 +1261,286 @@ def test_live_threshold_3_blocks_unconfirmed_single_factor():
|
|
| 1261 |
assert res_multi["horizons"]["intraday"].get("unconfirmed_single_factor", False) is False
|
| 1262 |
|
| 1263 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1264 |
|
|
|
|
| 1261 |
assert res_multi["horizons"]["intraday"].get("unconfirmed_single_factor", False) is False
|
| 1262 |
|
| 1263 |
|
| 1264 |
+
@pytest.mark.anyio
|
| 1265 |
+
async def test_shadow_veto_logging_isolation_and_per_horizon_anti_chasing():
|
| 1266 |
+
"""
|
| 1267 |
+
Module E.1 Task 5 Test 1:
|
| 1268 |
+
1. Logs a horizon-only ANTI_CHASING_EXTREME shadow prediction on intraday while top-level veto_reason is None
|
| 1269 |
+
(opposing swing logged live is_shadow=False).
|
| 1270 |
+
2. Verifies a PENDING shadow row does not block logging a live is_shadow=False signal on the next cycle.
|
| 1271 |
+
3. Verifies two different veto_reason values track independent cooldowns.
|
| 1272 |
+
"""
|
| 1273 |
+
from database.memory_store import memory_store
|
| 1274 |
+
from engine.outcome_evaluator import async_log_prediction_if_new
|
| 1275 |
+
|
| 1276 |
+
memory_store.reset()
|
| 1277 |
+
|
| 1278 |
+
# Step 1: Signal with top-level veto_reason=None, intraday vetoed with ANTI_CHASING_EXTREME, swing live SHORT
|
| 1279 |
+
sig = {
|
| 1280 |
+
"symbol": "BTCUSDT",
|
| 1281 |
+
"direction": "SHORT",
|
| 1282 |
+
"conviction": 4,
|
| 1283 |
+
"veto_reason": None,
|
| 1284 |
+
"sniper_grade": "SWING_SETUP",
|
| 1285 |
+
"horizons": {
|
| 1286 |
+
"intraday": {
|
| 1287 |
+
"direction": "NEUTRAL",
|
| 1288 |
+
"vetoed_from": "LONG",
|
| 1289 |
+
"veto_reason": "ANTI_CHASING_EXTREME",
|
| 1290 |
+
"conviction": 4,
|
| 1291 |
+
"regime": "trending",
|
| 1292 |
+
"trade_levels": None,
|
| 1293 |
+
"factor_scores": {"market_structure": 2, "spot_futures_cvd": 1},
|
| 1294 |
+
},
|
| 1295 |
+
"swing": {
|
| 1296 |
+
"direction": "SHORT",
|
| 1297 |
+
"conviction": 4,
|
| 1298 |
+
"regime": "trending",
|
| 1299 |
+
"veto_reason": None,
|
| 1300 |
+
"trade_levels": {"entry_price": 50000.0, "stop_loss": 51000.0, "take_profit_1": 49000.0, "take_profit_2": 48000.0},
|
| 1301 |
+
"factor_scores": {"market_structure": -2, "spot_futures_cvd": -1},
|
| 1302 |
+
},
|
| 1303 |
+
},
|
| 1304 |
+
"_shadow_trade_levels": {
|
| 1305 |
+
"intraday": {"entry_price": 50000.0, "stop_loss": 49000.0, "take_profit_1": 51000.0, "take_profit_2": 52000.0},
|
| 1306 |
+
},
|
| 1307 |
+
}
|
| 1308 |
+
|
| 1309 |
+
with patch("database.db.DATABASE_URL", ""):
|
| 1310 |
+
logged = await async_log_prediction_if_new(sig)
|
| 1311 |
+
|
| 1312 |
+
assert len(logged) == 2
|
| 1313 |
+
intraday_pred = next(r for r in logged if r["horizon"] == "intraday")
|
| 1314 |
+
swing_pred = next(r for r in logged if r["horizon"] == "swing")
|
| 1315 |
+
|
| 1316 |
+
assert intraday_pred["is_shadow"] is True
|
| 1317 |
+
assert intraday_pred["veto_reason"] == "ANTI_CHASING_EXTREME"
|
| 1318 |
+
assert intraday_pred["direction"] == "LONG"
|
| 1319 |
+
assert intraday_pred["entry_price"] == 50000.0
|
| 1320 |
+
assert intraday_pred["stop_loss"] == 49000.0
|
| 1321 |
+
assert intraday_pred["tp1"] == 51000.0
|
| 1322 |
+
assert intraday_pred["tp2"] == 52000.0
|
| 1323 |
+
assert intraday_pred["outcome"] == "PENDING"
|
| 1324 |
+
|
| 1325 |
+
assert swing_pred["is_shadow"] is False
|
| 1326 |
+
assert swing_pred["veto_reason"] is None
|
| 1327 |
+
assert swing_pred["direction"] == "SHORT"
|
| 1328 |
+
assert swing_pred["outcome"] == "PENDING"
|
| 1329 |
+
|
| 1330 |
+
# Step 2: Next cycle, intraday anti-chasing clears and becomes live LONG.
|
| 1331 |
+
# The PENDING shadow row must NOT block logging the live is_shadow=False prediction!
|
| 1332 |
+
live_sig = {
|
| 1333 |
+
"symbol": "BTCUSDT",
|
| 1334 |
+
"direction": "LONG",
|
| 1335 |
+
"conviction": 4,
|
| 1336 |
+
"veto_reason": None,
|
| 1337 |
+
"sniper_grade": "INTRADAY_ONLY",
|
| 1338 |
+
"horizons": {
|
| 1339 |
+
"intraday": {
|
| 1340 |
+
"direction": "LONG",
|
| 1341 |
+
"conviction": 4,
|
| 1342 |
+
"regime": "trending",
|
| 1343 |
+
"veto_reason": None,
|
| 1344 |
+
"trade_levels": {"entry_price": 50100.0, "stop_loss": 49100.0, "take_profit_1": 51100.0, "take_profit_2": 52100.0},
|
| 1345 |
+
"factor_scores": {"market_structure": 2, "spot_futures_cvd": 1},
|
| 1346 |
+
},
|
| 1347 |
+
"swing": {
|
| 1348 |
+
# swing already has an active PENDING prediction, should not re-log
|
| 1349 |
+
"direction": "SHORT",
|
| 1350 |
+
"conviction": 4,
|
| 1351 |
+
"regime": "trending",
|
| 1352 |
+
"veto_reason": None,
|
| 1353 |
+
"trade_levels": {"entry_price": 50000.0, "stop_loss": 51000.0, "take_profit_1": 49000.0, "take_profit_2": 48000.0},
|
| 1354 |
+
},
|
| 1355 |
+
},
|
| 1356 |
+
}
|
| 1357 |
+
|
| 1358 |
+
with patch("database.db.DATABASE_URL", ""):
|
| 1359 |
+
logged_live = await async_log_prediction_if_new(live_sig)
|
| 1360 |
+
|
| 1361 |
+
assert len(logged_live) == 1
|
| 1362 |
+
assert logged_live[0]["horizon"] == "intraday"
|
| 1363 |
+
assert logged_live[0]["is_shadow"] is False
|
| 1364 |
+
assert logged_live[0]["direction"] == "LONG"
|
| 1365 |
+
assert logged_live[0]["entry_price"] == 50100.0
|
| 1366 |
+
|
| 1367 |
+
# Step 3: Two different veto_reason values track independent cooldowns
|
| 1368 |
+
eth_fake = {
|
| 1369 |
+
"symbol": "ETHUSDT",
|
| 1370 |
+
"direction": "NEUTRAL",
|
| 1371 |
+
"conviction": 4,
|
| 1372 |
+
"veto_reason": "FAKE_DETECTOR",
|
| 1373 |
+
"sniper_grade": "WAIT",
|
| 1374 |
+
"horizons": {
|
| 1375 |
+
"intraday": {
|
| 1376 |
+
"direction": "NEUTRAL",
|
| 1377 |
+
"vetoed_from": "LONG",
|
| 1378 |
+
"veto_reason": "FAKE_DETECTOR",
|
| 1379 |
+
"conviction": 4,
|
| 1380 |
+
"regime": "ranging",
|
| 1381 |
+
"trade_levels": None,
|
| 1382 |
+
},
|
| 1383 |
+
},
|
| 1384 |
+
"_shadow_trade_levels": {
|
| 1385 |
+
"intraday": {"entry_price": 3000.0, "stop_loss": 2900.0, "take_profit_1": 3100.0, "take_profit_2": 3200.0},
|
| 1386 |
+
},
|
| 1387 |
+
}
|
| 1388 |
+
|
| 1389 |
+
with patch("database.db.DATABASE_URL", ""):
|
| 1390 |
+
logged_fake = await async_log_prediction_if_new(eth_fake)
|
| 1391 |
+
assert len(logged_fake) == 1
|
| 1392 |
+
assert logged_fake[0]["veto_reason"] == "FAKE_DETECTOR"
|
| 1393 |
+
assert logged_fake[0]["is_shadow"] is True
|
| 1394 |
+
|
| 1395 |
+
# Immediate duplicate FAKE_DETECTOR is blocked
|
| 1396 |
+
with patch("database.db.DATABASE_URL", ""):
|
| 1397 |
+
logged_fake_dup = await async_log_prediction_if_new(eth_fake)
|
| 1398 |
+
assert len(logged_fake_dup) == 0
|
| 1399 |
+
|
| 1400 |
+
# But CROWDED_FUNDING on the same symbol/horizon/direction tracks independent cooldown and logs!
|
| 1401 |
+
eth_crowded = {
|
| 1402 |
+
"symbol": "ETHUSDT",
|
| 1403 |
+
"direction": "NEUTRAL",
|
| 1404 |
+
"conviction": 4,
|
| 1405 |
+
"veto_reason": "CROWDED_FUNDING",
|
| 1406 |
+
"sniper_grade": "WAIT",
|
| 1407 |
+
"horizons": {
|
| 1408 |
+
"intraday": {
|
| 1409 |
+
"direction": "NEUTRAL",
|
| 1410 |
+
"vetoed_from": "LONG",
|
| 1411 |
+
"veto_reason": "CROWDED_FUNDING",
|
| 1412 |
+
"conviction": 4,
|
| 1413 |
+
"regime": "ranging",
|
| 1414 |
+
"trade_levels": None,
|
| 1415 |
+
},
|
| 1416 |
+
},
|
| 1417 |
+
"_shadow_trade_levels": {
|
| 1418 |
+
"intraday": {"entry_price": 3000.0, "stop_loss": 2900.0, "take_profit_1": 3100.0, "take_profit_2": 3200.0},
|
| 1419 |
+
},
|
| 1420 |
+
}
|
| 1421 |
+
|
| 1422 |
+
with patch("database.db.DATABASE_URL", ""):
|
| 1423 |
+
logged_crowded = await async_log_prediction_if_new(eth_crowded)
|
| 1424 |
+
assert len(logged_crowded) == 1
|
| 1425 |
+
assert logged_crowded[0]["veto_reason"] == "CROWDED_FUNDING"
|
| 1426 |
+
assert logged_crowded[0]["is_shadow"] is True
|
| 1427 |
+
|
| 1428 |
+
|
| 1429 |
+
def test_accuracy_summary_excludes_shadow_from_primary_and_computes_veto_effectiveness():
|
| 1430 |
+
"""
|
| 1431 |
+
Module E.1 Task 5 Test 2:
|
| 1432 |
+
Inserts evaluated is_shadow=False and is_shadow=True rows (FAKE_DETECTOR -1.0R, CROWDED_FUNDING +2.0R),
|
| 1433 |
+
queries GET /api/signals/accuracy?days=30, and asserts main total_evaluated, win_rate_pct, by_factor
|
| 1434 |
+
ignore shadow rows while veto_effectiveness reports saved_loss_rate_pct and would_have_won_pct accurately.
|
| 1435 |
+
"""
|
| 1436 |
+
from fastapi.testclient import TestClient
|
| 1437 |
+
from main import app
|
| 1438 |
+
from database.memory_store import memory_store
|
| 1439 |
+
|
| 1440 |
+
memory_store.reset()
|
| 1441 |
+
|
| 1442 |
+
# 1. Insert 2 live predictions (1 win +1.5R, 1 loss -1.0R) -> total_evaluated=2, win_rate=50.0%
|
| 1443 |
+
p1 = memory_store.insert_signal_prediction({
|
| 1444 |
+
"symbol": "BTCUSDT",
|
| 1445 |
+
"horizon": "intraday",
|
| 1446 |
+
"direction": "LONG",
|
| 1447 |
+
"conviction": 4,
|
| 1448 |
+
"regime": "trending",
|
| 1449 |
+
"sniper_grade": "SNIPER_A_PLUS",
|
| 1450 |
+
"entry_price": 50000.0,
|
| 1451 |
+
"stop_loss": 49000.0,
|
| 1452 |
+
"tp1": 51500.0,
|
| 1453 |
+
"tp2": 53000.0,
|
| 1454 |
+
"factor_scores": {"market_structure": 2},
|
| 1455 |
+
"is_shadow": False,
|
| 1456 |
+
})
|
| 1457 |
+
memory_store.update_signal_prediction_outcome(p1["id"], "TP1_BREAKEVEN", 51500.0, 1.5)
|
| 1458 |
+
|
| 1459 |
+
p2 = memory_store.insert_signal_prediction({
|
| 1460 |
+
"symbol": "BTCUSDT",
|
| 1461 |
+
"horizon": "intraday",
|
| 1462 |
+
"direction": "LONG",
|
| 1463 |
+
"conviction": 4,
|
| 1464 |
+
"regime": "trending",
|
| 1465 |
+
"sniper_grade": "INTRADAY_ONLY",
|
| 1466 |
+
"entry_price": 50000.0,
|
| 1467 |
+
"stop_loss": 49000.0,
|
| 1468 |
+
"tp1": 51500.0,
|
| 1469 |
+
"tp2": 53000.0,
|
| 1470 |
+
"factor_scores": {"market_structure": 2},
|
| 1471 |
+
"is_shadow": False,
|
| 1472 |
+
})
|
| 1473 |
+
memory_store.update_signal_prediction_outcome(p2["id"], "SL", 49000.0, -1.0)
|
| 1474 |
+
|
| 1475 |
+
# 2. Insert shadow counterfactual predictions:
|
| 1476 |
+
# FAKE_DETECTOR: r_multiple = -1.0 (saved loss)
|
| 1477 |
+
p_fake = memory_store.insert_signal_prediction({
|
| 1478 |
+
"symbol": "ETHUSDT",
|
| 1479 |
+
"horizon": "intraday",
|
| 1480 |
+
"direction": "LONG",
|
| 1481 |
+
"conviction": 4,
|
| 1482 |
+
"regime": "ranging",
|
| 1483 |
+
"sniper_grade": "WAIT",
|
| 1484 |
+
"entry_price": 3000.0,
|
| 1485 |
+
"stop_loss": 2900.0,
|
| 1486 |
+
"tp1": 3100.0,
|
| 1487 |
+
"tp2": 3200.0,
|
| 1488 |
+
"factor_scores": {"market_structure": -2},
|
| 1489 |
+
"is_shadow": True,
|
| 1490 |
+
"veto_reason": "FAKE_DETECTOR",
|
| 1491 |
+
})
|
| 1492 |
+
memory_store.update_signal_prediction_outcome(p_fake["id"], "SL", 2900.0, -1.0)
|
| 1493 |
+
|
| 1494 |
+
# CROWDED_FUNDING: r_multiple = +2.0 (missed win / would have won)
|
| 1495 |
+
p_crowd = memory_store.insert_signal_prediction({
|
| 1496 |
+
"symbol": "SOLUSDT",
|
| 1497 |
+
"horizon": "swing",
|
| 1498 |
+
"direction": "SHORT",
|
| 1499 |
+
"conviction": 4,
|
| 1500 |
+
"regime": "trending",
|
| 1501 |
+
"sniper_grade": "WAIT",
|
| 1502 |
+
"entry_price": 100.0,
|
| 1503 |
+
"stop_loss": 105.0,
|
| 1504 |
+
"tp1": 95.0,
|
| 1505 |
+
"tp2": 90.0,
|
| 1506 |
+
"factor_scores": {"funding_rate": -2},
|
| 1507 |
+
"is_shadow": True,
|
| 1508 |
+
"veto_reason": "CROWDED_FUNDING",
|
| 1509 |
+
})
|
| 1510 |
+
memory_store.update_signal_prediction_outcome(p_crowd["id"], "TP2", 90.0, 2.0)
|
| 1511 |
+
|
| 1512 |
+
client = TestClient(app)
|
| 1513 |
+
with patch("database.db.DATABASE_URL", ""):
|
| 1514 |
+
resp = client.get("/api/signals/accuracy?days=30")
|
| 1515 |
+
|
| 1516 |
+
assert resp.status_code == 200
|
| 1517 |
+
data = resp.json()
|
| 1518 |
+
|
| 1519 |
+
# Primary metrics must completely exclude shadow rows
|
| 1520 |
+
assert data["total_evaluated"] == 2
|
| 1521 |
+
assert data["win_rate_pct"] == 50.0
|
| 1522 |
+
assert data["avg_r_multiple"] == 0.25
|
| 1523 |
+
assert data["by_horizon"]["intraday"]["total"] == 2
|
| 1524 |
+
assert data["by_horizon"]["swing"]["total"] == 0
|
| 1525 |
+
|
| 1526 |
+
# by_factor must also exclude shadow rows
|
| 1527 |
+
ms_factor = data["by_factor"].get("market_structure", {})
|
| 1528 |
+
assert ms_factor.get("aligned_trades") == 2
|
| 1529 |
+
|
| 1530 |
+
# Isolated veto_effectiveness section
|
| 1531 |
+
veto_eff = data.get("veto_effectiveness", {})
|
| 1532 |
+
assert "FAKE_DETECTOR" in veto_eff
|
| 1533 |
+
assert veto_eff["FAKE_DETECTOR"]["total"] == 1
|
| 1534 |
+
assert veto_eff["FAKE_DETECTOR"]["saved_loss_rate_pct"] == 100.0
|
| 1535 |
+
assert veto_eff["FAKE_DETECTOR"]["would_have_won_pct"] == 0.0
|
| 1536 |
+
assert veto_eff["FAKE_DETECTOR"]["avg_shadow_r"] == -1.0
|
| 1537 |
+
|
| 1538 |
+
assert "CROWDED_FUNDING" in veto_eff
|
| 1539 |
+
assert veto_eff["CROWDED_FUNDING"]["total"] == 1
|
| 1540 |
+
assert veto_eff["CROWDED_FUNDING"]["saved_loss_rate_pct"] == 0.0
|
| 1541 |
+
assert veto_eff["CROWDED_FUNDING"]["would_have_won_pct"] == 100.0
|
| 1542 |
+
assert veto_eff["CROWDED_FUNDING"]["avg_shadow_r"] == 2.0
|
| 1543 |
+
|
| 1544 |
+
|
| 1545 |
+
|
| 1546 |
|