asdzxcvzxcvx commited on
Commit
b0cd8be
·
verified ·
1 Parent(s): 67f0f71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -11
app.py CHANGED
@@ -40,6 +40,31 @@ def sigmoid(x):
40
  return 1 / (1 + math.exp(-x))
41
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  def cornish_fisher_calibrate(prob, skew, kurt):
44
  """Adjust a probability using Cornish‑Fisher expansion for skew/kurtosis."""
45
  if abs(skew) < 1e-4 and abs(kurt - 3) < 1e-2:
@@ -59,17 +84,31 @@ def cornish_fisher_calibrate(prob, skew, kurt):
59
  return max(0.0, min(1.0, 0.5 * (1 + math.erf(cf / math.sqrt(2)))))
60
 
61
 
62
- def aggregate_log_odds(signals):
63
- """Weighted log‑odds aggregation → returns 0–100 score."""
 
 
 
 
 
64
  s_lo, w_total = 0.0, 0.0
 
65
  for sig in signals:
66
  score = clamp(sig["score"])
67
- w = sig["weight"]
68
- s_lo += logit(score) * w
69
- w_total += w
 
 
 
 
70
  if w_total == 0:
71
- return 50
72
- return round(sigmoid(s_lo / w_total) * 100)
 
 
 
 
73
 
74
 
75
  def fear_index(garch_vol, adx_val, streak_obj, dd_obj, vol_spike, r_vol3, a_vol20, c3, c4):
@@ -212,11 +251,9 @@ async def compute_confidence(payload: Dict[str, Any]):
212
  # ── Build signals for log‑odds aggregation ──
213
  primary_is_bull = primary_trend == "bull"
214
 
215
- # CMF signal (new)
216
  cmf_val = indicators.get("chaikinMoneyFlow", 0)
217
  cmf_signal = clamp(0.5 + cmf_val * 0.5)
218
 
219
- # Keltner signal (new)
220
  kc_upper = indicators.get("keltnerUpper", last_close)
221
  kc_lower = indicators.get("keltnerLower", last_close)
222
  if kc_upper and kc_lower and kc_upper != kc_lower:
@@ -285,8 +322,9 @@ async def compute_confidence(payload: Dict[str, Any]):
285
  (sentiment.get("oiTrend") == "rising" and not primary_is_bull) else 1.0
286
  iv_p = 0.88 if iv_data.get("ivElevated", False) else 1.0
287
 
288
- # ── Confidence score ──
289
- raw_conf = aggregate_log_odds(signals) / 100
 
290
 
291
  log_ret = [math.log(closes[i]/closes[i-1]) for i in range(1, len(closes))]
292
  if len(log_ret) > 10:
@@ -299,6 +337,16 @@ async def compute_confidence(payload: Dict[str, Any]):
299
  all_penalties = contra_p * vol_p * macro_p * adx_p * streak_p * atr_p * dd_p * fear_damp * vol_spike_p * oi_p * iv_p
300
  confidence_score = round(max(0, min(100, calibrated * 100 * all_penalties)))
301
 
 
 
 
 
 
 
 
 
 
 
302
  # ── Fear‑adjusted cases ──
303
  bear_mult = 1.25
304
  bull_mult = 0.80
@@ -335,6 +383,10 @@ async def compute_confidence(payload: Dict[str, Any]):
335
  "bearCase": round(adj_bear, 2),
336
  "confidenceScore": confidence_score,
337
 
 
 
 
 
338
  "garchVolatility": round(garch_vol * 100, 2),
339
  "egarchVolatility": round(egarch_vol * 100, 2),
340
  "yangZhangVol": round(yz_vol * 100, 2),
 
40
  return 1 / (1 + math.exp(-x))
41
 
42
 
43
+ def signal_strength(score):
44
+ """
45
+ How strong is this signal?
46
+ Returns 0.3–1.5 multiplier.
47
+ Score near 0.5 = weak (0.3× weight).
48
+ Score near 0.05 or 0.95 = strong (1.5× weight).
49
+ """
50
+ distance = abs(score - 0.5) * 2 # 0 = neutral, 1 = extreme
51
+ return 0.3 + distance * 1.2 # range: 0.3 to 1.5
52
+
53
+
54
+ def regime_weight_multiplier(regime):
55
+ """
56
+ In random walk, ALL signal weights are reduced by 40%.
57
+ In trending, trend signals get boosted.
58
+ In mean_revert, mean-reversion signals get boosted.
59
+ """
60
+ return {
61
+ "random_walk": 0.60,
62
+ "trend": 1.0,
63
+ "strong_trend": 1.2,
64
+ "mean_revert": 0.85,
65
+ }.get(regime, 1.0)
66
+
67
+
68
  def cornish_fisher_calibrate(prob, skew, kurt):
