suppa09 commited on
Commit
f17713f
·
verified ·
1 Parent(s): 7bc39f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -36
app.py CHANGED
@@ -1,5 +1,6 @@
 
1
  """
2
- PolyBloom ML Ensemble Service v14.3 — OMEGA COUNCIL (8 Models)
3
 
4
  FIXES in v14.2 (reviewer-corrected from v14.1):
5
  1. slope_to_direction: per-TF thresholds (5M=0.003, 15M=0.005, 1D=0.018)
@@ -9,12 +10,12 @@ FIXES in v14.2 (reviewer-corrected from v14.1):
9
 
10
  3. Reviewer fix #4: Instead of patching each fallback individually, the
11
  funding/RSI nudge is applied as a final context_nudge() pass inside
12
- omega_forecast() AFTER all models have run. This means every model —
13
- primary AND fallback — benefits uniformly. Cleaner than threading req
14
  into each individual fallback.
15
 
16
  4. run_tabpfn / run_patchtst / run_chronos_fallback: keep price-only logic
17
- (no RSI/funding injected into model internals — preserves independence).
18
  Context correction happens at the endpoint level via context_nudge().
19
 
20
  5. Composite NEUTRAL threshold tightened per-TF.
@@ -23,11 +24,24 @@ FIX in v14.3:
23
  6. N-BEATS structural UP bias removed.
24
  Root cause: seasonal_signal = math.sin(phase + math.pi/2).
25
  When n % period ≈ 0 (common at session open), phase ≈ 0 and
26
- sin(0 + π/2) = 1.0 — a permanent +1 UP bias injected into every
27
  forecast regardless of actual price structure.
28
- Fix: use math.sin(phase) — unbiased; averages to 0 over a full cycle.
29
  The ctx_nudge (max ±0.006%) was far too small to counteract the
30
  seasonal term's ±3% contribution (seasonal_signal * 0.03 * 100).
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  """
32
  import os, time, math
33
  from typing import List, Optional, Tuple
@@ -53,7 +67,7 @@ except Exception:
53
  CHRONOS_MODEL = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-small")
54
  MOIRAI_MODEL = os.environ.get("MOIRAI_MODEL", "Salesforce/moirai-1.1-R-small")
55
 
56
- app = FastAPI(title="PolyBloom ML Ensemble v14.3", version="14.3.0")
57
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
58
 
59
  _chronos = None
@@ -138,13 +152,13 @@ class OmegaResponse(BaseModel):
138
 
139
 
140
  # ── FIX 1: Per-timeframe slope thresholds ─────────────────────────────────────
141
- # Old: hardcoded 0.008% for every TF — caused Chronos NEUTRAL ~65% of runs.
142
- # Chronos T5 median forecast moves ~$3–8 over 2 5M candles = 0.003–0.008% at $100k.
143
  # The hardcoded threshold sat right at the top of Chronos's natural output range.
144
  SLOPE_THRESHOLDS = {
145
- "5M": 0.003, # $3 move at $100k — realistic 2-candle 5M forecast
146
- "15M": 0.005, # $5 move — 15M window is slightly wider
147
- "1D": 0.018, # $18 move — daily forecasts have much more range
148
  }
149
 
150
  def slope_to_direction(slope_pct: float, threshold: float = 0.003) -> Tuple[str, float]:
@@ -256,7 +270,7 @@ def run_chronos(closes, horizon):
256
 
257
 
258
  def run_chronos_fallback(closes, horizon):
259
- """Holt-Winters fallback — price-only, context nudge applied at endpoint level."""
260
  n = len(closes)
261
  if n < 4:
262
  return 0.0, "holt-winters-fallback", "Insufficient data"
@@ -274,7 +288,7 @@ def run_chronos_fallback(closes, horizon):
274
 
275
 
276
  def run_tabpfn(closes, horizon):
277
- """TabPFN numeric — price-only. Context nudge applied at endpoint level."""
278
  n = len(closes)
279
  if n < 8:
280
  return 0.0, "tabpfn", "Insufficient data"
@@ -337,7 +351,7 @@ def run_aropt(closes, horizon):
337
 
338
 
339
  def run_patchtst(closes, horizon):
340
- """PatchTST numeric — price-only. Context nudge applied at endpoint level."""
341
  n = len(closes)
342
  patch_size = 8
343
  n_patches = n // patch_size
@@ -447,17 +461,141 @@ def run_nbeats(closes, horizon):
447
  f"N-BEATS: trend={trend_slope:.4f}%, seasonal(period≈{period:.1f})={seasonal_signal:.3f}, residual={float(residual)*100:.4f}%."
