suppa09 commited on
Commit
a69e0ca
·
verified ·
1 Parent(s): c24f491

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -8
app.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- PolyBloom ML Service — v19.1.0
3
  Hugging Face Space: OMEGA COUNCIL (7 models)
4
 
5
  Model roster:
@@ -24,6 +24,14 @@ v19.1 changes:
24
  - Health endpoint now emits "catboost" boolean
25
  - Ensemble expanded to 7 models; weights renormalized
26
 
 
 
 
 
 
 
 
 
27
  Health endpoint GET /
28
  Omega endpoint POST /omega
29
  """
@@ -72,6 +80,8 @@ _flags: dict = {
72
  _models: dict = {} # name → loaded object
73
 
74
  # Weights — renormalized for 7 models (v19.1)
 
 
75
  WEIGHTS = {
76
  "Chronos": 0.20,
77
  "XGBoost": 0.18,
@@ -82,6 +92,49 @@ WEIGHTS = {
82
  "iTransformer": 0.08,
83
  }
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  # ─────────────────────────────────────────────────────────────────────────────
86
  # Helpers
87
  # ─────────────────────────────────────────────────────────────────────────────
@@ -625,10 +678,13 @@ def _predict_neuralforecast(closes: list, feats: dict) -> list:
625
 
626
  def _aggregate(predictions: list) -> dict:
627
  up_w = dn_w = total_w = 0.0
 
628
 
629
  for p in predictions:
630
  conf = p["confidence"] / 100.0
631
- w = WEIGHTS.get(p["name"], 0.10) * conf
 
 
632
  if p["direction"] == "UP":
633
  up_w += w
634
  elif p["direction"] == "DOWN":
@@ -641,21 +697,22 @@ def _aggregate(predictions: list) -> dict:
641
  composite_confidence=50,
642
  composite_score=0.0,
643
  models=predictions,
 
644
  is_local_fallback=False,
645
  )
646
 
647
  if up_w > dn_w:
648
- comp_dir = "UP"
649
  win_preds = [p for p in predictions if p["direction"] == "UP"]
650
  elif dn_w > up_w:
651
- comp_dir = "DOWN"
652
  win_preds = [p for p in predictions if p["direction"] == "DOWN"]
653
  else:
654
- comp_dir = "NEUTRAL"
655
  win_preds = []
656
 
657
- margin = abs(up_w - dn_w) / total_w
658
- avg_conf = (
659
  sum(p["confidence"] for p in win_preds) / len(win_preds)
660
  if win_preds else 50.0
661
  )
@@ -668,6 +725,7 @@ def _aggregate(predictions: list) -> dict:
668
  composite_confidence=comp_conf,
669
  composite_score=comp_score,
670
  models=predictions,
 
671
  is_local_fallback=False,
672
  )
673
 
@@ -680,7 +738,7 @@ def _aggregate(predictions: list) -> dict:
680
  async def health_check():
681
  return {
682
  "ok": True,
683
- "version": "19.1.0",
684
  "chronos": _flags["chronos"],
685
  "xgboost": _flags["xgboost"],
686
  "lgbm": _flags["lgbm"],
@@ -688,12 +746,83 @@ async def health_check():
688
  "patchtst": _flags["patchtst"],
689
  "nhits": _flags["nhits"],
690
  "itransformer": _flags["itransformer"],
 
691
  "models": ["Chronos", "XGBoost", "LightGBM", "CatBoost", "PatchTST", "N-HiTS", "iTransformer"],
692
  "removed": ["MOIRAI", "MOMENT", "TimesNet", "Lag-Llama", "DAG", "TiDE", "TabPFN-TS", "N-BEATS", "AROpt"],
693
  "hf_space": True,
694
  }
695
 
696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
697
  @app.post("/omega")
698
  async def omega(request: Request):
699
  t0 = time.perf_counter()
 
1
  """
2
+ PolyBloom ML Service — v19.2.0
3
  Hugging Face Space: OMEGA COUNCIL (7 models)
4
 
5
  Model roster:
 
24
  - Health endpoint now emits "catboost" boolean
25
  - Ensemble expanded to 7 models; weights renormalized
26
 