69
  """Adjust a probability using Cornish‑Fisher expansion for skew/kurtosis."""
70
  if abs(skew) < 1e-4 and abs(kurt - 3) < 1e-2:
 
84
  return max(0.0, min(1.0, 0.5 * (1 + math.erf(cf / math.sqrt(2)))))
85
 
86
 
87
+ def aggregate_log_odds(signals, regime):
88
+ """
89
+ Weighted log‑odds aggregation with dynamic weights.
90
+ Strong signals get amplified. Weak signals get dampened.
91
+ Regime affects all weights.
92
+ """
93
+ regime_mult = regime_weight_multiplier(regime)
94
  s_lo, w_total = 0.0, 0.0
95
+
96
  for sig in signals:
97
  score = clamp(sig["score"])
98
+ base_weight = sig["weight"]
99
+ strength = signal_strength(score)
100
+ final_weight = base_weight * strength * regime_mult
101
+
102
+ s_lo += logit(score) * final_weight
103
+ w_total += final_weight
104
+
105
  if w_total == 0:
106
+ return 50, 0.0
107
+
108
+ # Directional bias: positive = bullish, negative = bearish
109
+ directional_raw = s_lo / w_total # log-odds
110
+
111
+ return round(sigmoid(s_lo / w_total) * 100), directional_raw
112
 
113
 
114
  def fear_index(garch_vol, adx_val, streak_obj, dd_obj, vol_spike, r_vol3, a_vol20, c3, c4):
 
251
  # ── Build signals for log‑odds aggregation ──
252
  primary_is_bull = primary_trend == "bull"
253
 
 
254
  cmf_val = indicators.get("chaikinMoneyFlow", 0)
255
  cmf_signal = clamp(0.5 + cmf_val * 0.5)
256
 
 
257
  kc_upper = indicators.get("keltnerUpper", last_close)
258
  kc_lower = indicators.get("keltnerLower", last_close)
259
  if kc_upper and kc_lower and kc_upper != kc_lower:
 
322
  (sentiment.get("oiTrend") == "rising" and not primary_is_bull) else 1.0
323
  iv_p = 0.88 if iv_data.get("ivElevated", False) else 1.0
324
 
325
+ # ── Confidence score with dynamic weights ──
326
+ raw_conf, directional_raw = aggregate_log_odds(signals, regime)
327
+ raw_conf = raw_conf / 100
328
 
329
  log_ret = [math.log(closes[i]/closes[i-1]) for i in range(1, len(closes))]
330
  if len(log_ret) > 10:
 
337
  all_penalties = contra_p * vol_p * macro_p * adx_p * streak_p * atr_p * dd_p * fear_damp * vol_spike_p * oi_p * iv_p
338
  confidence_score = round(max(0, min(100, calibrated * 100 * all_penalties)))
339
 
340
+ # ── Directional bias ──
341
+ # Convert log-odds to a -1 to +1 scale
342
+ directional_bias = round(max(-1.0, min(1.0, sigmoid(directional_raw) * 2 - 1)), 3)
343
+ if directional_bias > 0.15:
344
+ directional_signal = "bullish"
345
+ elif directional_bias < -0.15:
346
+ directional_signal = "bearish"
347
+ else:
348
+ directional_signal = "neutral"
349
+
350
  # ── Fear‑adjusted cases ──
351
  bear_mult = 1.25
352
  bull_mult = 0.80
 
383
  "bearCase": round(adj_bear, 2),
384
  "confidenceScore": confidence_score,
385
 
386
+ # ── NEW: Directional bias ──
387
+ "directionalBias": directional_bias,
388
+ "directionalSignal": directional_signal,
389
+
390
  "garchVolatility": round(garch_vol * 100, 2),
391
  "egarchVolatility": round(egarch_vol * 100, 2),
392
  "yangZhangVol": round(yz_vol * 100, 2),