Update app.py
Browse files
app.py
CHANGED
|
@@ -51,54 +51,79 @@ def entropy(p):
|
|
| 51 |
|
| 52 |
|
| 53 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 54 |
-
# LAYER 1 β
|
| 55 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
def update_indicator_performance(family: str, was_correct: bool):
|
| 64 |
-
"""Update performance tracking for a signal family"""
|
| 65 |
perf = _signal_performance[family]
|
| 66 |
perf["total"] += 1
|
| 67 |
if was_correct:
|
| 68 |
perf["correct"] += 1
|
| 69 |
|
| 70 |
-
# Keep only last 100 for rolling accuracy
|
| 71 |
if perf["total"] > 100:
|
| 72 |
perf["correct"] = perf["correct"] * 0.9
|
| 73 |
perf["total"] = int(perf["total"] * 0.9)
|
| 74 |
|
| 75 |
-
# Calculate weight multiplier based on accuracy
|
| 76 |
accuracy = perf["correct"] / max(perf["total"], 1)
|
| 77 |
-
# Accuracy 50% = 1.0x, 70% = 1.3x, 30% = 0.7x
|
| 78 |
perf["weight_multiplier"] = 0.5 + accuracy
|
| 79 |
|
| 80 |
|
| 81 |
def get_dynamic_weight(base_weight: float, family: str) -> float:
|
| 82 |
-
"""Get dynamically adjusted weight for a signal family"""
|
| 83 |
perf = _signal_performance[family]
|
| 84 |
adjusted = base_weight * perf["weight_multiplier"]
|
| 85 |
-
# Keep within reasonable bounds
|
| 86 |
return max(base_weight * 0.5, min(base_weight * 1.5, adjusted))
|
| 87 |
|
| 88 |
|
| 89 |
def record_prediction_outcome(symbol: str, predicted_direction: str, confidence: float, actual_price_change: float):
|
| 90 |
-
"""Call this after price moves to track accuracy"""
|
| 91 |
was_correct = (predicted_direction == "bullish" and actual_price_change > 0) or \
|
| 92 |
(predicted_direction == "bearish" and actual_price_change < 0) or \
|
| 93 |
(predicted_direction == "neutral" and abs(actual_price_change) < 0.005)
|
| 94 |
|
| 95 |
-
# Update each signal family based on what contributed
|
| 96 |
-
# This is simplified - in production you'd track per-signal
|
| 97 |
families = ["trend", "momentum", "volatility", "sentiment", "volume_flow", "order_flow"]
|
| 98 |
for family in families:
|
| 99 |
update_indicator_performance(family, was_correct)
|
| 100 |
|
| 101 |
-
# Store for calibration
|
| 102 |
_recent_predictions.append({
|
| 103 |
"timestamp": datetime.now().isoformat(),
|
| 104 |
"confidence": confidence,
|
|
@@ -106,47 +131,37 @@ def record_prediction_outcome(symbol: str, predicted_direction: str, confidence:
|
|
| 106 |
"symbol": symbol
|
| 107 |
})
|
| 108 |
|
| 109 |
-
# Keep only last 100
|
| 110 |
while len(_recent_predictions) > 100:
|
| 111 |
_recent_predictions.pop(0)
|
| 112 |
|
| 113 |
|
| 114 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 115 |
-
# LAYER
|
| 116 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 117 |
|
| 118 |
def indicator_families(idx: int) -> Set[str]:
|
| 119 |
-
"""
|
| 120 |
-
Multi-label classification οΏ½οΏ½ a signal can belong to multiple families.
|
| 121 |
-
UPDATED: Added order_flow family for CVD-based signals.
|
| 122 |
-
"""
|
| 123 |
mapping = {
|
| 124 |
-
0: {"volatility"},
|
| 125 |
-
1: {"volatility"},
|
| 126 |
-
2: {"momentum"},
|
| 127 |
-
3: {"volatility"},
|
| 128 |
-
4: {"trend"},
|
| 129 |
-
5: {"trend"},
|
| 130 |
-
6: {"trend"},
|
| 131 |
-
7: {"momentum"},
|
| 132 |
-
8: {"momentum", "volume_flow"},
|
| 133 |
-
9: {"momentum"},
|
| 134 |
-
10: {"sentiment"},
|
| 135 |
-
11: {"sentiment"},
|
| 136 |
-
12: {"sentiment"},
|
| 137 |
-
13: {"order_flow", "sentiment"},
|
| 138 |
-
14: {"order_flow"},
|
| 139 |
-
15: {"order_flow"},
|
| 140 |
}
|
| 141 |
return mapping.get(idx, {"other"})
|
| 142 |
|
| 143 |
|
| 144 |
def signal_strength(score: float) -> float:
|
| 145 |
-
"""
|
| 146 |
-
Entropy-based strength.
|
| 147 |
-
p=0.5 β max entropy β strengthβ0.15
|
| 148 |
-
pβ0 or 1 β low entropy β strengthβ1.0
|
| 149 |
-
"""
|
| 150 |
e = entropy(score)
|
| 151 |
max_e = entropy(0.5)
|
| 152 |
raw = 1.0 - (e / max_e)
|
|
@@ -154,10 +169,6 @@ def signal_strength(score: float) -> float:
|
|
| 154 |
|
| 155 |
|
| 156 |
def regime_gate(regime: str, families: Set[str]) -> float:
|
| 157 |
-
"""
|
| 158 |
-
Selective amplification per family, per regime.
|
| 159 |
-
UPDATED: Added order_flow gating.
|
| 160 |
-
"""
|
| 161 |
gate = 1.0
|
| 162 |
|
| 163 |
if regime in ("trend", "strong_trend"):
|
|
@@ -166,7 +177,7 @@ def regime_gate(regime: str, families: Set[str]) -> float:
|
|
| 166 |
if "momentum" in families:
|
| 167 |
gate = max(gate, 1.2)
|
| 168 |
if "order_flow" in families:
|
| 169 |
-
gate = max(gate, 1.15)
|
| 170 |
if "volatility" in families and "trend" not in families:
|
| 171 |
gate = min(gate, 0.9)
|
| 172 |
|
|
@@ -174,7 +185,7 @@ def regime_gate(regime: str, families: Set[str]) -> float:
|
|
| 174 |
if "momentum" in families or "volatility" in families:
|
| 175 |
gate = max(gate, 1.2)
|
| 176 |
if "order_flow" in families:
|
| 177 |
-
gate = min(gate, 0.7)
|
| 178 |
if "trend" in families:
|
| 179 |
gate = min(gate, 0.5)
|
| 180 |
|
|
@@ -186,7 +197,6 @@ def regime_gate(regime: str, families: Set[str]) -> float:
|
|
| 186 |
elif "volatility" in families:
|
| 187 |
gate = min(gate, 0.6)
|
| 188 |
|
| 189 |
-
# volume_flow & sentiment never gated β always 1.0
|
| 190 |
if families.issubset({"volume_flow", "sentiment"}):
|
| 191 |
return 1.0
|
| 192 |
|
|
@@ -194,17 +204,10 @@ def regime_gate(regime: str, families: Set[str]) -> float:
|
|
| 194 |
|
| 195 |
|
| 196 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 197 |
-
# LAYER
|
| 198 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 199 |
|
| 200 |
-
# Cache for cross-asset data
|
| 201 |
-
_cross_asset_cache = {}
|
| 202 |
-
|
| 203 |
def calculate_cross_asset_impact(symbol: str, btc_iv: float, eth_iv: float) -> dict:
|
| 204 |
-
"""
|
| 205 |
-
Calculate how BTC/ETH market conditions affect the current symbol.
|
| 206 |
-
For BTC/USDT itself, this is less relevant.
|
| 207 |
-
"""
|
| 208 |
is_btc = "BTC" in symbol.upper()
|
| 209 |
is_eth = "ETH" in symbol.upper()
|
| 210 |
|
|
@@ -216,20 +219,16 @@ def calculate_cross_asset_impact(symbol: str, btc_iv: float, eth_iv: float) -> d
|
|
| 216 |
}
|
| 217 |
|
| 218 |
if is_btc:
|
| 219 |
-
# BTC is the leader - no correlation adjustment needed
|
| 220 |
return result
|
| 221 |
|
| 222 |
-
# For ETH and alts, BTC movement matters
|
| 223 |
if btc_iv:
|
| 224 |
-
# High BTC volatility spills over to alts
|
| 225 |
if btc_iv > 70:
|
| 226 |
-
result["volatility_spillover"] = 1.15
|
| 227 |
result["btc_dominance_signal"] = "btc_volatile"
|
| 228 |
elif btc_iv > 50:
|
| 229 |
result["volatility_spillover"] = 1.05
|
| 230 |
|
| 231 |
if is_eth:
|
| 232 |
-
# ETH has its own dynamics
|
| 233 |
if eth_iv and eth_iv > 80:
|
| 234 |
result["volatility_spillover"] = max(result["volatility_spillover"], 1.1)
|
| 235 |
|
|
@@ -237,17 +236,13 @@ def calculate_cross_asset_impact(symbol: str, btc_iv: float, eth_iv: float) -> d
|
|
| 237 |
|
| 238 |
|
| 239 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 240 |
-
# LAYER 2 β INFERENCE
|
| 241 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 242 |
|
| 243 |
TEMPERATURE = 1.5
|
| 244 |
|
| 245 |
|
| 246 |
def aggregate_log_odds(signals: List[Dict], regime: str):
|
| 247 |
-
"""
|
| 248 |
-
Temperature-scaled log-odds with entropy strength + selective gating.
|
| 249 |
-
NOW WITH DYNAMIC WEIGHTS based on historical performance.
|
| 250 |
-
"""
|
| 251 |
s_lo, w_total = 0.0, 0.0
|
| 252 |
|
| 253 |
for i, sig in enumerate(signals):
|
|
@@ -255,17 +250,13 @@ def aggregate_log_odds(signals: List[Dict], regime: str):
|
|
| 255 |
base_weight = sig["weight"]
|
| 256 |
families = indicator_families(i)
|
| 257 |
|
| 258 |
-
# Get primary family for weight adjustment
|
| 259 |
primary_family = next(iter(families)) if families else "other"
|
| 260 |
-
|
| 261 |
-
# Apply dynamic weight adjustment based on historical performance
|
| 262 |
dynamic_weight = get_dynamic_weight(base_weight, primary_family)
|
| 263 |
|
| 264 |
strength = signal_strength(score)
|
| 265 |
gate = regime_gate(regime, families)
|
| 266 |
final_weight = dynamic_weight * strength * gate
|
| 267 |
|
| 268 |
-
# Temperature scaling β dampens extreme probabilities
|
| 269 |
s_lo += (logit(score) / TEMPERATURE) * final_weight
|
| 270 |
w_total += final_weight
|
| 271 |
|
|
@@ -278,7 +269,7 @@ def aggregate_log_odds(signals: List[Dict], regime: str):
|
|
| 278 |
|
| 279 |
|
| 280 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 281 |
-
# LAYER 3 β CALIBRATION
|
| 282 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 283 |
|
| 284 |
def cornish_fisher_calibrate(prob, skew, kurt):
|
|
@@ -312,7 +303,7 @@ def apply_penalties_log_space(penalties: List[float], floor: float = 0.15) -> fl
|
|
| 312 |
|
| 313 |
|
| 314 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 315 |
-
# LAYER 4 β INTERPRETATION
|
| 316 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 317 |
|
| 318 |
def fear_index(garch_vol, adx_val, streak_obj, dd_obj, vol_spike, r_vol3, a_vol20, c3, c4):
|
|
@@ -475,7 +466,7 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 475 |
confidence_interval_80 = mc.get("confidence_interval_80", [last_close * 0.95, last_close * 1.05])
|
| 476 |
confidence_interval_90 = mc.get("confidence_interval_90", [last_close * 0.92, last_close * 1.08])
|
| 477 |
|
| 478 |
-
# ββ
|
| 479 |
cumulative_delta = sentiment.get("cumulativeDelta", 0)
|
| 480 |
delta_trend = sentiment.get("deltaTrend", "neutral")
|
| 481 |
delta_strength = sentiment.get("deltaStrength", 0)
|
|
@@ -491,7 +482,6 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 491 |
normalized_slope = linear_regression_slope(closes, 200)
|
| 492 |
primary_is_bull = primary_trend == "bull"
|
| 493 |
|
| 494 |
-
# Cross-asset correlation impact
|
| 495 |
cross_asset = calculate_cross_asset_impact(symbol, iv_data.get("btcIV"), iv_data.get("ethIV"))
|
| 496 |
|
| 497 |
# Timeframe agreement
|
|
@@ -507,7 +497,7 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 507 |
(primary_trend == "bear" and normalized_slope < -0.0001):
|
| 508 |
tf_agree = min(1.0, tf_agree + 0.1)
|
| 509 |
|
| 510 |
-
# ββ LAYER 1: Build evidence
|
| 511 |
cmf_val = indicators.get("chaikinMoneyFlow", 0)
|
| 512 |
cmf_signal = clamp(0.5 + cmf_val * 0.5)
|
| 513 |
|
|
@@ -516,7 +506,6 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 516 |
kc_position = (last_close - kc_lower) / (kc_upper - kc_lower) if (kc_upper and kc_lower and kc_upper != kc_lower) else 0.5
|
| 517 |
kc_signal = clamp(kc_position)
|
| 518 |
|
| 519 |
-
# CVD signal (0-1 scale)
|
| 520 |
if cvd_bullish:
|
| 521 |
cvd_signal = 0.7 + delta_strength * 0.3
|
| 522 |
elif cvd_bearish:
|
|
@@ -525,7 +514,6 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 525 |
cvd_signal = 0.5 + (cumulative_delta / max(abs(cumulative_delta), 1)) * 0.1 if cumulative_delta != 0 else 0.5
|
| 526 |
cvd_signal = clamp(cvd_signal)
|
| 527 |
|
| 528 |
-
# Delta trend signal
|
| 529 |
if delta_trend == "accelerating_buy":
|
| 530 |
delta_trend_signal = 0.75
|
| 531 |
elif delta_trend == "accumulation":
|
|
@@ -537,15 +525,12 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 537 |
else:
|
| 538 |
delta_trend_signal = 0.5
|
| 539 |
|
| 540 |
-
# Whale activity signal
|
| 541 |
whale_signal = 0.6 if whale_activity and cvd_bullish else (0.4 if whale_activity and cvd_bearish else 0.5)
|
| 542 |
whale_signal = clamp(whale_signal)
|
| 543 |
|
| 544 |
-
# Enhanced orderbook signal (using 20-level imbalance)
|
| 545 |
ob_signal = clamp(0.5 + ob_imbalance_20 * 0.8)
|
| 546 |
|
| 547 |
signals = [
|
| 548 |
-
# Original signals
|
| 549 |
{"score": clamp(max(0, 1 - garch_vol * 100 / 4)), "weight": 0.10},
|
| 550 |
{"score": clamp(max(0, 1 - mc_spread / 0.15)), "weight": 0.08},
|
| 551 |
{"score": clamp(1 - abs(rsi_val - 50) / 50), "weight": 0.07},
|
|
@@ -559,8 +544,6 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 559 |
{"score": clamp(sentiment.get("sentimentScore", 50)/100), "weight": 0.06},
|
| 560 |
{"score": clamp(sentiment.get("takerBuyRatio", 0.5)), "weight": 0.04},
|
| 561 |
{"score": ob_signal, "weight": 0.04},
|
| 562 |
-
|
| 563 |
-
# NEW Order Flow signals
|
| 564 |
{"score": cvd_signal, "weight": 0.08},
|
| 565 |
{"score": delta_trend_signal, "weight": 0.06},
|
| 566 |
{"score": whale_signal, "weight": 0.04},
|
|
@@ -568,7 +551,7 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 568 |
|
| 569 |
divergence_index = signal_divergence_index(signals, tf_agree)
|
| 570 |
|
| 571 |
-
# ββ LAYER 2: Inference
|
| 572 |
raw_conf, directional_raw = aggregate_log_odds(signals, regime)
|
| 573 |
raw_conf = raw_conf / 100
|
| 574 |
|
|
@@ -581,7 +564,7 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 581 |
|
| 582 |
calibrated = cornish_fisher_calibrate(raw_conf, skew, kurt)
|
| 583 |
|
| 584 |
-
# Build penalty list
|
| 585 |
contra_checks = [
|
| 586 |
medium_trend == primary_trend,
|
| 587 |
macro_trend == primary_trend,
|
|
@@ -680,7 +663,6 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 680 |
if streak_obj.get("strongStreak"):
|
| 681 |
mean_reversion_likelihood = min(0.85, mean_reversion_likelihood + 0.15)
|
| 682 |
|
| 683 |
-
# Get dynamic weight info for debugging
|
| 684 |
dynamic_weights = {family: round(get_dynamic_weight(1.0, family), 2) for family in
|
| 685 |
["trend", "momentum", "volatility", "sentiment", "volume_flow", "order_flow"]}
|
| 686 |
|
|
@@ -699,30 +681,24 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 699 |
"signalDivergence": divergence_index,
|
| 700 |
"regimeInstability": divergence_index > 0.35,
|
| 701 |
|
| 702 |
-
# Confidence intervals
|
| 703 |
"confidenceInterval80": [round(confidence_interval_80[0], 2), round(confidence_interval_80[1], 2)],
|
| 704 |
"confidenceInterval90": [round(confidence_interval_90[0], 2), round(confidence_interval_90[1], 2)],
|
| 705 |
|
| 706 |
-
# Target probabilities
|
| 707 |
"probUp2pct": prob_up_2pct,
|
| 708 |
"probDown2pct": prob_down_2pct,
|
| 709 |
"probUp5pct": mc.get("prob_up_5pct", 0.25),
|
| 710 |
"probDown5pct": mc.get("prob_down_5pct", 0.25),
|
| 711 |
|
| 712 |
-
# Distribution characteristics
|
| 713 |
"quantile95": round(quantile_95, 2),
|
| 714 |
"quantile05": round(quantile_05, 2),
|
| 715 |
"skewness": skewness,
|
| 716 |
"upsidePotentialRatio": mc.get("upside_potential_ratio", 1.0),
|
| 717 |
|
| 718 |
-
# Trend & mean reversion
|
| 719 |
"trendContinuationProbability": round(trend_continuation_prob, 3),
|
| 720 |
"meanReversionLikelihood": round(mean_reversion_likelihood, 3),
|
| 721 |
|
| 722 |
-
# Position sizing
|
| 723 |
"positionSizing": position_sizing,
|
| 724 |
|
| 725 |
-
# Order Flow metrics (NEW from S3)
|
| 726 |
"cumulativeDelta": cumulative_delta,
|
| 727 |
"deltaTrend": delta_trend,
|
| 728 |
"deltaStrength": delta_strength,
|
|
@@ -734,13 +710,10 @@ async def compute_confidence(payload: Dict[str, Any]):
|
|
| 734 |
"bidWall": bid_wall,
|
| 735 |
"askWall": ask_wall,
|
| 736 |
|
| 737 |
-
# Cross-asset correlation
|
| 738 |
"crossAssetImpact": cross_asset,
|
| 739 |
-
|
| 740 |
-
# Dynamic weights (for debugging/transparency)
|
| 741 |
"dynamicWeights": dynamic_weights,
|
| 742 |
|
| 743 |
-
#
|
| 744 |
"garchVolatility": round(garch_vol * 100, 2),
|
| 745 |
"egarchVolatility": round(egarch_vol * 100, 2),
|
| 746 |
"yangZhangVol": round(yz_vol * 100, 2),
|
|
@@ -846,14 +819,12 @@ async def health():
|
|
| 846 |
|
| 847 |
@app.post("/record_outcome")
|
| 848 |
async def record_outcome(symbol: str, predicted_direction: str, confidence: float, actual_price_change: float):
|
| 849 |
-
"""Endpoint to record prediction outcomes for dynamic weight adjustment"""
|
| 850 |
record_prediction_outcome(symbol, predicted_direction, confidence, actual_price_change)
|
| 851 |
return {"status": "recorded"}
|
| 852 |
|
| 853 |
|
| 854 |
@app.get("/weight_status")
|
| 855 |
async def get_weight_status():
|
| 856 |
-
"""Get current dynamic weight multipliers for debugging"""
|
| 857 |
weights = {}
|
| 858 |
for family, perf in _signal_performance.items():
|
| 859 |
accuracy = perf["correct"] / max(perf["total"], 1)
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 54 |
+
# LAYER 1 β SIGNAL DIVERGENCE INDEX (MISSING FUNCTION - ADDED)
|
| 55 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
|
| 57 |
+
def signal_divergence_index(signals: List[Dict], tf_agree: float) -> float:
|
| 58 |
+
"""
|
| 59 |
+
Measures disagreement across signal families.
|
| 60 |
+
"""
|
| 61 |
+
families = {}
|
| 62 |
+
for i, sig in enumerate(signals):
|
| 63 |
+
for fam in indicator_families(i):
|
| 64 |
+
if fam not in families:
|
| 65 |
+
families[fam] = []
|
| 66 |
+
families[fam].append(sig["score"])
|
| 67 |
+
|
| 68 |
+
if len(families) < 2:
|
| 69 |
+
return 0.0
|
| 70 |
+
|
| 71 |
+
family_means = {}
|
| 72 |
+
for fam, scores in families.items():
|
| 73 |
+
family_means[fam] = sum(scores) / len(scores)
|
| 74 |
+
|
| 75 |
+
means = list(family_means.values())
|
| 76 |
+
mean_of_means = sum(means) / len(means)
|
| 77 |
+
variance = sum((m - mean_of_means) ** 2 for m in means) / len(means)
|
| 78 |
+
|
| 79 |
+
range_means = max(means) - min(means) if len(means) > 1 else 0.25
|
| 80 |
+
max_variance = (range_means ** 2) * 0.5
|
| 81 |
+
if max_variance < 1e-8:
|
| 82 |
+
max_variance = 0.25
|
| 83 |
|
| 84 |
+
normalized_variance = min(1.0, variance / max_variance)
|
| 85 |
+
tf_disagreement = 1.0 - tf_agree
|
| 86 |
+
divergence = (normalized_variance * 0.6) + (tf_disagreement * 0.4)
|
| 87 |
+
|
| 88 |
+
return round(divergence, 3)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 92 |
+
# LAYER 1B β DYNAMIC INDICATOR WEIGHTS
|
| 93 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 94 |
+
|
| 95 |
+
_signal_performance = defaultdict(lambda: {"correct": 0, "total": 0, "weight_multiplier": 1.0})
|
| 96 |
+
_recent_predictions = []
|
| 97 |
|
| 98 |
def update_indicator_performance(family: str, was_correct: bool):
|
|
|
|
| 99 |
perf = _signal_performance[family]
|
| 100 |
perf["total"] += 1
|
| 101 |
if was_correct:
|
| 102 |
perf["correct"] += 1
|
| 103 |
|
|
|
|
| 104 |
if perf["total"] > 100:
|
| 105 |
perf["correct"] = perf["correct"] * 0.9
|
| 106 |
perf["total"] = int(perf["total"] * 0.9)
|
| 107 |
|
|
|
|
| 108 |
accuracy = perf["correct"] / max(perf["total"], 1)
|
|
|
|
| 109 |
perf["weight_multiplier"] = 0.5 + accuracy
|
| 110 |
|
| 111 |
|
| 112 |
def get_dynamic_weight(base_weight: float, family: str) -> float:
|
|
|
|
| 113 |
perf = _signal_performance[family]
|
| 114 |
adjusted = base_weight * perf["weight_multiplier"]
|
|
|
|
| 115 |
return max(base_weight * 0.5, min(base_weight * 1.5, adjusted))
|
| 116 |
|
| 117 |
|
| 118 |
def record_prediction_outcome(symbol: str, predicted_direction: str, confidence: float, actual_price_change: float):
|
|
|
|
| 119 |
was_correct = (predicted_direction == "bullish" and actual_price_change > 0) or \
|
| 120 |
(predicted_direction == "bearish" and actual_price_change < 0) or \
|
| 121 |
(predicted_direction == "neutral" and abs(actual_price_change) < 0.005)
|
| 122 |
|
|
|
|
|
|
|
| 123 |
families = ["trend", "momentum", "volatility", "sentiment", "volume_flow", "order_flow"]
|
| 124 |
for family in families:
|
| 125 |
update_indicator_performance(family, was_correct)
|
| 126 |
|
|
|
|
| 127 |
_recent_predictions.append({
|
| 128 |
"timestamp": datetime.now().isoformat(),
|
| 129 |
"confidence": confidence,
|
|
|
|
| 131 |
"symbol": symbol
|
| 132 |
})
|
| 133 |
|
|
|
|
| 134 |
while len(_recent_predictions) > 100:
|
| 135 |
_recent_predictions.pop(0)
|
| 136 |
|
| 137 |
|
| 138 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 139 |
+
# LAYER 1C β SIGNAL CLASSIFICATION
|
| 140 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 141 |
|
| 142 |
def indicator_families(idx: int) -> Set[str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
mapping = {
|
| 144 |
+
0: {"volatility"},
|
| 145 |
+
1: {"volatility"},
|
| 146 |
+
2: {"momentum"},
|
| 147 |
+
3: {"volatility"},
|
| 148 |
+
4: {"trend"},
|
| 149 |
+
5: {"trend"},
|
| 150 |
+
6: {"trend"},
|
| 151 |
+
7: {"momentum"},
|
| 152 |
+
8: {"momentum", "volume_flow"},
|
| 153 |
+
9: {"momentum"},
|
| 154 |
+
10: {"sentiment"},
|
| 155 |
+
11: {"sentiment"},
|
| 156 |
+
12: {"sentiment"},
|
| 157 |
+
13: {"order_flow", "sentiment"},
|
| 158 |
+
14: {"order_flow"},
|
| 159 |
+
15: {"order_flow"},
|
| 160 |
}
|
| 161 |
return mapping.get(idx, {"other"})
|
| 162 |
|
| 163 |
|
| 164 |
def signal_strength(score: float) -> float:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
e = entropy(score)
|
| 166 |
max_e = entropy(0.5)
|
| 167 |
raw = 1.0 - (e / max_e)
|
|
|
|
| 169 |
|
| 170 |
|
| 171 |
def regime_gate(regime: str, families: Set[str]) -> float:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
gate = 1.0
|
| 173 |
|
| 174 |
if regime in ("trend", "strong_trend"):
|
|
|
|
| 177 |
if "momentum" in families:
|
| 178 |
gate = max(gate, 1.2)
|
| 179 |
if "order_flow" in families:
|
| 180 |
+
gate = max(gate, 1.15)
|
| 181 |
if "volatility" in families and "trend" not in families:
|
| 182 |
gate = min(gate, 0.9)
|
| 183 |
|
|
|
|
| 185 |
if "momentum" in families or "volatility" in families:
|
| 186 |
gate = max(gate, 1.2)
|
| 187 |
if "order_flow" in families:
|
| 188 |
+
gate = min(gate, 0.7)
|
| 189 |
if "trend" in families:
|
| 190 |
gate = min(gate, 0.5)
|
| 191 |
|
|
|
|
| 197 |
elif "volatility" in families:
|
| 198 |
gate = min(gate, 0.6)
|
| 199 |
|
|
|
|
| 200 |
if families.issubset({"volume_flow", "sentiment"}):
|
| 201 |
return 1.0
|
| 202 |
|
|
|
|
| 204 |
|
| 205 |
|
| 206 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 207 |
+
# LAYER 1D β CROSS-ASSET CORRELATIONS
|
| 208 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 209 |
|
|
|
|
|
|
|
|
|
|
| 210 |
def calculate_cross_asset_impact(symbol: str, btc_iv: float, eth_iv: float) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
is_btc = "BTC" in symbol.upper()
|
| 212 |
is_eth = "ETH" in symbol.upper()
|
| 213 |
|
|
|
|
| 219 |
}
|
| 220 |
|
| 221 |
if is_btc:
|
|
|
|
| 222 |
return result
|
| 223 |
|
|
|
|
| 224 |
if btc_iv:
|
|
|
|
| 225 |
if btc_iv > 70:
|
| 226 |
+
result["volatility_spillover"] = 1.15
|
| 227 |
result["btc_dominance_signal"] = "btc_volatile"
|
| 228 |
elif btc_iv > 50:
|
| 229 |
result["volatility_spillover"] = 1.05
|
| 230 |
|
| 231 |
if is_eth:
|
|
|
|
| 232 |
if eth_iv and eth_iv > 80:
|
| 233 |
result["volatility_spillover"] = max(result["volatility_spillover"], 1.1)
|
| 234 |
|
|
|
|
| 236 |
|
| 237 |
|
| 238 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 239 |
+
# LAYER 2 β INFERENCE
|
| 240 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 241 |
|
| 242 |
TEMPERATURE = 1.5
|
| 243 |
|
| 244 |
|
| 245 |
def aggregate_log_odds(signals: List[Dict], regime: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
s_lo, w_total = 0.0, 0.0
|
| 247 |
|
| 248 |
for i, sig in enumerate(signals):
|
|
|
|
| 250 |
base_weight = sig["weight"]
|
| 251 |
families = indicator_families(i)
|
| 252 |
|
|
|
|
| 253 |
primary_family = next(iter(families)) if families else "other"
|
|
|
|
|
|
|
| 254 |
dynamic_weight = get_dynamic_weight(base_weight, primary_family)
|
| 255 |
|
| 256 |
strength = signal_strength(score)
|
| 257 |
gate = regime_gate(regime, families)
|
| 258 |
final_weight = dynamic_weight * strength * gate
|
| 259 |
|
|
|
|
| 260 |
s_lo += (logit(score) / TEMPERATURE) * final_weight
|
| 261 |
w_total += final_weight
|
| 262 |
|
|
|
|
| 269 |
|
| 270 |
|
| 271 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 272 |
+
# LAYER 3 β CALIBRATION
|
| 273 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 274 |
|
| 275 |
def cornish_fisher_calibrate(prob, skew, kurt):
|
|
|
|
| 303 |
|
| 304 |
|
| 305 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 306 |
+
# LAYER 4 β INTERPRETATION
|
| 307 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 308 |
|
| 309 |
def fear_index(garch_vol, adx_val, streak_obj, dd_obj, vol_spike, r_vol3, a_vol20, c3, c4):
|
|
|
|
| 466 |
confidence_interval_80 = mc.get("confidence_interval_80", [last_close * 0.95, last_close * 1.05])
|
| 467 |
confidence_interval_90 = mc.get("confidence_interval_90", [last_close * 0.92, last_close * 1.08])
|
| 468 |
|
| 469 |
+
# ββ Extract order flow fields from S3 ββ
|
| 470 |
cumulative_delta = sentiment.get("cumulativeDelta", 0)
|
| 471 |
delta_trend = sentiment.get("deltaTrend", "neutral")
|
| 472 |
delta_strength = sentiment.get("deltaStrength", 0)
|
|
|
|
| 482 |
normalized_slope = linear_regression_slope(closes, 200)
|
| 483 |
primary_is_bull = primary_trend == "bull"
|
| 484 |
|
|
|
|
| 485 |
cross_asset = calculate_cross_asset_impact(symbol, iv_data.get("btcIV"), iv_data.get("ethIV"))
|
| 486 |
|
| 487 |
# Timeframe agreement
|
|
|
|
| 497 |
(primary_trend == "bear" and normalized_slope < -0.0001):
|
| 498 |
tf_agree = min(1.0, tf_agree + 0.1)
|
| 499 |
|
| 500 |
+
# ββ LAYER 1: Build evidence ββ
|
| 501 |
cmf_val = indicators.get("chaikinMoneyFlow", 0)
|
| 502 |
cmf_signal = clamp(0.5 + cmf_val * 0.5)
|
| 503 |
|
|
|
|
| 506 |
kc_position = (last_close - kc_lower) / (kc_upper - kc_lower) if (kc_upper and kc_lower and kc_upper != kc_lower) else 0.5
|
| 507 |
kc_signal = clamp(kc_position)
|
| 508 |
|
|
|
|
| 509 |
if cvd_bullish:
|
| 510 |
cvd_signal = 0.7 + delta_strength * 0.3
|
| 511 |
elif cvd_bearish:
|
|
|
|
| 514 |
cvd_signal = 0.5 + (cumulative_delta / max(abs(cumulative_delta), 1)) * 0.1 if cumulative_delta != 0 else 0.5
|
| 515 |
cvd_signal = clamp(cvd_signal)
|
| 516 |
|
|
|
|
| 517 |
if delta_trend == "accelerating_buy":
|
| 518 |
delta_trend_signal = 0.75
|
| 519 |
elif delta_trend == "accumulation":
|
|
|
|
| 525 |
else:
|
| 526 |
delta_trend_signal = 0.5
|
| 527 |
|
|
|
|
| 528 |
whale_signal = 0.6 if whale_activity and cvd_bullish else (0.4 if whale_activity and cvd_bearish else 0.5)
|
| 529 |
whale_signal = clamp(whale_signal)
|
| 530 |
|
|
|
|
| 531 |
ob_signal = clamp(0.5 + ob_imbalance_20 * 0.8)
|
| 532 |
|
| 533 |
signals = [
|
|
|
|
| 534 |
{"score": clamp(max(0, 1 - garch_vol * 100 / 4)), "weight": 0.10},
|
| 535 |
{"score": clamp(max(0, 1 - mc_spread / 0.15)), "weight": 0.08},
|
| 536 |
{"score": clamp(1 - abs(rsi_val - 50) / 50), "weight": 0.07},
|
|
|
|
| 544 |
{"score": clamp(sentiment.get("sentimentScore", 50)/100), "weight": 0.06},
|
| 545 |
{"score": clamp(sentiment.get("takerBuyRatio", 0.5)), "weight": 0.04},
|
| 546 |
{"score": ob_signal, "weight": 0.04},
|
|
|
|
|
|
|
| 547 |
{"score": cvd_signal, "weight": 0.08},
|
| 548 |
{"score": delta_trend_signal, "weight": 0.06},
|
| 549 |
{"score": whale_signal, "weight": 0.04},
|
|
|
|
| 551 |
|
| 552 |
divergence_index = signal_divergence_index(signals, tf_agree)
|
| 553 |
|
| 554 |
+
# ββ LAYER 2: Inference ββ
|
| 555 |
raw_conf, directional_raw = aggregate_log_odds(signals, regime)
|
| 556 |
raw_conf = raw_conf / 100
|
| 557 |
|
|
|
|
| 564 |
|
| 565 |
calibrated = cornish_fisher_calibrate(raw_conf, skew, kurt)
|
| 566 |
|
| 567 |
+
# Build penalty list
|
| 568 |
contra_checks = [
|
| 569 |
medium_trend == primary_trend,
|
| 570 |
macro_trend == primary_trend,
|
|
|
|
| 663 |
if streak_obj.get("strongStreak"):
|
| 664 |
mean_reversion_likelihood = min(0.85, mean_reversion_likelihood + 0.15)
|
| 665 |
|
|
|
|
| 666 |
dynamic_weights = {family: round(get_dynamic_weight(1.0, family), 2) for family in
|
| 667 |
["trend", "momentum", "volatility", "sentiment", "volume_flow", "order_flow"]}
|
| 668 |
|
|
|
|
| 681 |
"signalDivergence": divergence_index,
|
| 682 |
"regimeInstability": divergence_index > 0.35,
|
| 683 |
|
|
|
|
| 684 |
"confidenceInterval80": [round(confidence_interval_80[0], 2), round(confidence_interval_80[1], 2)],
|
| 685 |
"confidenceInterval90": [round(confidence_interval_90[0], 2), round(confidence_interval_90[1], 2)],
|
| 686 |
|
|
|
|
| 687 |
"probUp2pct": prob_up_2pct,
|
| 688 |
"probDown2pct": prob_down_2pct,
|
| 689 |
"probUp5pct": mc.get("prob_up_5pct", 0.25),
|
| 690 |
"probDown5pct": mc.get("prob_down_5pct", 0.25),
|
| 691 |
|
|
|
|
| 692 |
"quantile95": round(quantile_95, 2),
|
| 693 |
"quantile05": round(quantile_05, 2),
|
| 694 |
"skewness": skewness,
|
| 695 |
"upsidePotentialRatio": mc.get("upside_potential_ratio", 1.0),
|
| 696 |
|
|
|
|
| 697 |
"trendContinuationProbability": round(trend_continuation_prob, 3),
|
| 698 |
"meanReversionLikelihood": round(mean_reversion_likelihood, 3),
|
| 699 |
|
|
|
|
| 700 |
"positionSizing": position_sizing,
|
| 701 |
|
|
|
|
| 702 |
"cumulativeDelta": cumulative_delta,
|
| 703 |
"deltaTrend": delta_trend,
|
| 704 |
"deltaStrength": delta_strength,
|
|
|
|
| 710 |
"bidWall": bid_wall,
|
| 711 |
"askWall": ask_wall,
|
| 712 |
|
|
|
|
| 713 |
"crossAssetImpact": cross_asset,
|
|
|
|
|
|
|
| 714 |
"dynamicWeights": dynamic_weights,
|
| 715 |
|
| 716 |
+
# All original fields (keeping for backward compatibility)
|
| 717 |
"garchVolatility": round(garch_vol * 100, 2),
|
| 718 |
"egarchVolatility": round(egarch_vol * 100, 2),
|
| 719 |
"yangZhangVol": round(yz_vol * 100, 2),
|
|
|
|
| 819 |
|
| 820 |
@app.post("/record_outcome")
|
| 821 |
async def record_outcome(symbol: str, predicted_direction: str, confidence: float, actual_price_change: float):
|
|
|
|
| 822 |
record_prediction_outcome(symbol, predicted_direction, confidence, actual_price_change)
|
| 823 |
return {"status": "recorded"}
|
| 824 |
|
| 825 |
|
| 826 |
@app.get("/weight_status")
|
| 827 |
async def get_weight_status():
|
|
|
|
| 828 |
weights = {}
|
| 829 |
for family, perf in _signal_performance.items():
|
| 830 |
accuracy = perf["correct"] / max(perf["total"], 1)
|