448
 
449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
450
  # ── Static model weights ──────────────────────────────────────────────────────
451
 
452
  STATIC_WEIGHTS = {
453
- "Chronos": 0.18,
454
- "TabPFN-TS": 0.14,
455
- "DAG": 0.16,
456
- "AROpt": 0.12,
457
- "PatchTST": 0.15,
458
- "TiDE": 0.13,
459
- "MOIRAI": 0.07,
460
- "N-BEATS": 0.05,
 
 
 
 
 
 
461
  }
462
 
463
 
@@ -469,7 +607,7 @@ def health():
469
  "ok": True,
470
  "chronos": CHRONOS_AVAILABLE,
471
  "moirai": MOIRAI_AVAILABLE,
472
- "version": "14.3.0",
473
  "models": list(STATIC_WEIGHTS.keys()),
474
  }
475
 
@@ -481,7 +619,7 @@ def omega_forecast(req: OmegaRequest):
481
  horizon = req.horizon
482
  results: List[ModelResult] = []
483
 
484
- # FIX 2: per-TF threshold — was hardcoded 0.008 for all TFs
485
  tf_threshold = SLOPE_THRESHOLDS.get(req.timeframe, 0.003)
486
 
487
  # FIX (reviewer #4): compute context nudge ONCE here, apply to all models
@@ -492,7 +630,7 @@ def omega_forecast(req: OmegaRequest):
492
  def add(name, slope_pct, note, reasoning, is_avail, threshold=None, conf_mult=1.0):
493
  t = threshold if threshold is not None else tf_threshold
494
  # Apply context nudge to slope before direction decision.
495
- # Nudge is small (max ±0.008%) — can tip near-threshold to DOWN/UP
496
  # but cannot reverse a confident model.
497
  nudged_slope = slope_pct + ctx_nudge
498
  direction, conf = slope_to_direction(nudged_slope, t)
@@ -504,15 +642,19 @@ def omega_forecast(req: OmegaRequest):
504
  ))
505
 
506
  runners = [
507
- ("Chronos", lambda: run_chronos(closes, horizon),
508
- lambda: run_chronos_fallback(closes, horizon)),
509
- ("TabPFN-TS", lambda: run_tabpfn(closes, horizon), None),
510
- ("DAG", lambda: run_dag(closes, req), None),
511
- ("AROpt", lambda: run_aropt(closes, horizon), None),
512
- ("PatchTST", lambda: run_patchtst(closes, horizon), None),
513
- ("TiDE", lambda: run_tide(closes, req, horizon), None),
514
- ("MOIRAI", lambda: run_moirai(closes, horizon, req), None),
515
- ("N-BEATS", lambda: run_nbeats(closes, horizon), None),
 
 
 
 
516
  ]
517
 
518
  for name, fn, fb in runners:
@@ -553,7 +695,7 @@ def omega_forecast(req: OmegaRequest):
553
  total_weight += w
554
  comp_score = composite / total_weight if total_weight > 0 else 0.0
555
 
556
- # ── Composite direction — tightened NEUTRAL threshold ────────────────────
557
  # Old: fixed 0.03 for all TFs. New: per-TF, consistent with model thresholds.
558
  COMPOSITE_THRESHOLD = {"5M": 0.018, "15M": 0.015, "1D": 0.012}.get(req.timeframe, 0.018)
