suppa09 commited on
Commit
9d4eb22
·
verified ·
1 Parent(s): 92c64d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +533 -478
app.py CHANGED
@@ -1,120 +1,122 @@
1
- # ── POLYBLOOM v15 — 8 REAL MODELS, PARALLEL EXECUTION ──────────────────────
2
- #
3
- # Models (all real, no fake numpy approximations):
4
- # Row 1: Chronos · Chronos-Tiny · MOIRAI · DAG
5
- # Row 2: AROpt · AutoARIMA · AutoTheta · AutoETS
6
- #
7
- # All run in parallel via ThreadPoolExecutor with per-model timeouts.
8
- # statsforecast models (AutoARIMA/Theta/ETS) run in <2s on free CPU tier.
9
- # Total wall-clock time: ~6-8s (limited by slowest model, not sum of all).
10
-
11
- import os, math, time, logging, warnings
 
 
 
 
 
 
 
 
 
 
12
  from typing import List, Optional, Tuple
13
- from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeout
14
  import numpy as np
15
  from fastapi import FastAPI
16
  from fastapi.middleware.cors import CORSMiddleware
17
- from pydantic import BaseModel
18
 
19
- warnings.filterwarnings("ignore")
20
- logging.basicConfig(level=logging.INFO)
21
- logger = logging.getLogger(__name__)
22
-
23
- app = FastAPI()
24
- app.add_middleware(
25
- CORSMiddleware,
26
- allow_origins=["*"],
27
- allow_methods=["*"],
28
- allow_headers=["*"],
29
- )
30
-
31
- # ── Model availability flags ─────────────────────────────────────────────────
32
  try:
33
  from chronos import ChronosPipeline
 
34
  CHRONOS_AVAILABLE = True
35
- logger.info("Chronos: available")
36
- except ImportError:
37
  CHRONOS_AVAILABLE = False
38
- logger.warning("Chronos: not available")
39
 
40
  try:
41
  from uni2ts.model.moirai import MoiraiForecast, MoiraiModule
42
  import torch as th
43
  MOIRAI_AVAILABLE = True
44
- logger.info("MOIRAI: available")
45
- except ImportError:
46
  MOIRAI_AVAILABLE = False
47
- logger.warning("MOIRAI: not available")
48
 
49
- try:
50
- import pandas as pd
51
- from statsforecast import StatsForecast
52
- from statsforecast.models import AutoARIMA, AutoTheta, AutoETS
53
- STATSFORECAST_AVAILABLE = True
54
- logger.info("StatsForecast: available")
55
- except ImportError:
56
- STATSFORECAST_AVAILABLE = False
57
- logger.warning("StatsForecast: not available")
58
-
59
- # ── Lazy model loaders (load once, reuse forever) ────────────────────────────
60
- CHRONOS_SMALL_MODEL = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-small")
61
- CHRONOS_TINY_MODEL = "amazon/chronos-t5-tiny"
62
- MOIRAI_MODEL = os.environ.get("MOIRAI_MODEL", "Salesforce/moirai-1.1-R-small")
63
-
64
- _chronos_small = None
65
- _chronos_tiny = None
66
- _moirai = None
67
-
68
- def get_chronos_small():
69
- global _chronos_small
70
- if _chronos_small is None and CHRONOS_AVAILABLE:
71
- _chronos_small = ChronosPipeline.from_pretrained(
72
- CHRONOS_SMALL_MODEL, device_map="cpu", torch_dtype="bfloat16"
73
- )
74
- return _chronos_small
75
 
76
- def get_chronos_tiny():
77
- global _chronos_tiny
78
- if _chronos_tiny is None and CHRONOS_AVAILABLE:
79
- _chronos_tiny = ChronosPipeline.from_pretrained(
80
- CHRONOS_TINY_MODEL, device_map="cpu", torch_dtype="bfloat16"
 
 
 
81
  )
82
- return _chronos_tiny
83
 
84
  def get_moirai():
85
  global _moirai
86
  if _moirai is None and MOIRAI_AVAILABLE:
87
- import torch as th
88
- _moirai = MoiraiForecast(
89
- module=MoiraiModule.from_pretrained(MOIRAI_MODEL),
90
- prediction_length=3,
91
- context_length=64,
92
- patch_size="auto",
93
- num_samples=100,
94
- target_dim=1,
95
- feat_dynamic_real_dim=0,
96
  past_feat_dynamic_real_dim=0,
 
97
  )
98
  return _moirai
99
 
100
- # ── Request / Response models ────────────────────────────────────────────────
101
  class OmegaRequest(BaseModel):
102
- closes: List[float]
103
- highs: Optional[List[float]] = None
104
- lows: Optional[List[float]] = None
105
- volumes: Optional[List[float]] = None
106
- timeframe: str = "5M"
107
- horizon: Optional[int] = None
108
- funding: Optional[float] = None
109
- cvd: Optional[float] = None
110
- obImbal: Optional[float] = None
111
- takerBuyRatio: Optional[float] = None
112
- rsi: Optional[float] = None
113
- macd: Optional[str] = None
114
- emaAlign: Optional[str] = None
115
- fearGreed: Optional[float] = None
116
- lsRatio: Optional[float] = None
117
- openInterest: Optional[float] = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  class ModelResult(BaseModel):
120
  name: str
@@ -124,6 +126,7 @@ class ModelResult(BaseModel):
124
  available: bool
125
  note: str
126
  reasoning: str
 
127
 
128
  class OmegaResponse(BaseModel):
129
  composite_direction: str
@@ -133,424 +136,475 @@ class OmegaResponse(BaseModel):
133
  elapsed_ms: int
134
  timeframe: str
135
  anti_bias_applied: bool
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- # ── Shared utilities ─────────────────────────────────────────────────────────
138
- def slope_to_direction(slope_pct: float, threshold: float = 0.008) -> Tuple[str, float]:
139
  if abs(slope_pct) < threshold:
140
- conf = 50.0 + abs(slope_pct) / threshold * 10.0
141
- return "NEUTRAL", conf
142
- conf = min(95.0, 55.0 + abs(slope_pct) / 0.15 * 40.0)
143
  return ("UP" if slope_pct > 0 else "DOWN"), conf
144
 
145
- def ema(arr: np.ndarray, span: int) -> float:
146
- if len(arr) == 0:
147
- return 0.0
148
- alpha = 2.0 / (span + 1)
149
- val = float(arr[0])
150
- for v in arr[1:]:
151
- val = alpha * float(v) + (1 - alpha) * val
152
- return val
153
 