27
+ v19.2 changes (dynamic reweighting):
28
+ - ADDED: in-memory win/loss tracker (_win_stats) per model
29
+ - ADDED: _effective_weight() — blends static base weight with rolling win-rate
30
+ - _aggregate() now uses dynamic weights; same API surface, richer internals
31
+ - ADDED: POST /record_outcome — call after each resolved prediction
32
+ - ADDED: GET /model_stats — returns per-model wins/losses/win_rate/weight
33
+ - No schema changes to /omega response; new field "dynamic_weights" appended
34
+
35
  Health endpoint GET /
36
  Omega endpoint POST /omega
37
  """
 
80
  _models: dict = {} # name → loaded object
81
 
82
  # Weights — renormalized for 7 models (v19.1)
83
+ # These are BASE weights. At runtime _effective_weight() blends them with
84
+ # the rolling win-rate once a model has enough recorded outcomes.
85
  WEIGHTS = {
86
  "Chronos": 0.20,
87
  "XGBoost": 0.18,
 
92
  "iTransformer": 0.08,
93
  }
94
 
95
+ # ── Dynamic win/loss tracker (in-memory, resets on pod restart) ───────────────
96
+ # Structure: { model_name: {"wins": int, "losses": int} }
97
+ # Populated by POST /record_outcome. Used by _effective_weight().
98
+ _win_stats: dict = {name: {"wins": 0, "losses": 0} for name in WEIGHTS}
99
+
100
+ # Minimum resolved predictions before we start trusting win-rate over base weight.
101
+ # Below this threshold the model uses its full base weight (no penalty/boost).
102
+ _WIN_STATS_MIN_SAMPLES = 10
103
+
104
+ # How much the win-rate can shift a model's weight.
105
+ # At 60% win-rate → +20% boost. At 40% → -20% penalty. Capped at ±30%.
106
+ _WIN_RATE_SCALE = 0.6 # multiplier on (win_rate - 0.5)
107
+
108
+
109
+ def _effective_weight(name: str) -> float:
110
+ """
111
+ Blends the static base weight with recent win-rate performance.
112
+
113
+ Formula:
114
+ adj = clamp((win_rate - 0.5) * WIN_RATE_SCALE, -0.30, +0.30)
115
+ effective = base_weight * (1 + adj)
116
+
117
+ Below MIN_SAMPLES the adjustment is linearly ramped in so early noise
118
+ doesn't over-penalise a model in its first few predictions.
119
+ """
120
+ base = WEIGHTS.get(name, 0.10)
121
+ stats = _win_stats.get(name)
122
+ if not stats:
123
+ return base
124
+
125
+ total = stats["wins"] + stats["losses"]
126
+ if total == 0:
127
+ return base
128
+
129
+ win_rate = stats["wins"] / total
130
+ raw_adj = _clamp((win_rate - 0.5) * _WIN_RATE_SCALE, -0.30, 0.30)
131
+
132
+ # Ramp: blend in adjustment gradually up to MIN_SAMPLES
133
+ ramp = min(1.0, total / _WIN_STATS_MIN_SAMPLES)
134
+ adj = raw_adj * ramp
135
+
136
+ return max(0.01, base * (1.0 + adj))
137
+
138
  # ─────────────────────────────────────────────────────────────────────────────
139
  # Helpers
140
  # ─────────────────────────────────────────────────────────────────────────────
 
678
 
679
  def _aggregate(predictions: list) -> dict:
680
  up_w = dn_w = total_w = 0.0
681
+ dynamic_weights: dict = {}
682
 
683
  for p in predictions:
684
  conf = p["confidence"] / 100.0
685
+ eff = _effective_weight(p["name"])
686
+ w = eff * conf
687
+ dynamic_weights[p["name"]] = round(eff, 6)
688
  if p["direction"] == "UP":
689
  up_w += w
690
  elif p["direction"] == "DOWN":
 
697
  composite_confidence=50,
698
  composite_score=0.0,
699
  models=predictions,
700
+ dynamic_weights=dynamic_weights,
701
  is_local_fallback=False,
702
  )
703
 
704
  if up_w > dn_w:
705
+ comp_dir = "UP"
706
  win_preds = [p for p in predictions if p["direction"] == "UP"]
707
  elif dn_w > up_w:
708
+ comp_dir = "DOWN"
709
  win_preds = [p for p in predictions if p["direction"] == "DOWN"]
710
  else:
711
+ comp_dir = "NEUTRAL"
712
  win_preds = []
713
 
714
+ margin = abs(up_w - dn_w) / total_w
715
+ avg_conf = (
716
  sum(p["confidence"] for p in win_preds) / len(win_preds)
717
  if win_preds else 50.0
718
  )
 
725
  composite_confidence=comp_conf,
726
  composite_score=comp_score,
727
  models=predictions,
728
+ dynamic_weights=dynamic_weights,
729
  is_local_fallback=False,
730
  )
731
 
 
738
  async def health_check():
739
  return {
740
  "ok": True,
741
+ "version": "19.2.0",
742
  "chronos": _flags["chronos"],
743
  "xgboost": _flags["xgboost"],
744
  "lgbm": _flags["lgbm"],
 
746
  "patchtst": _flags["patchtst"],
747
  "nhits": _flags["nhits"],
748
  "itransformer": _flags["itransformer"],
749
+ "neuralforecast": _flags["patchtst"] and _flags["nhits"] and _flags["itransformer"],
750
  "models": ["Chronos", "XGBoost", "LightGBM", "CatBoost", "PatchTST", "N-HiTS", "iTransformer"],
751
  "removed": ["MOIRAI", "MOMENT", "TimesNet", "Lag-Llama", "DAG", "TiDE", "TabPFN-TS", "N-BEATS", "AROpt"],
752
  "hf_space": True,
753
  }
754
 
755
 
756
+ @app.get("/model_stats")
757
+ async def model_stats():
758
+ """
759
+ Returns per-model win/loss record and current effective weight.
760
+ Frontend (useMlModelStats.ts) can call this to display live accuracy.
761
+ """
762
+ result = {}
763
+ for name, base in WEIGHTS.items():
764
+ stats = _win_stats.get(name, {"wins": 0, "losses": 0})
765
+ total = stats["wins"] + stats["losses"]
766
+ win_rate = round(stats["wins"] / total, 4) if total > 0 else None
767
+ result[name] = {
768
+ "wins": stats["wins"],
769
+ "losses": stats["losses"],
770
+ "total": total,
771
+ "win_rate": win_rate,
772
+ "base_weight": base,
773
+ "effective_weight": round(_effective_weight(name), 6),
774
+ "min_samples": _WIN_STATS_MIN_SAMPLES,
775
+ "ramp_pct": round(min(1.0, total / _WIN_STATS_MIN_SAMPLES) * 100),
776
+ }
777
+ return {"models": result}
778
+
779
+
780
+ @app.post("/record_outcome")
781
+ async def record_outcome(request: Request):
782
+ """
783
+ Call this after each Polymarket window resolves.
784
+
785
+ Expected body:
786
+ {
787
+ "outcomes": [
788
+ { "model": "XGBoost", "predicted": "UP", "actual": "UP" },
789
+ { "model": "LightGBM", "predicted": "DOWN", "actual": "UP" },
790
+ ...
791
+ ]
792
+ }
793
+
794
+ Each entry where predicted == actual increments wins; otherwise losses.
795
+ Models not in WEIGHTS are silently ignored.
796
+ Returns updated stats for every model mentioned.
797
+ """
798
+ body = await request.json()
799
+ outcomes = body.get("outcomes", [])
800
+
801
+ if not isinstance(outcomes, list):
802
+ return JSONResponse(status_code=422, content={"error": "outcomes must be a list"})
803
+
804
+ updated = {}
805
+ for entry in outcomes:
806
+ name = entry.get("model", "")
807
+ predicted = entry.get("predicted", "")
808
+ actual = entry.get("actual", "")
809
+
810
+ if name not in _win_stats:
811
+ continue # unknown model — ignore
812
+ if predicted in ("UP", "DOWN") and actual in ("UP", "DOWN"):
813
+ if predicted == actual:
814
+ _win_stats[name]["wins"] += 1
815
+ else:
816
+ _win_stats[name]["losses"] += 1
817
+ updated[name] = {
818
+ **_win_stats[name],
819
+ "effective_weight": round(_effective_weight(name), 6),
820
+ }
821
+
822
+ logger.info("record_outcome: updated %d models — %s", len(updated), list(updated.keys()))
823
+ return {"updated": updated}
824
+
825
+
826
  @app.post("/omega")
827
  async def omega(request: Request):
828
  t0 = time.perf_counter()