559
 
 
1
+ # -*- coding: utf-8 -*-
2
  """
3
+ PolyBloom ML Ensemble Service v14.4 -- OMEGA COUNCIL (11 Models)
4
 
5
  FIXES in v14.2 (reviewer-corrected from v14.1):
6
  1. slope_to_direction: per-TF thresholds (5M=0.003, 15M=0.005, 1D=0.018)
 
10
 
11
  3. Reviewer fix #4: Instead of patching each fallback individually, the
12
  funding/RSI nudge is applied as a final context_nudge() pass inside
13
+ omega_forecast() AFTER all models have run. This means every model --
14
+ primary AND fallback -- benefits uniformly. Cleaner than threading req
15
  into each individual fallback.
16
 
17
  4. run_tabpfn / run_patchtst / run_chronos_fallback: keep price-only logic
18
+ (no RSI/funding injected into model internals -- preserves independence).
19
  Context correction happens at the endpoint level via context_nudge().
20
 
21
  5. Composite NEUTRAL threshold tightened per-TF.
 
24
  6. N-BEATS structural UP bias removed.
25
  Root cause: seasonal_signal = math.sin(phase + math.pi/2).
26
  When n % period ≈ 0 (common at session open), phase ≈ 0 and
27
+ sin(0 + π/2) = 1.0 -- a permanent +1 UP bias injected into every
28
  forecast regardless of actual price structure.
29
+ Fix: use math.sin(phase) -- unbiased; averages to 0 over a full cycle.
30
  The ctx_nudge (max ±0.006%) was far too small to counteract the
31
  seasonal term's ±3% contribution (seasonal_signal * 0.03 * 100).
32
+
33
+ FIX in v14.4:
34
+ 7. Added 3 missing model runners so Python service name-matches the frontend
35
+ localEnsemble exactly (11 models total, all names aligned):
36
+ - run_river() SNARIMAX-style online AR: taker-buy-ratio + funding fade
37
+ + short-lag momentum (sl3). Mirrors sRiver in frontend.
38
+ - run_informer() Fibonacci-decay attention over price history + Polymarket
39
+ yes-prob delta + sentiment polarity. Mirrors sInformer.
40
+ - run_statsforecast() MSTL/ETS-style: trend (sl20) + mean-reversion-to-EMA
41
+ + RSI-weighted vol dampening. Mirrors sStats.
42
+ TabPFN-TS kept as-is (distinct signal; weight reduced to make room).
43
+ STATIC_WEIGHTS renormalized across all 11 models.
44
+
45
  """
46
  import os, time, math
47
  from typing import List, Optional, Tuple
 
67
  CHRONOS_MODEL = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-small")
68
  MOIRAI_MODEL = os.environ.get("MOIRAI_MODEL", "Salesforce/moirai-1.1-R-small")
69
 
70
+ app = FastAPI(title="PolyBloom ML Ensemble v14.4", version="14.4.0")
71
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
72
 
73
  _chronos = None
 
152
 
153
 
154
  # ── FIX 1: Per-timeframe slope thresholds ─────────────────────────────────────
155
+ # Old: hardcoded 0.008% for every TF -- caused Chronos NEUTRAL ~65% of runs.
156
+ # Chronos T5 median forecast moves ~$3--8 over 2 5M candles = 0.003--0.008% at $100k.
157
  # The hardcoded threshold sat right at the top of Chronos's natural output range.
158
  SLOPE_THRESHOLDS = {
159
+ "5M": 0.003, # $3 move at $100k -- realistic 2-candle 5M forecast
160
+ "15M": 0.005, # $5 move -- 15M window is slightly wider
161
+ "1D": 0.018, # $18 move -- daily forecasts have much more range
162
  }
163
 
164
  def slope_to_direction(slope_pct: float, threshold: float = 0.003) -> Tuple[str, float]:
 
270
 
271
 
272
  def run_chronos_fallback(closes, horizon):
273
+ """Holt-Winters fallback -- price-only, context nudge applied at endpoint level."""
274
  n = len(closes)
275
  if n < 4:
276
  return 0.0, "holt-winters-fallback", "Insufficient data"
 
288
 
289
 
290
  def run_tabpfn(closes, horizon):
291
+ """TabPFN numeric -- price-only. Context nudge applied at endpoint level."""
292
  n = len(closes)
293
  if n < 8:
294
  return 0.0, "tabpfn", "Insufficient data"
 
351
 
352
 
353
  def run_patchtst(closes, horizon):
354
+ """PatchTST numeric -- price-only. Context nudge applied at endpoint level."""
355
  n = len(closes)
356
  patch_size = 8
357
  n_patches = n // patch_size
 
461
  f"N-BEATS: trend={trend_slope:.4f}%, seasonal(period≈{period:.1f})={seasonal_signal:.3f}, residual={float(residual)*100:.4f}%."
462
 
463
 