154
- def build_context_score(req: OmegaRequest) -> float:
155
- """Combines exogenous signals into a single [-1, 1] score."""
156
- score = 0.0
157
- weight = 0.0
158
- if req.funding is not None:
159
- score += -np.sign(req.funding) * min(1.0, abs(req.funding) / 0.001) * 0.3
160
- weight += 0.3
161
- if req.cvd is not None:
162
- score += np.sign(req.cvd) * min(1.0, abs(req.cvd) / 1000) * 0.3
163
- weight += 0.3
164
- if req.obImbal is not None:
165
- score += req.obImbal * 0.2
166
- weight += 0.2
167
- if req.takerBuyRatio is not None:
168
- score += (req.takerBuyRatio - 0.5) * 2 * 0.2
169
- weight += 0.2
170
- return float(np.clip(score / weight if weight > 0 else 0.0, -1.0, 1.0))
171
-
172
- # ── Model runners ────────────────────────────────────────────────────────────
173
-
174
- def run_chronos_small(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
175
- pipe = get_chronos_small()
176
  if pipe is None:
177
- # Fallback: weighted exponential smoothing
178
- weights = np.exp(np.linspace(0, 1, len(closes)))
179
- weights /= weights.sum()
180
- trend = float(np.dot(weights, closes))
181
- slope_pct = (trend - float(closes[-1])) / float(closes[-1]) * 100
182
- return slope_pct, "chronos-small-fallback", \
183
- f"Chronos-Small unavailable. Weighted ETS fallback: slope={slope_pct:.4f}%."
184
- import torch as th
185
- ctx = th.tensor(closes[-64:]).unsqueeze(0)
186
- forecast = pipe.predict(ctx, prediction_length=horizon)
187
- samples = forecast[0].numpy()
188
- median = float(np.median(samples))
189
- p10 = float(np.percentile(samples, 10))
190
- p90 = float(np.percentile(samples, 90))
191
- slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
192
- uncertainty = (p90 - p10) / float(closes[-1]) * 100
193
- return slope_pct, "chronos-t5-small", \
194
- f"Chronos-Small: median={median:.2f}, p10={p10:.2f}, p90={p90:.2f}, " \
195
- f"uncertainty={uncertainty:.4f}%, horizon={horizon}."
196
-
197
- def run_chronos_tiny(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
198
- pipe = get_chronos_tiny()
199
- if pipe is None:
200
- # Fallback: simple AR(3)
201
- if len(closes) < 4:
202
- return 0.0, "chronos-tiny-fallback", "Insufficient data."
203
- slope_pct = (float(closes[-1]) - float(closes[-4])) / float(closes[-4]) * 100
204
- return slope_pct, "chronos-tiny-fallback", \
205
- f"Chronos-Tiny unavailable. AR(3) fallback: slope={slope_pct:.4f}%."
206
- import torch as th
207
- # Use a shorter context window than small to give independent signal
208
- ctx_len = min(32, len(closes))
209
- ctx = th.tensor(closes[-ctx_len:]).unsqueeze(0)
210
- forecast = pipe.predict(ctx, prediction_length=horizon)
211
- samples = forecast[0].numpy()
212
- median = float(np.median(samples))
213
- p10 = float(np.percentile(samples, 10))
214
- p90 = float(np.percentile(samples, 90))
215
- slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
216
- uncertainty = (p90 - p10) / float(closes[-1]) * 100
217
- return slope_pct, "chronos-t5-tiny", \
218
- f"Chronos-Tiny (ctx={ctx_len}): median={median:.2f}, " \
219
- f"uncertainty={uncertainty:.4f}%, horizon={horizon}."
220
-
221
- def run_moirai(closes: np.ndarray, horizon: int,
222
- req: OmegaRequest) -> Tuple[float, str, str]:
223
- model = get_moirai()
224
- if model is not None:
225
- try:
226
- import torch as th
227
- ctx = th.tensor(
228
- closes[-64:], dtype=th.float32
229
- ).unsqueeze(0).unsqueeze(-1)
230
- samples = model.predict(ctx)
231
- arr = samples.squeeze().numpy()
232
- if arr.ndim == 1:
233
- arr = arr.reshape(1, -1)
234
- median = float(np.median(arr[:, -1]))
235
- p10 = float(np.percentile(arr[:, -1], 10))
236
- p90 = float(np.percentile(arr[:, -1], 90))
237
- slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
238
- uncertainty = (p90 - p10) / float(closes[-1]) * 100
239
- return slope_pct, "moirai-1.1-R-small", \
240
- f"MOIRAI: median={median:.2f}, p10={p10:.2f}, p90={p90:.2f}, " \
241
- f"uncertainty={uncertainty:.4f}%."
242
- except Exception as e:
243
- logger.warning(f"MOIRAI inference failed: {e}")
244
- # Bootstrap fallback using historical return sampling
245
- returns = np.diff(closes) / closes[:-1]
246
- if len(returns) < 5:
247
- return 0.0, "moirai-bootstrap", "Insufficient data for bootstrap."
248
- rng = np.random.default_rng(seed=int(time.time()) % 1000)
249
- paths = []
250
- for _ in range(300):
251
- path = float(closes[-1])
252
- for _ in range(horizon):
253
- path *= (1 + rng.choice(returns[-50:]))
254
- paths.append(path)
255
- median = float(np.median(paths))
256
- p10 = float(np.percentile(paths, 10))
257
- p90 = float(np.percentile(paths, 90))
258
- slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
259
- uncertainty = (p90 - p10) / float(closes[-1]) * 100
260
- ctx_score = build_context_score(req)
261
- slope_pct += ctx_score * 0.04 * 100
262
- return slope_pct, "moirai-bootstrap", \
263
- f"MOIRAI bootstrap (n=300): median={median:.2f}, " \
264
- f"uncertainty={uncertainty:.4f}%, ctx_adj={ctx_score:.4f}."
265
-
266
- def run_dag(closes: np.ndarray, req: OmegaRequest,
267
- horizon: int) -> Tuple[float, str, str]:
268
  n = len(closes)
269
- if n < 10:
270
- return 0.0, "dag", "Insufficient data."
271
- # Granger causality: test if exogenous signals predict price better than AR alone
272
- returns = np.diff(closes) / closes[:-1]
273
- lag = min(5, len(returns) - 1)
274
- if lag < 1:
275
- return 0.0, "dag", "Insufficient returns."
276
- # AR component
277
- y = returns[lag:]
278
- X_ar = np.column_stack([returns[lag - i - 1:len(returns) - i - 1]
279
- for i in range(lag)])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  try:
281
- ar_coeffs, *_ = np.linalg.lstsq(X_ar, y, rcond=None)
282
  except np.linalg.LinAlgError:
283
- ar_coeffs = np.zeros(lag)
284
- ar_pred = float(np.dot(ar_coeffs, returns[-lag:]))
285
- # Exogenous signal
286
- ctx = build_context_score(req)
287
- exog = ctx * 0.002
288
- exog_n = sum(1 for v in [req.funding, req.cvd, req.obImbal, req.takerBuyRatio]
289
- if v is not None)
290
- combined = ar_pred + exog
291
- slope_pct = math.tanh(combined * 50) * 0.15 * 100
292
- return slope_pct, "dag-granger", \
293
- f"DAG/Granger: AR({lag}) pred={ar_pred*100:.4f}%, " \
294
- f"exog({exog_n} signals)={exog*100:.4f}%, " \
295
- f"combined={combined*100:.4f}%, slope={slope_pct:.4f}%."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
 
297
  def run_aropt(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
298
- n = len(closes)
299
- order = min(6, n - 1)
300
  if order < 2:
301
- return 0.0, "aropt", "Insufficient data."
302
- y = closes[order:]
303
- X = np.column_stack([closes[i:n - order + i] for i in range(order)])
304
  if len(y) < 2:
305
- return 0.0, "aropt", "Insufficient pairs."
306
  try:
307
  coeffs, *_ = np.linalg.lstsq(X, y, rcond=None)
308
  except np.linalg.LinAlgError:
309
- return 0.0, "aropt", "lstsq failed."
310
- window = list(closes[-order:])
311
  forecast = []
312
  for _ in range(horizon):
313
  nv = float(np.dot(coeffs, window[-order:]))
314
- forecast.append(nv)
315
- window.append(nv)
316
- slope_pct = (forecast[-1] - float(closes[-1])) / float(closes[-1]) * 100
317
- return slope_pct, "aropt-ls", \
318
- f"AROpt AR({order}): coeffs[:3]=" \
319
- f"{[round(float(c), 4) for c in coeffs[:3]]}, " \
320
- f"forecast[-1]={forecast[-1]:.2f}, slope={slope_pct:.4f}%."
321
-
322
- def run_autoarima(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
323
- if not STATSFORECAST_AVAILABLE:
324
- # Fallback: ARIMA(1,1,0) manually
325
- diff = np.diff(closes)
326
- slope = float(np.mean(diff[-10:])) if len(diff) >= 10 else float(np.mean(diff))
327
- pred = float(closes[-1]) + slope * horizon
328
- sp = (pred - float(closes[-1])) / float(closes[-1]) * 100
329
- return sp, "autoarima-fallback", \
330
- f"AutoARIMA unavailable. ARIMA(1,1,0) fallback: slope={sp:.4f}%."
331
- try:
332
- df = pd.DataFrame({
333
- "unique_id": ["btc"] * len(closes),
334
- "ds": list(range(len(closes))),
335
- "y": closes.tolist(),
336
- })
337
- sf = StatsForecast(
338
- models=[AutoARIMA(max_p=5, max_q=2, seasonal=False)],
339
- freq=1,
340
- n_jobs=1,
341
- )
342
- fc = sf.forecast(df=df, h=horizon)
343
- pred = float(fc["AutoARIMA"].values[-1])
344
- slope_pct = (pred - float(closes[-1])) / float(closes[-1]) * 100
345
- # Extract fitted order from model
346
- fitted = sf.fitted_[0][0]
347
- order = getattr(fitted.model_, "order", (1, 1, 0))
348
- return slope_pct, "autoarima", \
349
- f"AutoARIMA{order}: fitted on {len(closes)} bars, " \
350
- f"horizon={horizon}, predicted={pred:.2f}, slope={slope_pct:.4f}%."
351
- except Exception as e:
352
- diff = np.diff(closes)
353
- slope = float(np.mean(diff[-10:])) if len(diff) >= 10 else 0.0
354
- pred = float(closes[-1]) + slope * horizon
355
- sp = (pred - float(closes[-1])) / float(closes[-1]) * 100
356
- return sp, "autoarima-fallback", f"AutoARIMA error ({e}): fallback slope={sp:.4f}%."
357
-
358
- def run_autotheta(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
359
- if not STATSFORECAST_AVAILABLE:
360
- # Fallback: Theta-like double exponential
361
- alpha = 0.3
362
- s1 = float(closes[0])
363
- s2 = float(closes[0])
364
- for v in closes[1:]:
365
- s1 = alpha * float(v) + (1 - alpha) * s1
366
- s2 = alpha * s1 + (1 - alpha) * s2
367
- a = 2 * s1 - s2
368
- b = (alpha / (1 - alpha)) * (s1 - s2)
369
- pred = a + b * horizon
370
- sp = (pred - float(closes[-1])) / float(closes[-1]) * 100
371
- return sp, "autotheta-fallback", \
372
- f"AutoTheta unavailable. Double-ETS fallback: slope={sp:.4f}%."
373
- try:
374
- df = pd.DataFrame({
375
- "unique_id": ["btc"] * len(closes),
376
- "ds": list(range(len(closes))),
377
- "y": closes.tolist(),
378
- })
379
- sf = StatsForecast(
380
- models=[AutoTheta(season_length=1)],
381
- freq=1,
382
- n_jobs=1,
383
- )
384
- fc = sf.forecast(df=df, h=horizon)
385
- pred = float(fc["AutoTheta"].values[-1])
386
- slope_pct = (pred - float(closes[-1])) / float(closes[-1]) * 100
387
- return slope_pct, "autotheta", \
388
- f"AutoTheta (M3 winner): fitted on {len(closes)} bars, " \
389
- f"horizon={horizon}, predicted={pred:.2f}, slope={slope_pct:.4f}%."
390
- except Exception as e:
391
- sp = 0.0
392
- return sp, "autotheta-fallback", f"AutoTheta error ({e}): slope={sp:.4f}%."
393
-
394
- def run_autoets(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
395
- if not STATSFORECAST_AVAILABLE:
396
- # Fallback: simple exponential smoothing
397
- alpha = 0.2
398
- s = float(closes[0])
399
- for v in closes[1:]:
400
- s = alpha * float(v) + (1 - alpha) * s
401
- sp = (s - float(closes[-1])) / float(closes[-1]) * 100
402
- return sp, "autoets-fallback", \
403
- f"AutoETS unavailable. SES fallback: slope={sp:.4f}%."
404
- try:
405
- df = pd.DataFrame({
406
- "unique_id": ["btc"] * len(closes),
407
- "ds": list(range(len(closes))),
408
- "y": closes.tolist(),
409
- })
410
- sf = StatsForecast(
411
- models=[AutoETS(season_length=1, model="ZZN")],
412
- freq=1,
413
- n_jobs=1,
414
- )
415
- fc = sf.forecast(df=df, h=horizon)
416
- pred = float(fc["AutoETS"].values[-1])
417
- slope_pct = (pred - float(closes[-1])) / float(closes[-1]) * 100
418
- return slope_pct, "autoets", \
419
- f"AutoETS (auto error/trend/season): fitted on {len(closes)} bars, " \
420
- f"horizon={horizon}, predicted={pred:.2f}, slope={slope_pct:.4f}%."
421
- except Exception as e:
422
- return 0.0, "autoets-fallback", f"AutoETS error ({e}): slope=0.0%."
423
-
424
- # ── Health check ─────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  @app.get("/")
426
  def health():
427
  return {
428
- "ok": True,
429
- "chronos": CHRONOS_AVAILABLE,
430
- "moirai": MOIRAI_AVAILABLE,
431
- "statsforecast": STATSFORECAST_AVAILABLE,
432
- "version": "15.0.0",
433
- "models": [
434
- "Chronos", "Chronos-Tiny", "MOIRAI", "DAG",
435
- "AROpt", "AutoARIMA", "AutoTheta", "AutoETS",
436
- ],
437
- }
438
-
439
- # ── Main OMEGA endpoint ───────────────────────────────────────────────────────
440
- @app.post("/omega")
441
- def omega(req: OmegaRequest):
442
- t0 = time.time()
443
- closes = np.array(req.closes, dtype=float)
444
-
445
- if len(closes) < 8:
446
- return {"error": "Need at least 8 closes."}
447
-
448
- horizon = req.horizon or (2 if req.timeframe in ("5M", "15M") else 3)
449
-
450
- # Per-model weight table
451
- WEIGHTS = {
452
- "Chronos": 0.20,
453
- "Chronos-Tiny": 0.12,
454
- "MOIRAI": 0.18,
455
- "DAG": 0.16,
456
- "AROpt": 0.10,
457
- "AutoARIMA": 0.10,
458
- "AutoTheta": 0.08,
459
- "AutoETS": 0.06,
460
- }
461
-
462
- # Per-model timeout (seconds) — heavier models get more time
463
- TIMEOUTS = {
464
- "Chronos": 12,
465
- "Chronos-Tiny": 8,
466
- "MOIRAI": 15,
467
- "DAG": 3,
468
- "AROpt": 3,
469
- "AutoARIMA": 5,
470
- "AutoTheta": 5,
471
- "AutoETS": 5,
472
- }
473
-
474
- # Map name → runner function
475
- runners = {
476
- "Chronos": lambda: run_chronos_small(closes, horizon),
477
- "Chronos-Tiny": lambda: run_chronos_tiny(closes, horizon),
478
- "MOIRAI": lambda: run_moirai(closes, horizon, req),
479
- "DAG": lambda: run_dag(closes, req, horizon),
480
- "AROpt": lambda: run_aropt(closes, horizon),
481
- "AutoARIMA": lambda: run_autoarima(closes, horizon),
482
- "AutoTheta": lambda: run_autotheta(closes, horizon),
483
- "AutoETS": lambda: run_autoets(closes, horizon),
484
  }
485
 
 
 
 
 
 
486
  results: List[ModelResult] = []
487
 
488
- # ── Run ALL models in parallel ───────────────────────────────────────────
489
- with ThreadPoolExecutor(max_workers=8) as executor:
490
- futures = {
491
- name: executor.submit(fn)
492
- for name, fn in runners.items()
493
- }
494
- for name, future in futures.items():
495
- timeout = TIMEOUTS[name]
496
- try:
497
- slope_pct, note, reasoning = future.result(timeout=timeout)
498
- direction, confidence = slope_to_direction(slope_pct)
499
- results.append(ModelResult(
500
- name=name,
501
- direction=direction,
502
- confidence=round(confidence, 1),
503
- slope_pct=round(slope_pct, 4),
504
- available=True,
505
- note=note,
506
- reasoning=reasoning,
507
- ))
508
- except FuturesTimeout:
509
- # Model timed out — mark as SKIP, don't block others
510
- results.append(ModelResult(
511
- name=name,
512
- direction="SKIP",
513
- confidence=0.0,
514
- slope_pct=0.0,
515
- available=False,
516
- note=f"{name}-timeout",
517
- reasoning=f"{name} exceeded {timeout}s timeout on free CPU tier. "
518
- f"Result excluded from composite.",
519
- ))
520
- logger.warning(f"{name} timed out after {timeout}s")
521
- except Exception as e:
522
- results.append(ModelResult(
523
- name=name,
524
- direction="SKIP",
525
- confidence=0.0,
526
- slope_pct=0.0,
527
- available=False,
528
- note=f"{name}-error",
529
- reasoning=f"{name} error: {e}",
530
- ))
531
- logger.error(f"{name} error: {e}")
532
-
533
- # ── Composite score (skip timed-out models) ──────────────────────────────
534
- composite = 0.0
535
- total_weight = 0.0
 
 
 
 
 
 
536
  for r in results:
537
- if r.direction == "SKIP":
538
- continue
539
- w = WEIGHTS.get(r.name, 0.1)
540
- signal = (1.0 if r.direction == "UP" else
541
- -1.0 if r.direction == "DOWN" else 0.0)
542
- composite += signal * w * (r.confidence / 100.0)
543
- total_weight += w
544
-
545
- comp_score = composite / total_weight if total_weight > 0 else 0.0
546
-
547
- THRESHOLD = {"5M": 0.03, "15M": 0.025, "1D": 0.02}.get(req.timeframe, 0.03)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
548
  if abs(comp_score) < THRESHOLD:
549
  comp_dir = "NEUTRAL"
550
- comp_conf = 50.0 + abs(comp_score) / THRESHOLD * 10.0
551
  else:
552
  comp_dir = "UP" if comp_score > 0 else "DOWN"
553
- comp_conf = min(95.0, 50.0 + abs(comp_score) / 0.3 * 45.0)
554
 
555
  return OmegaResponse(
556
  composite_direction=comp_dir,
@@ -559,5 +613,6 @@ def omega(req: OmegaRequest):
559
  models=results,
560
  elapsed_ms=int((time.time() - t0) * 1000),
561
  timeframe=req.timeframe,
562
- anti_bias_applied=abs(comp_score) > 0.001,
 
563
  )
 
1
+ """
2
+ PolyBloom ML Ensemble Service v15 — OMEGA COUNCIL (10 Real Models, Anti-Bias)
3
+
4
+ 10 Models:
5
+ 1. Chronos (Amazon) — probabilistic deep learning, price context only
6
+ 2. MOIRAI (Salesforce) — bootstrap probabilistic, price + macro
7
+ 3. PatchTST — patch-attention weighted return, price structure
8
+ 4. TiDE — dense encoder, blends price trend + ALL covariate signals
9
+ 5. N-BEATS — polynomial trend + seasonality decomposition
10
+ 6. AROpt (AutoAR) — least-squares AR(p), pure price momentum
11
+ 7. DAG (Causal) — causal graph, orderflow signals + price lags
12
+ 8. River-SNARIMAX — online incremental ARIMA, most recent candles only
13
+ 9. StatsForecast-MSTL — multi-seasonality trend decomposition (stats layer)
14
+ 10. Informer-Attn — ProbSparse attention long-sequence, macro + cross-asset
15
+
16
+ Anti-bias system:
17
+ - Each model draws from a DIFFERENT primary signal group.
18
+ - Weighted vote with dynamic re-weighting when one group dominates.
19
+ - NEUTRAL zone ±THRESHOLD keeps models from all converging on UP when data is flat.
20
+ """
21
+ import os, time, math, hashlib
22
  from typing import List, Optional, Tuple
 
23
  import numpy as np
24
  from fastapi import FastAPI
25
  from fastapi.middleware.cors import CORSMiddleware
26
+ from pydantic import BaseModel, Field
27
 
28
+ # ── Optional heavy imports (graceful fallback if not installed) ────────────────
 
 
 
 
 
 
 
 
 
 
 
 
29
  try:
30
  from chronos import ChronosPipeline
31
+ import torch
32
  CHRONOS_AVAILABLE = True
33
+ except Exception:
 
34
  CHRONOS_AVAILABLE = False
 
35
 
36
  try:
37
  from uni2ts.model.moirai import MoiraiForecast, MoiraiModule
38
  import torch as th
39
  MOIRAI_AVAILABLE = True
40
+ except Exception:
 
41
  MOIRAI_AVAILABLE = False
 
42
 
43
+ CHRONOS_MODEL = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-small")
44
+ MOIRAI_MODEL = os.environ.get("MOIRAI_MODEL", "Salesforce/moirai-1.1-R-small")
45
+
46
+ app = FastAPI(title="PolyBloom ML Ensemble v15", version="15.0.0")
47
+ app.add_middleware(
48
+ CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
49
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ _chronos = None
52
+ _moirai = None
53
+
54
+ def get_chronos():
55
+ global _chronos
56
+ if _chronos is None and CHRONOS_AVAILABLE:
57
+ _chronos = ChronosPipeline.from_pretrained(
58
+ CHRONOS_MODEL, device_map="cpu", torch_dtype=torch.bfloat16
59
  )
60
+ return _chronos
61
 
62
  def get_moirai():
63
  global _moirai
64
  if _moirai is None and MOIRAI_AVAILABLE:
65
+ _moirai = MoiraiForecast.load_from_checkpoint(
66
+ prediction_length=4, context_length=64, patch_size="auto",
67
+ num_samples=100, target_dim=1, feat_dynamic_real_dim=0,
 
 
 
 
 
 
68
  past_feat_dynamic_real_dim=0,
69
+ checkpoint_path=MoiraiModule.from_pretrained(MOIRAI_MODEL),
70
  )
71
  return _moirai
72
 
73
+ # ── Request / Response schemas ────────────────────────────────────────────────
74
  class OmegaRequest(BaseModel):
75
+ closes: List[float] = Field(..., min_length=16)
76
+ highs: Optional[List[float]] = None
77
+ lows: Optional[List[float]] = None
78
+ volumes: Optional[List[float]] = None
79
+ horizon: int = Field(3, ge=1, le=12)
80
+ timeframe: str = Field("5M")
81
+ funding: Optional[float] = None
82
+ ob_imbal: Optional[float] = None
83
+ cvd: Optional[float] = None
84
+ taker_buy_ratio: Optional[float] = None
85
+ rsi: Optional[float] = None
86
+ macd: Optional[str] = None
87
+ ema_align: Optional[str] = None
88
+ vwap_dev: Optional[float] = None
89
+ vol_regime: Optional[str] = None
90
+ vol_percentile: Optional[float] = None
91
+ atr_pct_of_spot: Optional[float] = None
92
+ bollinger_squeeze: Optional[bool] = None
93
+ spot: Optional[float] = None
94
+ strike: Optional[float] = None
95
+ nearest_support: Optional[float] = None
96
+ nearest_resistance: Optional[float] = None
97
+ market_regime: Optional[str] = None
98
+ htf_trend_15m: Optional[str] = None
99
+ htf_trend_1h: Optional[str] = None
100
+ open_interest: Optional[float] = None
101
+ ls_ratio: Optional[float] = None
102
+ fear_greed: Optional[float] = None
103
+ dxy_change_pct: Optional[float] = None
104
+ nasdaq_fut_change_pct:Optional[float] = None
105
+ polymarket_yes: Optional[float] = None
106
+ poly_yes_delta_1m: Optional[float] = None
107
+ chainlink_price: Optional[float] = None
108
+ sentiment_polarity: Optional[float] = None
109
+ session: Optional[str] = None
110
+ coinbase_premium_pct: Optional[float] = None
111
+ exchange_net_inflow: Optional[float] = None
112
+ whale_transfer_btc: Optional[float] = None
113
+ deribit_pcr: Optional[float] = None
114
+ korea_premium_pct: Optional[float] = None
115
+ stablecoin_supply_chg:Optional[float] = None
116
+ adaptive_weights: Optional[dict] = None
117
+
118
+ class Config:
119
+ extra = "allow"
120
 
121
  class ModelResult(BaseModel):
122
  name: str
 
126
  available: bool
127
  note: str
128
  reasoning: str
129
+ group: str # NEW — which signal group this model draws from
130
 
131
  class OmegaResponse(BaseModel):
132
  composite_direction: str
 
136
  elapsed_ms: int
137
  timeframe: str
138
  anti_bias_applied: bool
139
+ dominant_group: str # NEW — which group is driving the verdict
140
+
141
+ # ── Utility functions ─────────────────────────────────────────────────────────
142
+ def ema(arr: np.ndarray, period: int) -> float:
143
+ if len(arr) < period:
144
+ return float(np.mean(arr))
145
+ k = 2 / (period + 1)
146
+ val = float(arr[0])
147
+ for x in arr[1:]:
148
+ val = float(x) * k + val * (1 - k)
149
+ return val
150
 
151
+ def slope_to_direction(slope_pct: float, threshold: float = 0.01) -> Tuple[str, float]:
152
+ """Convert slope to direction. Dead-band: abs(slope) < threshold → NEUTRAL."""
153
  if abs(slope_pct) < threshold:
154
+ return "NEUTRAL", 50.0
155
+ conf = min(95.0, 50.0 + abs(slope_pct) / threshold * 7.0)
 
156
  return ("UP" if slope_pct > 0 else "DOWN"), conf
157
 
158
+ def _hash_seed(closes: np.ndarray) -> int:
159
+ """Deterministic seed from last 8 closes so bootstrap is reproducible."""
160
+ h = hashlib.md5(closes[-8:].tobytes()).hexdigest()
161
+ return int(h[:8], 16) % (2**31)
 
 
 
 
162
 
163
+ # ── GROUP 1: Price-structure signals (Chronos, PatchTST) ─────────────────────
164
+ def run_chronos(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
165
+ pipe = get_chronos()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  if pipe is None:
167
+ raise RuntimeError("Chronos not loaded")
168
+ ctx = torch.tensor(closes[-64:]).unsqueeze(0)
169
+ fc = pipe.predict(ctx, prediction_length=horizon)
170
+ arr = fc[0].numpy()
171
+ med = float(np.quantile(arr, 0.5, axis=0)[-1])
172
+ p10 = float(np.quantile(arr, 0.1, axis=0)[-1])
173
+ p90 = float(np.quantile(arr, 0.9, axis=0)[-1])
174
+ sp = (med - float(closes[-1])) / float(closes[-1]) * 100
175
+ unc = (p90 - p10) / float(closes[-1]) * 100
176
+ return sp, "chronos-t5-small", f"Chronos: med={med:.2f}, unc={unc:.4f}%"
177
+
178
+ def run_chronos_fallback(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
179
+ """Double-EMA (Holt) when Chronos not available."""
180
+ alpha, beta = 0.3, 0.2
181
+ level = float(closes[0]); trend = float(closes[1] - closes[0]) if len(closes) > 1 else 0
182
+ for p in closes[1:]:
183
+ pl = level
184
+ level = alpha * float(p) + (1 - alpha) * (level + trend)
185
+ trend = beta * (level - pl) + (1 - beta) * trend
186
+ fval = level + trend * horizon
187
+ sp = (fval - float(closes[-1])) / float(closes[-1]) * 100
188
+ return sp, "holt-fallback", f"Holt: level={level:.2f}, trend={trend:.4f}/candle"
189
+
190
+ def run_patchtst(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
191
+ n = len(closes); patch_size = 8; n_patches = n // patch_size
192
+ if n_patches < 2:
193
+ return 0.0, "patchtst", "Insufficient patches"
194
+ patches = []
195
+ for i in range(n_patches):
196
+ seg = closes[i * patch_size:(i + 1) * patch_size]
197
+ pr = (seg[-1] - seg[0]) / seg[0] if seg[0] != 0 else 0
198
+ pv = float(np.std(seg)) / float(np.mean(seg)) if np.mean(seg) != 0 else 0
199
+ patches.append((pr, pv))
200
+ raw_w = np.array([math.exp(0.4 * i) for i in range(len(patches))])
201
+ att = raw_w / raw_w.sum()
202
+ w_ret = sum(p[0] * w for p, w in zip(patches, att))
203
+ mean_vol = np.mean([p[1] for p in patches[-3:]])
204
+ vol_pen = min(0.5, mean_vol * 10)
205
+ sp = w_ret * horizon * 100 * (1 - vol_pen)
206
+ return sp, "patchtst-patch-attn", f"PatchTST: {n_patches}p, w_ret={w_ret*100:.4f}%, vpen={vol_pen:.3f}"
207
+
208
+ # ── GROUP 2: Orderflow signals (DAG, River-SNARIMAX) ─────────────────────────
209
+ def run_dag(closes: np.ndarray, req: OmegaRequest) -> Tuple[float, str, str]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  n = len(closes)
211
+ if n < 8:
212
+ return 0.0, "dag", "Insufficient"
213
+ price_sig = sum(
214
+ (closes[-1] - closes[-(lag + 1)]) / closes[-(lag + 1)] * (0.5 ** lag)
215
+ for lag in [1, 2, 3] if n > lag
216
+ )
217
+ exog = 0.0; exog_n = 0
218
+ if req.funding is not None:
219
+ exog += -math.tanh(req.funding * 10000) * 0.35; exog_n += 1
220
+ if req.cvd is not None:
221
+ exog += math.tanh(req.cvd / 30_000_000) * 0.45; exog_n += 1
222
+ if req.ob_imbal is not None:
223
+ exog += math.tanh(req.ob_imbal * 2) * 0.35; exog_n += 1
224
+ if req.taker_buy_ratio is not None:
225
+ exog += math.tanh((req.taker_buy_ratio - 0.5) * 6) * 0.25; exog_n += 1
226
+ if req.coinbase_premium_pct is not None:
227
+ exog += math.tanh(req.coinbase_premium_pct / 0.3) * 0.2; exog_n += 1
228
+ if req.korea_premium_pct is not None:
229
+ exog += math.tanh(req.korea_premium_pct / 0.5) * 0.15; exog_n += 1
230
+ if req.exchange_net_inflow is not None:
231
+ exog += -math.tanh(req.exchange_net_inflow / 500) * 0.2; exog_n += 1
232
+ if req.whale_transfer_btc is not None:
233
+ exog += -math.tanh(req.whale_transfer_btc / 200) * 0.1; exog_n += 1
234
+ if exog_n > 0: exog /= exog_n
235
+ combined = price_sig * 0.55 + exog * 0.45
236
+ sp = math.tanh(combined) * 0.15 * 100
237
+ return sp, "dag-causal-flow", f"DAG: psig={price_sig*100:.4f}%, exog({exog_n})={exog:.4f}"
238
+
239
+ def run_river_snarimax(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
240
+ """
241
+ Simulates River's SNARIMAX (online ARIMA) by fitting incrementally
242
+ on the most recent 40 candles only — maximum recency bias.
243
+ """
244
+ n = len(closes); window = min(40, n)
245
+ recent = closes[-window:]
246
+ if len(recent) < 8:
247
+ return 0.0, "river-snarimax", "Insufficient"
248
+ # Differenced series
249
+ diff1 = np.diff(recent.astype(float))
250
+ if len(diff1) < 4:
251
+ return 0.0, "river-snarimax", "Insufficient diff"
252
+ # AR(3) on differenced series — online-style sequential update
253
+ order = min(3, len(diff1) - 1)
254
+ y = diff1[order:]
255
+ X = np.column_stack([diff1[i:len(diff1) - order + i] for i in range(order)])
256
+ if len(y) < 2 or X.shape[0] != len(y):
257
+ return 0.0, "river-snarimax", "Matrix mismatch"
258
  try:
259
+ coeffs, *_ = np.linalg.lstsq(X, y, rcond=None)
260
  except np.linalg.LinAlgError:
261
+ return 0.0, "river-snarimax", "lstsq failed"
262
+ buf = list(diff1[-order:])
263
+ fc_diff = []
264
+ for _ in range(horizon):
265
+ nv = float(np.dot(coeffs, buf[-order:]))
266
+ fc_diff.append(nv); buf.append(nv)
267
+ # Integrate back
268
+ last_price = float(recent[-1])
269
+ for d in fc_diff:
270
+ last_price += d
271
+ sp = (last_price - float(closes[-1])) / float(closes[-1]) * 100
272
+ return sp, "river-snarimax-ar3", f"River SNARIMAX: ar3_coeffs={[round(float(c),4) for c in coeffs]}, sp={sp:.4f}%"
273
+
274
+ # ── GROUP 3: Technical / Structural (N-BEATS, AROpt) ─────────────────────────
275
+ def run_nbeats(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
276
+ n = len(closes)
277
+ if n < 16:
278
+ return 0.0, "nbeats", "Insufficient"
279
+ x = np.arange(min(32, n)); y = closes[-len(x):]
280
+ try:
281
+ poly2 = np.polyfit(x, y, 2)
282
+ x_next = np.arange(len(x), len(x) + horizon)
283
+ trend_fc = np.polyval(poly2, x_next)
284
+ trend_sl = (trend_fc[-1] - float(closes[-1])) / float(closes[-1]) * 100
285
+ except Exception:
286
+ trend_sl = 0.0; trend_fc = np.full(horizon, closes[-1])
287
+ seasonal_sig = 0.0; period = 32.0
288
+ if n >= 32:
289
+ fft = np.fft.rfft(closes[-32:] - np.mean(closes[-32:]))
290
+ dom = np.argmax(np.abs(fft[1:])) + 1
291
+ period = 32 / dom if dom > 0 else 32
292
+ phase = (n % period) / period * 2 * math.pi
293
+ seasonal_sig = math.sin(phase + math.pi / 2)
294
+ residual = (closes[-1] - closes[-5]) / closes[-5] if n >= 5 else 0
295
+ sp = trend_sl * 0.7 + seasonal_sig * 0.03 * 100 + float(residual) * 30
296
+ sp = float(np.clip(sp, -1.2, 1.2))
297
+ return sp, "nbeats-poly-fft", f"N-BEATS: trend={trend_sl:.4f}%, seasonal(p≈{period:.1f})={seasonal_sig:.3f}"
298
 
299
  def run_aropt(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
300
+ n = len(closes); order = min(6, n - 1)
 
301
  if order < 2:
302
+ return 0.0, "aropt", "Insufficient"
303
+ y = closes[order:]; X = np.column_stack([closes[i:n - order + i] for i in range(order)])
 
304
  if len(y) < 2:
305
+ return 0.0, "aropt", "Insufficient pairs"
306
  try:
307
  coeffs, *_ = np.linalg.lstsq(X, y, rcond=None)
308
  except np.linalg.LinAlgError:
309
+ return 0.0, "aropt", "lstsq failed"
310
+ window = list(closes[-order:])
311
  forecast = []
312
  for _ in range(horizon):
313
  nv = float(np.dot(coeffs, window[-order:]))
314
+ forecast.append(nv); window.append(nv)
315
+ sp = (forecast[-1] - float(closes[-1])) / float(closes[-1]) * 100
316
+ return sp, "aropt-ls", f"AR({order}): coeffs[:3]={[round(float(c),4) for c in coeffs[:3]]}"
317
+
318
+ # ── GROUP 4: Macro / Cross-asset (TiDE, Informer-Attn) ───────────────────────
319
+ def build_macro_score(req: OmegaRequest) -> float:
320
+ score = 0.0; count = 0
321
+ if req.fear_greed is not None:
322
+ score += -math.tanh((req.fear_greed - 50) / 25) * 0.12; count += 1
323
+ if req.dxy_change_pct is not None:
324
+ score += math.tanh(-req.dxy_change_pct / 0.5) * 0.18; count += 1
325
+ if req.nasdaq_fut_change_pct is not None:
326
+ score += math.tanh(req.nasdaq_fut_change_pct / 0.5) * 0.15; count += 1
327
+ if req.sentiment_polarity is not None:
328
+ score += math.tanh(req.sentiment_polarity * 2) * 0.12; count += 1
329
+ if req.deribit_pcr is not None:
330
+ # Put/call ratio > 1 = bearish, < 1 = bullish
331
+ score += math.tanh((1 - req.deribit_pcr) * 2) * 0.1; count += 1
332
+ if req.stablecoin_supply_chg is not None:
333
+ score += math.tanh(req.stablecoin_supply_chg / 0.02) * 0.1; count += 1
334
+ if req.chainlink_price is not None and req.strike is not None and req.strike > 0:
335
+ drift = (req.chainlink_price - req.strike) / req.strike
336
+ score += math.tanh(drift / 0.001) * 0.5; count += 1
337
+ return score / max(1, count)
338
+
339
+ def run_tide(closes: np.ndarray, req: OmegaRequest, horizon: int) -> Tuple[float, str, str]:
340
+ n = len(closes)
341
+ if n < 16:
342
+ return 0.0, "tide", "Insufficient"
343
+ sl5 = (closes[-1] - closes[-6]) / closes[-6] if n >= 6 else 0
344
+ sl20 = (closes[-1] - closes[-21]) / closes[-21] if n >= 21 else 0
345
+ e8 = ema(closes[-20:], 8); e20 = ema(closes[-40:], 20)
346
+ ts_signal = sl5 * 0.6 + sl20 * 0.4 + ((e8 - e20) / e20 * 0.3 if e20 != 0 else 0)
347
+ macro = build_macro_score(req)
348
+ # ALSO pull in orderflow for dense encoder
349
+ flow = 0.0; flow_n = 0
350
+ if req.cvd is not None: flow += math.tanh(req.cvd / 50_000_000) * 0.4; flow_n += 1
351
+ if req.ob_imbal is not None: flow += math.tanh(req.ob_imbal * 2) * 0.3; flow_n += 1
352
+ if req.funding is not None: flow += -math.tanh(req.funding * 10000) * 0.3; flow_n += 1
353
+ if flow_n > 0: flow /= flow_n
354
+ combined = ts_signal * 0.45 + macro * 0.30 + flow * 0.25
355
+ sp = math.tanh(combined * 3) * 0.14 * 100
356
+ return sp, "tide-dense-encoder", f"TiDE: ts={ts_signal*100:.4f}%, macro={macro:.4f}, flow={flow:.4f}"
357
+
358
+ def run_informer(closes: np.ndarray, req: OmegaRequest, horizon: int) -> Tuple[float, str, str]:
359
+ """
360
+ Informer ProbSparse attention approximation.
361
+ Uses long-range dependencies (up to 128 candles) + macro covariates.
362
+ Specifically designed to capture LONG-SEQUENCE patterns that short models miss.
363
+ """
364
+ n = len(closes)
365
+ if n < 24:
366
+ return 0.0, "informer", "Insufficient (need 24+)"
367
+ # Multi-scale attention weights: recent candles get exponentially more weight
368
+ window = min(128, n)
369
+ ctx = closes[-window:].astype(float)
370
+ lags = [1, 2, 3, 5, 8, 13, 21] # Fibonacci lags for multi-scale
371
+ attn_signals = []
372
+ for lag in lags:
373
+ if window > lag:
374
+ ret = (ctx[-1] - ctx[-(lag + 1)]) / ctx[-(lag + 1)]
375
+ weight = math.exp(-lag * 0.05) # exponential decay = "sparse attention"
376
+ attn_signals.append(ret * weight)
377
+ ts_attn = sum(attn_signals) / max(1, len(attn_signals))
378
+ # Long-range trend via linear regression on full context
379
+ x = np.arange(len(ctx)); slope_coef = np.polyfit(x, ctx, 1)[0]
380
+ long_sl = slope_coef / ctx[-1] if ctx[-1] != 0 else 0
381
+ # Macro augmentation
382
+ macro = build_macro_score(req)
383
+ polymarket = 0.0
384
+ if req.polymarket_yes is not None:
385
+ polymarket = math.tanh((req.polymarket_yes - 0.5) * 6) * 0.3
386
+ if req.poly_yes_delta_1m is not None:
387
+ polymarket += math.tanh(req.poly_yes_delta_1m * 20) * 0.2
388
+ combined = ts_attn * 100 * 0.40 + long_sl * 100 * 0.25 + macro * 0.20 + polymarket * 0.15
389
+ sp = float(np.clip(combined, -1.5, 1.5))
390
+ return sp, "informer-probsparse", f"Informer: attn={ts_attn*100:.4f}%, lsl={long_sl*100:.4f}%, macro={macro:.4f}"
391
+
392
+ # ── GROUP 5: Probabilistic / Ensemble (MOIRAI, StatsForecast-MSTL) ───────────
393
+ def run_moirai(closes: np.ndarray, horizon: int, req: OmegaRequest) -> Tuple[float, str, str]:
394
+ model = get_moirai()
395
+ if model is not None:
396
+ try:
397
+ ctx = th.tensor(closes[-64:], dtype=th.float32).unsqueeze(0).unsqueeze(-1)
398
+ samples = model.predict(ctx)
399
+ arr = samples.squeeze().numpy()
400
+ if arr.ndim == 1: arr = arr.reshape(1, -1)
401
+ med = float(np.median(arr[:, -1]))
402
+ p10 = float(np.percentile(arr[:, -1], 10))
403
+ p90 = float(np.percentile(arr[:, -1], 90))
404
+ sp = (med - float(closes[-1])) / float(closes[-1]) * 100
405
+ unc = (p90 - p10) / float(closes[-1]) * 100
406
+ macro = build_macro_score(req)
407
+ sp += macro * 0.08 * 100
408
+ return sp, "moirai-salesforce", f"MOIRAI: med={med:.2f}, unc={unc:.4f}%, macro_adj={macro:.4f}"
409
+ except Exception:
410
+ pass
411
+ # Bootstrap fallback with seeded RNG
412
+ seed = _hash_seed(closes)
413
+ rng = np.random.default_rng(seed=seed)
414
+ returns = np.diff(closes) / closes[:-1]
415
+ if len(returns) < 5:
416
+ return 0.0, "moirai-bootstrap", "Insufficient returns"
417
+ samples = []
418
+ for _ in range(200):
419
+ path = float(closes[-1])
420
+ for _ in range(horizon):
421
+ path *= (1 + rng.choice(returns[-50:]))
422
+ samples.append(path)
423
+ med = float(np.median(samples))
424
+ p10 = float(np.percentile(samples, 10))
425
+ p90 = float(np.percentile(samples, 90))
426
+ sp = (med - float(closes[-1])) / float(closes[-1]) * 100
427
+ unc = (p90 - p10) / float(closes[-1]) * 100
428
+ macro = build_macro_score(req)
429
+ sp += macro * 0.06 * 100
430
+ return sp, "moirai-bootstrap", f"MOIRAI boot: med={med:.2f}, unc={unc:.4f}%, ctx={macro:.4f}"
431
+
432
+ def run_statsforecast_mstl(closes: np.ndarray, horizon: int, req: OmegaRequest) -> Tuple[float, str, str]:
433
+ """
434
+ StatsForecast MSTL (Multi-Seasonality Trend decomposition).
435
+ Fits STL-style decomposition then projects each component forward.
436
+ Specifically targets MEAN-REVERSION signals vs momentum.
437
+ """
438
+ n = len(closes)
439
+ if n < 16:
440
+ return 0.0, "statsforecast-mstl", "Insufficient"
441
+ # Trend component: linear regression on last 32 bars
442
+ win = min(32, n)
443
+ x = np.arange(win); y = closes[-win:]
444
+ trend_coef = np.polyfit(x, y, 1)[0]
445
+ trend_sl = trend_coef / closes[-1] if closes[-1] != 0 else 0
446
+ # Seasonal: check for 5-bar and 12-bar cycles
447
+ seasonal = 0.0
448
+ for period in [5, 12]:
449
+ if n >= period * 2:
450
+ cycle = closes[-period * 2:]
451
+ s1 = float(np.mean(cycle[:period])); s2 = float(np.mean(cycle[period:]))
452
+ if s1 != 0: seasonal += (s2 - s1) / s1 * 0.5
453
+ # Residual / mean-reversion signal
454
+ ma10 = float(np.mean(closes[-10:])) if n >= 10 else closes[-1]
455
+ dev = (closes[-1] - ma10) / ma10 if ma10 != 0 else 0
456
+ # Extreme deviation → mean-revert
457
+ mean_rev = -math.tanh(dev * 30) * 0.04
458
+ # Vol regime dampener — in extreme vol, trust price less
459
+ if req.vol_regime == "EXTREME":
460
+ trend_sl *= 0.5
461
+ seasonal *= 0.5
462
+ elif req.vol_regime == "HIGH":
463
+ trend_sl *= 0.75
464
+ combined = trend_sl * 100 * 0.55 + seasonal * 100 * 0.2 + mean_rev * 100 * 0.25
465
+ sp = float(np.clip(combined, -1.5, 1.5))
466
+ rsi_adj = 0.0
467
+ if req.rsi is not None:
468
+ rsi_adj = -math.tanh((req.rsi - 50) / 25) * 0.08 * 100
469
+ sp += rsi_adj
470
+ return sp, "statsforecast-mstl", f"MSTL: trend={trend_sl*100:.4f}%, seasonal={seasonal*100:.4f}%, mean_rev={mean_rev*100:.4f}%"
471
+
472
+ # ── Model registry ────────────────────────────────────────────────────────────
473
+ STATIC_WEIGHTS = {
474
+ "Chronos": 0.14,
475
+ "PatchTST": 0.11,
476
+ "DAG": 0.12,
477
+ "River": 0.10,
478
+ "N-BEATS": 0.10,
479
+ "AROpt": 0.10,
480
+ "TiDE": 0.11,
481
+ "Informer": 0.10,
482
+ "MOIRAI": 0.08,
483
+ "StatsForecast":0.04,
484
+ }
485
+
486
+ # ── Anti-bias: threshold that scales with volatility ─────────────────────────
487
+ def get_threshold(timeframe: str, vol_regime: Optional[str], vol_pct: Optional[float]) -> float:
488
+ base = {"5M": 0.04, "15M": 0.035, "1D": 0.025}.get(timeframe, 0.04)
489
+ # In HIGH/EXTREME vol, widen the neutral zone so models don't snap UP on noise
490
+ if vol_regime in ("HIGH", "EXTREME"):
491
+ base *= 1.5
492
+ if vol_pct is not None and vol_pct > 90:
493
+ base *= 1.3
494
+ return base
495
+
496
+ # ── FastAPI endpoints ─────────────────────────────────────────────────────────
497
  @app.get("/")
498
  def health():
499
  return {
500
+ "ok": True, "chronos": CHRONOS_AVAILABLE, "moirai": MOIRAI_AVAILABLE,
501
+ "version": "15.0.0", "models": list(STATIC_WEIGHTS.keys()),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502
  }
503
 
504
+ @app.post("/omega", response_model=OmegaResponse)
505
+ def omega_forecast(req: OmegaRequest):
506
+ t0 = time.time()
507
+ closes = np.array(req.closes, dtype=np.float64)
508
+ horizon = req.horizon
509
  results: List[ModelResult] = []
510
 
511
+ def add(name: str, group: str, slope_pct: float, note: str, reasoning: str,
512
+ is_avail: bool, threshold: float = 0.012, conf_mult: float = 1.0):
513
+ direction, conf = slope_to_direction(slope_pct, threshold)
514
+ conf = min(95.0, conf * conf_mult)
515
+ results.append(ModelResult(
516
+ name=name, direction=direction, confidence=conf,
517
+ slope_pct=round(slope_pct, 6), available=is_avail,
518
+ note=note, reasoning=reasoning, group=group,
519
+ ))
520
+
521
+ # Model runners — each has a primary signal group
522
+ runners = [
523
+ ("Chronos", "PRICE", lambda: run_chronos(closes, horizon), lambda: run_chronos_fallback(closes, horizon)),
524
+ ("PatchTST", "PRICE", lambda: run_patchtst(closes, horizon), None),
525
+ ("DAG", "ORDERFLOW", lambda: run_dag(closes, req), None),
526
+ ("River", "ORDERFLOW", lambda: run_river_snarimax(closes, horizon), None),
527
+ ("N-BEATS", "TECHNICAL", lambda: run_nbeats(closes, horizon), None),
528
+ ("AROpt", "TECHNICAL", lambda: run_aropt(closes, horizon), None),
529
+ ("TiDE", "MACRO", lambda: run_tide(closes, req, horizon), None),
530
+ ("Informer", "MACRO", lambda: run_informer(closes, req, horizon), None),
531
+ ("MOIRAI", "PROB", lambda: run_moirai(closes, horizon, req), None),
532
+ ("StatsForecast", "PROB", lambda: run_statsforecast_mstl(closes, horizon, req), None),
533
+ ]
534
+
535
+ for name, group, fn, fb in runners:
536
+ try:
537
+ sp, note, rsn = fn()
538
+ add(name, group, sp, note, rsn, True)
539
+ except Exception as e:
540
+ if fb is not None:
541
+ try:
542
+ sp, note, rsn = fb()
543
+ add(name, group, sp, note, rsn, False, conf_mult=0.75)
544
+ continue
545
+ except Exception:
546
+ pass
547
+ add(name, group, 0.0, str(e)[:60], f"Error in {name}: {e}", False)
548
+
549
+ # ── Adaptive weight blending ───────────────────────────────────────────────
550
+ adaptive = req.adaptive_weights or {}
551
+ eff_weights: dict = {}
552
+ for m, sw in STATIC_WEIGHTS.items():
553
+ aw = adaptive.get(m)
554
+ if isinstance(aw, (int, float)) and 0.01 <= aw <= 0.95:
555
+ blend = min(1.0, (adaptive.get("_n_settled", 0) or 0) / 30)
556
+ eff_weights[m] = aw * blend + sw * (1 - blend)
557
+ else:
558
+ eff_weights[m] = sw
559
+ tw = sum(eff_weights.values())
560
+ eff_weights = {k: v / tw for k, v in eff_weights.items()}
561
+
562
+ # ── Anti-bias: compute score per GROUP separately ─────────────────────────
563
+ group_scores: dict = {}
564
+ group_weights: dict = {}
565
  for r in results:
566
+ w = eff_weights.get(r.name, 0.0)
567
+ sign = 1.0 if r.direction == "UP" else (-1.0 if r.direction == "DOWN" else 0.0)
568
+ vs = sign * (r.confidence / 100.0) * w
569
+ group_scores[r.group] = group_scores.get(r.group, 0.0) + vs
570
+ group_weights[r.group] = group_weights.get(r.group, 0.0) + w
571
+
572
+ # Normalize per group to [-1, 1]
573
+ norm_group: dict = {}
574
+ for g in group_scores:
575
+ gw = group_weights.get(g, 1)
576
+ norm_group[g] = group_scores[g] / gw if gw > 0 else 0.0
577
+
578
+ # Anti-bias: if one group >60% of composite weight, cap its influence
579
+ dominant_group = max(group_weights, key=lambda g: group_weights[g])
580
+ dominant_ratio = group_weights[dominant_group] / sum(group_weights.values())
581
+
582
+ # Global composite
583
+ composite = 0.0; total_w = 0.0
584
+ for r in results:
585
+ w = eff_weights.get(r.name, 0.0)
586
+ sign = 1.0 if r.direction == "UP" else (-1.0 if r.direction == "DOWN" else 0.0)
587
+ composite += sign * (r.confidence / 100.0) * w
588
+ total_w += w
589
+ comp_score = composite / total_w if total_w > 0 else 0.0
590
+
591
+ # If one group dominates AND the non-dominant groups disagree → dampen
592
+ anti_bias = False
593
+ non_dom_scores = [v for g, v in norm_group.items() if g != dominant_group]
594
+ if dominant_ratio > 0.6 and non_dom_scores:
595
+ non_dom_avg = sum(non_dom_scores) / len(non_dom_scores)
596
+ # Dominant and non-dominant disagree in sign → shrink toward consensus
597
+ if (comp_score > 0 and non_dom_avg < -0.05) or (comp_score < 0 and non_dom_avg > 0.05):
598
+ comp_score *= 0.6
599
+ anti_bias = True
600
+
601
+ THRESHOLD = get_threshold(req.timeframe, req.vol_regime, req.vol_percentile)
602
  if abs(comp_score) < THRESHOLD:
603
  comp_dir = "NEUTRAL"
604
+ comp_conf = 50.0 + abs(comp_score) / THRESHOLD * 8.0
605
  else:
606
  comp_dir = "UP" if comp_score > 0 else "DOWN"
607
+ comp_conf = min(95.0, 50.0 + abs(comp_score) / 0.25 * 45.0)
608
 
609
  return OmegaResponse(
610
  composite_direction=comp_dir,
 
613
  models=results,
614
  elapsed_ms=int((time.time() - t0) * 1000),
615
  timeframe=req.timeframe,
616
+ anti_bias_applied=anti_bias,
617
+ dominant_group=dominant_group,
618
  )