Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,120 +1,122 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 45 |
-
except ImportError:
|
| 46 |
MOIRAI_AVAILABLE = False
|
| 47 |
-
logger.warning("MOIRAI: not available")
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 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 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
| 81 |
)
|
| 82 |
-
return
|
| 83 |
|
| 84 |
def get_moirai():
|
| 85 |
global _moirai
|
| 86 |
if _moirai is None and MOIRAI_AVAILABLE:
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 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
|
| 101 |
class OmegaRequest(BaseModel):
|
| 102 |
-
closes:
|
| 103 |
-
highs:
|
| 104 |
-
lows:
|
| 105 |
-
volumes:
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
funding:
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
rsi:
|
| 113 |
-
macd:
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 138 |
-
|
| 139 |
if abs(slope_pct) < threshold:
|
| 140 |
-
|
| 141 |
-
|
| 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
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
val = float(arr[0])
|
| 150 |
-
for v in arr[1:]:
|
| 151 |
-
val = alpha * float(v) + (1 - alpha) * val
|
| 152 |
-
return val
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 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 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 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 <
|
| 270 |
-
return 0.0, "dag", "Insufficient
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
try:
|
| 281 |
-
|
| 282 |
except np.linalg.LinAlgError:
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
def run_aropt(closes: np.ndarray, horizon: int) -> Tuple[float, str, str]:
|
| 298 |
-
n
|
| 299 |
-
order = min(6, n - 1)
|
| 300 |
if order < 2:
|
| 301 |
-
return 0.0, "aropt", "Insufficient
|
| 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
|
| 311 |
forecast = []
|
| 312 |
for _ in range(horizon):
|
| 313 |
nv = float(np.dot(coeffs, window[-order:]))
|
| 314 |
-
forecast.append(nv)
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
if not
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
def
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
if not
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
"
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
@app.get("/")
|
| 426 |
def health():
|
| 427 |
return {
|
| 428 |
-
"ok":
|
| 429 |
-
"
|
| 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 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
)
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
for r in results:
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
if abs(comp_score) < THRESHOLD:
|
| 549 |
comp_dir = "NEUTRAL"
|
| 550 |
-
comp_conf = 50.0 + abs(comp_score) / THRESHOLD *
|
| 551 |
else:
|
| 552 |
comp_dir = "UP" if comp_score > 0 else "DOWN"
|
| 553 |
-
comp_conf = min(95.0, 50.0 + abs(comp_score) / 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=
|
|
|
|
| 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 |
)
|