464
+
465
+ def run_river(closes, horizon, req):
466
+ """
467
+ River SNARIMAX-style online AR runner.
468
+ Independent signal: short-lag momentum + taker-buy aggression + funding fade.
469
+ Mirrors the frontend's sRiver formula (GROUP 2: Orderflow).
470
+ Price-only slope -- context nudge applied at endpoint level.
471
+ """
472
+ n = len(closes)
473
+ if n < 4:
474
+ return 0.0, "river-snarimax", "Insufficient data"
475
+
476
+ # sl3: 3-bar momentum (fastest price signal)
477
+ sl3 = (closes[-1] - closes[-4]) / closes[-4] if n >= 4 else 0.0
478
+
479
+ # Taker buy ratio: directional aggression (0.5 = neutral)
480
+ tbr_score = 0.0
481
+ if req.taker_buy_ratio is not None:
482
+ tbr_score = math.tanh((req.taker_buy_ratio - 0.5) * 6)
483
+
484
+ # Funding fade: crowded longs (high +funding) = mean-reversion bearish signal
485
+ fund_score = 0.0
486
+ if req.funding is not None:
487
+ fund_score = -math.copysign(min(1.0, abs(req.funding) * 5000), req.funding)
488
+
489
+ # Weighted combination -- mirrors frontend sRiver weights exactly
490
+ combined = (0.50 * math.copysign(min(1.0, abs(sl3) * 100), sl3)
491
+ + 0.30 * tbr_score
492
+ + 0.20 * fund_score)
493
+ slope_pct = math.tanh(combined) * 0.10 * 100 # scale to ~±0.10% range
494
+
495
+ return slope_pct, "river-snarimax", (
496
+ f"River SNARIMAX: sl3={sl3*100:.4f}%, tbr={req.taker_buy_ratio or 0.5:.3f}, "
497
+ f"fund={req.funding or 0.0:.6f}, combined={combined:.4f}, slope={slope_pct:.4f}%."
498
+ )
499
+
500
+
501
+ def run_informer(closes, horizon, req):
502
+ """
503
+ Informer-style multi-scale attention runner.
504
+ Uses Fibonacci-spaced lag returns (exponential decay attention) over price
505
+ history, weighted with Polymarket yes-prob momentum and sentiment polarity.
506
+ Mirrors the frontend's sInformer formula (GROUP 4: Macro/Cross-asset).
507
+ """
508
+ n = len(closes)
509
+ if n < 14:
510
+ return 0.0, "informer-attn", "Insufficient data"
511
+
512
+ # Fibonacci attention: lags [1,2,3,5,8,13], exponential decay weight
513
+ fib_lags = [1, 2, 3, 5, 8, 13]
514
+ fib_signal = 0.0
515
+ for lag in fib_lags:
516
+ if n > lag:
517
+ ret = (closes[-1] - closes[-(lag + 1)]) / closes[-(lag + 1)]
518
+ fib_signal += ret * math.exp(-lag * 0.05)
519
+
520
+ # Polymarket yes-probability (directional sentiment from prediction market)
521
+ pyes = req.polymarket_yes or 0.5
522
+ pdel = float(getattr(req, "poly_yes_delta_1m", None) or 0.0)
523
+ pyes_score = math.tanh((pyes - 0.5) * 6)
524
+ pdel_score = math.tanh(pdel * 20)
525
+
526
+ # Sentiment polarity
527
+ snt_score = 0.0
528
+ if req.sentiment_polarity is not None:
529
+ snt_score = math.tanh(req.sentiment_polarity * 2)
530
+
531
+ # Weighted combination -- mirrors frontend sInformer weights exactly
532
+ combined = (0.35 * math.tanh(fib_signal * 50)
533
+ + 0.30 * pyes_score
534
+ + 0.20 * pdel_score
535
+ + 0.15 * snt_score)
536
+ slope_pct = math.tanh(combined) * 0.10 * 100
537
+
538
+ return slope_pct, "informer-attn", (
539
+ f"Informer: fib_attn={math.tanh(fib_signal*50):.4f}, pyes={pyes:.3f}, "
540
+ f"pdel={pdel:.4f}, snt={req.sentiment_polarity or 0.0:.3f}, slope={slope_pct:.4f}%."
541
+ )
542
+
543
+
544
+ def run_statsforecast(closes, horizon, req):
545
+ """
546
+ StatsForecast MSTL/ETS-style decomposition runner.
547
+ Trend component (sl20) + mean-reversion-to-EMA + RSI-weighted vol dampening.
548
+ Mirrors the frontend's sStats formula (GROUP 5: Probabilistic).
549
+ Price-only slope -- context nudge applied at endpoint level.
550
+ """
551
+ n = len(closes)
552
+ if n < 21:
553
+ return 0.0, "statsforecast-mstl", "Insufficient data"
554
+
555
+ last = float(closes[-1])
556
+
557
+ # sl20: 20-bar trend slope
558
+ sl20 = (closes[-1] - closes[-21]) / closes[-21] if n >= 21 else 0.0
559
+
560
+ # Mean reversion: deviation of price from EMA-20
561
+ e20 = ema(closes[-40:], 20) if n >= 20 else last
562
+ dev = (last - e20) / e20 if e20 != 0 else 0.0
563
+ mean_rev = -math.tanh(dev * 30) * 0.04
564
+
565
+ # Vol: std/mean of last 30 bars (dampens RSI signal under high vol)
566
+ vol = float(np.std(closes[-30:])) / float(np.mean(closes[-30:])) if n >= 30 else 0.01
567
+ rsi = req.rsi or 50.0
568
+ rsi_factor = -((rsi - 50) / 50) * (0.5 if vol > 0.01 else 1.0)
569
+
570
+ # Weighted combination -- mirrors frontend sStats weights exactly
571
+ combined = (0.45 * math.copysign(min(1.0, abs(sl20) * 22), sl20)
572
+ + 0.30 * mean_rev
573
+ + 0.25 * rsi_factor)
574
+ slope_pct = math.tanh(combined) * 0.10 * 100
575
+
576
+ return slope_pct, "statsforecast-mstl", (
577
+ f"StatsForecast MSTL: sl20={sl20*100:.4f}%, dev={dev:.4f}, "
578
+ f"meanRev={mean_rev:.4f}, rsi={rsi:.1f}, vol={vol*100:.3f}%, slope={slope_pct:.4f}%."
579
+ )
580
+
581
+
582
  # ── Static model weights ──────────────────────────────────────────────────────
583
 
584
  STATIC_WEIGHTS = {
585
+ # Original 8 -- weights trimmed slightly to make room for 3 new models.
586
+ # Total still sums to 1.0 after renormalization in omega_forecast().
587
+ "Chronos": 0.14,
588
+ "TabPFN-TS": 0.10,
589
+ "DAG": 0.13,
590
+ "AROpt": 0.09,
591
+ "PatchTST": 0.12,
592
+ "TiDE": 0.10,
593
+ "MOIRAI": 0.06,
594
+ "N-BEATS": 0.04,
595
+ # New models (v14.4) -- mirror frontend localEnsemble names exactly
596
+ "River": 0.10, # SNARIMAX orderflow
597
+ "Informer": 0.08, # Fibonacci-attention + Polymarket
598
+ "StatsForecast": 0.04, # MSTL/ETS decomposition
599
  }
600
 
601
 
 
607
  "ok": True,
608
  "chronos": CHRONOS_AVAILABLE,
609
  "moirai": MOIRAI_AVAILABLE,
610
+ "version": "14.4.0",
611
  "models": list(STATIC_WEIGHTS.keys()),
612
  }
613
 
 
619
  horizon = req.horizon
620
  results: List[ModelResult] = []
621
 
622
+ # FIX 2: per-TF threshold -- was hardcoded 0.008 for all TFs
623
  tf_threshold = SLOPE_THRESHOLDS.get(req.timeframe, 0.003)
624
 
625
  # FIX (reviewer #4): compute context nudge ONCE here, apply to all models
 
630
  def add(name, slope_pct, note, reasoning, is_avail, threshold=None, conf_mult=1.0):
631
  t = threshold if threshold is not None else tf_threshold
632
  # Apply context nudge to slope before direction decision.
633
+ # Nudge is small (max ±0.008%) -- can tip near-threshold to DOWN/UP
634
  # but cannot reverse a confident model.
635
  nudged_slope = slope_pct + ctx_nudge
636
  direction, conf = slope_to_direction(nudged_slope, t)
 
642
  ))
643
 
644
  runners = [
645
+ ("Chronos", lambda: run_chronos(closes, horizon),
646
+ lambda: run_chronos_fallback(closes, horizon)),
647
+ ("TabPFN-TS", lambda: run_tabpfn(closes, horizon), None),
648
+ ("DAG", lambda: run_dag(closes, req), None),
649
+ ("AROpt", lambda: run_aropt(closes, horizon), None),
650
+ ("PatchTST", lambda: run_patchtst(closes, horizon), None),
651
+ ("TiDE", lambda: run_tide(closes, req, horizon), None),
652
+ ("MOIRAI", lambda: run_moirai(closes, horizon, req), None),
653
+ ("N-BEATS", lambda: run_nbeats(closes, horizon), None),
654
+ # v14.4: new runners matching frontend localEnsemble names
655
+ ("River", lambda: run_river(closes, horizon, req), None),
656
+ ("Informer", lambda: run_informer(closes, horizon, req), None),
657
+ ("StatsForecast", lambda: run_statsforecast(closes, horizon, req), None),
658
  ]
659
 
660
  for name, fn, fb in runners:
 
695
  total_weight += w
696
  comp_score = composite / total_weight if total_weight > 0 else 0.0
697
 
698
+ # ── Composite direction -- tightened NEUTRAL threshold ────────────────────
699
  # Old: fixed 0.03 for all TFs. New: per-TF, consistent with model thresholds.
700
  COMPOSITE_THRESHOLD = {"5M": 0.018, "15M": 0.015, "1D": 0.012}.get(req.timeframe, 0.018)
701