Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,23 @@
|
|
| 1 |
"""
|
| 2 |
-
PolyBloom ML Ensemble Service v14.
|
| 3 |
|
| 4 |
-
FIXES in v14.1:
|
| 5 |
-
1. slope_to_direction: per-
|
| 6 |
-
|
| 7 |
-
This was the root cause of Chronos/PatchTST always showing NEUTRAL
|
| 8 |
|
| 9 |
-
2. add() closure: uses tf_threshold
|
| 10 |
|
| 11 |
-
3.
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
4. run_tabpfn / run_patchtst
|
| 15 |
-
|
|
|
|
| 16 |
|
| 17 |
-
5. Composite NEUTRAL threshold tightened
|
| 18 |
-
not whenever the score is merely small
|
| 19 |
"""
|
| 20 |
import os, time, math
|
| 21 |
from typing import List, Optional, Tuple
|
|
@@ -41,7 +43,7 @@ except Exception:
|
|
| 41 |
CHRONOS_MODEL = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-small")
|
| 42 |
MOIRAI_MODEL = os.environ.get("MOIRAI_MODEL", "Salesforce/moirai-1.1-R-small")
|
| 43 |
|
| 44 |
-
app = FastAPI(title="PolyBloom ML Ensemble v14.
|
| 45 |
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
| 46 |
|
| 47 |
_chronos = None
|
|
@@ -70,38 +72,38 @@ def get_moirai():
|
|
| 70 |
# ── Request / Response models ─────────────────────────────────────────────────
|
| 71 |
|
| 72 |
class OmegaRequest(BaseModel):
|
| 73 |
-
closes:
|
| 74 |
-
highs:
|
| 75 |
-
lows:
|
| 76 |
-
volumes:
|
| 77 |
-
horizon:
|
| 78 |
timeframe: str = Field("5M")
|
| 79 |
-
funding:
|
| 80 |
-
ob_imbal:
|
| 81 |
-
cvd:
|
| 82 |
-
taker_buy_ratio:
|
| 83 |
-
rsi:
|
| 84 |
-
macd:
|
| 85 |
-
ema_align:
|
| 86 |
-
vwap_dev:
|
| 87 |
-
vol_regime:
|
| 88 |
-
spot:
|
| 89 |
-
strike:
|
| 90 |
-
nearest_support:
|
| 91 |
-
nearest_resistance:Optional[float] = None
|
| 92 |
-
market_regime:
|
| 93 |
-
htf_trend_15m:
|
| 94 |
-
htf_trend_1h:
|
| 95 |
-
open_interest:
|
| 96 |
-
ls_ratio:
|
| 97 |
-
fear_greed:
|
| 98 |
-
dxy_change_pct:
|
| 99 |
nasdaq_fut_change_pct: Optional[float] = None
|
| 100 |
-
polymarket_yes:
|
| 101 |
-
chainlink_price:
|
| 102 |
-
sentiment_polarity:Optional[float] = None
|
| 103 |
-
session:
|
| 104 |
-
adaptive_weights:
|
| 105 |
|
| 106 |
class Config:
|
| 107 |
extra = "allow"
|
|
@@ -125,22 +127,21 @@ class OmegaResponse(BaseModel):
|
|
| 125 |
anti_bias_applied: bool
|
| 126 |
|
| 127 |
|
| 128 |
-
# ── FIX 1: Per-timeframe slope thresholds ────────────────────────────────────
|
| 129 |
-
# Old: hardcoded 0.008% for every
|
| 130 |
-
#
|
| 131 |
-
#
|
| 132 |
-
# New: calibrated to actual BTC intraday volatility per timeframe.
|
| 133 |
SLOPE_THRESHOLDS = {
|
| 134 |
-
"5M": 0.003, # $3 move at $100k — realistic 2-candle
|
| 135 |
-
"15M": 0.005, # $5 move —
|
| 136 |
-
"1D": 0.018, # $18 move — daily
|
| 137 |
}
|
| 138 |
|
| 139 |
def slope_to_direction(slope_pct: float, threshold: float = 0.003) -> Tuple[str, float]:
|
| 140 |
-
"""Convert a forecast slope
|
| 141 |
if abs(slope_pct) < threshold:
|
| 142 |
return "NEUTRAL", 50.0
|
| 143 |
-
#
|
| 144 |
conf = min(95.0, 50.0 + (abs(slope_pct) / threshold - 1.0) * 12.0)
|
| 145 |
return ("UP" if slope_pct > 0 else "DOWN"), conf
|
| 146 |
|
|
@@ -158,52 +159,78 @@ def ema(arr: np.ndarray, period: int) -> float:
|
|
| 158 |
|
| 159 |
|
| 160 |
# ── Helper: Context score from exogenous signals ──────────────────────────────
|
| 161 |
-
# Used by TiDE, MOIRAI, and
|
| 162 |
-
# Returns a score in roughly -1..+1 where positive = bullish context.
|
| 163 |
|
| 164 |
def build_context_score(req: OmegaRequest) -> float:
|
| 165 |
score = 0.0
|
| 166 |
count = 0
|
| 167 |
if req.funding is not None:
|
| 168 |
-
|
| 169 |
-
score += -math.tanh(req.funding * 10000) * 0.3
|
| 170 |
-
count += 1
|
| 171 |
if req.cvd is not None:
|
| 172 |
-
score += math.tanh(req.cvd / 50_000_000) * 0.4
|
| 173 |
-
count += 1
|
| 174 |
if req.ob_imbal is not None:
|
| 175 |
-
score += math.tanh(req.ob_imbal * 2) * 0.3
|
| 176 |
-
count += 1
|
| 177 |
if req.taker_buy_ratio is not None:
|
| 178 |
-
score += math.tanh((req.taker_buy_ratio - 0.5) * 6) * 0.25
|
| 179 |
-
count += 1
|
| 180 |
if req.rsi is not None:
|
| 181 |
-
|
| 182 |
-
score += -math.tanh((req.rsi - 50) / 20) * 0.2
|
| 183 |
-
count += 1
|
| 184 |
if req.sentiment_polarity is not None:
|
| 185 |
-
score += math.tanh(req.sentiment_polarity * 2) * 0.15
|
| 186 |
-
count += 1
|
| 187 |
if req.fear_greed is not None:
|
| 188 |
-
score += -math.tanh((req.fear_greed - 50) / 25) * 0.1
|
| 189 |
-
count += 1
|
| 190 |
if req.dxy_change_pct is not None:
|
| 191 |
-
score += math.tanh(-req.dxy_change_pct / 0.5) * 0.15
|
| 192 |
-
count += 1
|
| 193 |
if req.nasdaq_fut_change_pct is not None:
|
| 194 |
-
score += math.tanh(req.nasdaq_fut_change_pct / 0.5) * 0.1
|
| 195 |
-
count += 1
|
| 196 |
if req.chainlink_price is not None and req.strike is not None and req.strike > 0:
|
| 197 |
drift = (req.chainlink_price - req.strike) / req.strike
|
| 198 |
-
score += math.tanh(drift / 0.001) * 0.5
|
| 199 |
-
count += 1
|
| 200 |
return score / max(1, count)
|
| 201 |
|
| 202 |
|
| 203 |
-
# ──
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
def run_chronos(closes, horizon):
|
| 206 |
-
"""Real Chronos T5 inference via HuggingFace."""
|
| 207 |
pipe = get_chronos()
|
| 208 |
if pipe is None:
|
| 209 |
raise RuntimeError("not loaded")
|
|
@@ -218,19 +245,11 @@ def run_chronos(closes, horizon):
|
|
| 218 |
f"Chronos T5: median={float(median[-1]):.2f}, uncertainty={uncertainty:.4f}%."
|
| 219 |
|
| 220 |
|
| 221 |
-
def run_chronos_fallback(closes, horizon
|
| 222 |
-
"""
|
| 223 |
-
Holt-Winters fallback when Chronos model is unavailable.
|
| 224 |
-
|
| 225 |
-
FIX v14.1: Blends in RSI mean-reversion + funding fade to prevent
|
| 226 |
-
pure price-trend UP bias. Without this, the fallback always trended
|
| 227 |
-
UP whenever BTC had a positive recent slope (which is ~60% of sessions).
|
| 228 |
-
"""
|
| 229 |
n = len(closes)
|
| 230 |
if n < 4:
|
| 231 |
return 0.0, "holt-winters-fallback", "Insufficient data"
|
| 232 |
-
|
| 233 |
-
# Holt-Winters double exponential smoothing
|
| 234 |
alpha, beta = 0.3, 0.2
|
| 235 |
level = float(closes[0])
|
| 236 |
trend = float(closes[1] - closes[0]) if n > 1 else 0.0
|
|
@@ -238,122 +257,46 @@ def run_chronos_fallback(closes, horizon, req=None):
|
|
| 238 |
prev_level = level
|
| 239 |
level = alpha * float(price) + (1 - alpha) * (level + trend)
|
| 240 |
trend = beta * (level - prev_level) + (1 - beta) * trend
|
| 241 |
-
fval
|
| 242 |
slope_pct = (fval - float(closes[-1])) / float(closes[-1]) * 100
|
| 243 |
-
|
| 244 |
-
# FIX: Blend in context signals so fallback can output DOWN
|
| 245 |
-
if req is not None:
|
| 246 |
-
funding = req.funding if req.funding is not None else 0.0
|
| 247 |
-
rsi = req.rsi if req.rsi is not None else 50.0
|
| 248 |
-
|
| 249 |
-
# Funding fade: high positive funding = longs crowded = bearish adj
|
| 250 |
-
if funding > 0.04: funding_adj = -0.020
|
| 251 |
-
elif funding > 0.02: funding_adj = -0.010
|
| 252 |
-
elif funding < -0.025: funding_adj = 0.015
|
| 253 |
-
elif funding < -0.01: funding_adj = 0.007
|
| 254 |
-
else: funding_adj = 0.0
|
| 255 |
-
|
| 256 |
-
# RSI mean-reversion: overbought = bearish adj
|
| 257 |
-
if rsi > 72: rsi_adj = -0.012
|
| 258 |
-
elif rsi > 65: rsi_adj = -0.006
|
| 259 |
-
elif rsi < 28: rsi_adj = 0.012
|
| 260 |
-
elif rsi < 35: rsi_adj = 0.006
|
| 261 |
-
else: rsi_adj = 0.0
|
| 262 |
-
|
| 263 |
-
# Blend: 75% Holt-Winters price trend, 25% context adjustment
|
| 264 |
-
ctx_adj = (funding_adj + rsi_adj) * 100
|
| 265 |
-
slope_pct = slope_pct * 0.75 + ctx_adj * 0.25
|
| 266 |
-
|
| 267 |
return slope_pct, "holt-winters-fallback", \
|
| 268 |
f"Holt-Winters: level={level:.2f}, trend={trend:.2f}/candle, slope={slope_pct:.4f}%."
|
| 269 |
|
| 270 |
|
| 271 |
-
def run_tabpfn(closes, horizon
|
| 272 |
-
"""
|
| 273 |
-
TabPFN numeric approximation.
|
| 274 |
-
|
| 275 |
-
FIX v14.1: Added RSI, funding, and CVD context so TabPFN can output
|
| 276 |
-
DOWN when price is flat but orderflow is bearish. Previously only used
|
| 277 |
-
price returns which biased toward UP in trending markets.
|
| 278 |
-
"""
|
| 279 |
n = len(closes)
|
| 280 |
if n < 8:
|
| 281 |
return 0.0, "tabpfn", "Insufficient data"
|
| 282 |
-
last
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
ret3 = (closes[-1] - closes[-4]) / closes[-4] if n >= 4 else 0.0
|
| 287 |
-
ret8 = (closes[-1] - closes[-9]) / closes[-9] if n >= 9 else 0.0
|
| 288 |
-
|
| 289 |
-
# EMA signal
|
| 290 |
ema8 = float(np.mean(closes[-8:]))
|
| 291 |
ema16 = float(np.mean(closes[-16:])) if n >= 16 else ema8
|
| 292 |
ema_sig = (ema8 - ema16) / ema16 if ema16 != 0 else 0.0
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
# Base price score
|
| 297 |
-
price_score = ret1 * 0.40 + ret3 * 0.30 + ret8 * 0.20 + ema_sig * 0.10 - vol * 0.05
|
| 298 |
-
|
| 299 |
-
# FIX: Context adjustment from exogenous signals
|
| 300 |
-
ctx_adj = 0.0
|
| 301 |
-
ctx_n = 0
|
| 302 |
-
if req is not None:
|
| 303 |
-
if req.funding is not None:
|
| 304 |
-
# High funding = crowded longs = fade UP
|
| 305 |
-
ctx_adj += -math.tanh(req.funding * 8000) * 0.3
|
| 306 |
-
ctx_n += 1
|
| 307 |
-
if req.rsi is not None:
|
| 308 |
-
# RSI overbought = mean-reversion bias
|
| 309 |
-
ctx_adj += -math.tanh((req.rsi - 50) / 22) * 0.25
|
| 310 |
-
ctx_n += 1
|
| 311 |
-
if req.cvd is not None:
|
| 312 |
-
ctx_adj += math.tanh(req.cvd / 40_000_000) * 0.2
|
| 313 |
-
ctx_n += 1
|
| 314 |
-
if ctx_n > 0:
|
| 315 |
-
ctx_adj /= ctx_n
|
| 316 |
-
|
| 317 |
-
# Blend: 70% price, 30% context
|
| 318 |
-
combined = price_score * 0.70 + ctx_adj * 0.30
|
| 319 |
-
slope_pct = combined * horizon * 100
|
| 320 |
-
|
| 321 |
-
ctx_note = f", ctx_adj={ctx_adj:.4f}" if ctx_n > 0 else ""
|
| 322 |
return slope_pct, "tabpfn-numeric", \
|
| 323 |
-
f"TabPFN: ret1={ret1*100:.4f}%, ret3={ret3*100:.4f}%, ema_sig={ema_sig*100:.4f}%, vol={vol*100:.3f}%
|
| 324 |
|
| 325 |
|
| 326 |
def run_dag(closes, req):
|
| 327 |
-
"""DAG Granger-causality approximation — uses exogenous signals heavily."""
|
| 328 |
n = len(closes)
|
| 329 |
if n < 8:
|
| 330 |
return 0.0, "dag", "Insufficient"
|
| 331 |
-
|
| 332 |
price_signal = 0.0
|
| 333 |
for lag in [1, 2, 3]:
|
| 334 |
if n > lag:
|
| 335 |
price_signal += (closes[-1] - closes[-(lag+1)]) / closes[-(lag+1)] * (0.5 ** lag)
|
| 336 |
-
|
| 337 |
-
exog =
|
| 338 |
-
|
| 339 |
-
if req.
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
if
|
| 343 |
-
exog += math.tanh(req.cvd / 30_000_000) * 0.4
|
| 344 |
-
exog_n += 1
|
| 345 |
-
if req.ob_imbal is not None:
|
| 346 |
-
exog += math.tanh(req.ob_imbal * 2) * 0.3
|
| 347 |
-
exog_n += 1
|
| 348 |
-
if req.taker_buy_ratio is not None:
|
| 349 |
-
exog += math.tanh((req.taker_buy_ratio - 0.5) * 6) * 0.2
|
| 350 |
-
exog_n += 1
|
| 351 |
-
if req.rsi is not None:
|
| 352 |
-
exog += -math.tanh((req.rsi - 50) / 20) * 0.15
|
| 353 |
-
exog_n += 1
|
| 354 |
-
if exog_n > 0:
|
| 355 |
-
exog /= exog_n
|
| 356 |
-
|
| 357 |
combined = price_signal * 0.6 + exog * 0.4
|
| 358 |
slope_pct = math.tanh(combined) * 0.15 * 100
|
| 359 |
return slope_pct, "dag-granger", \
|
|
@@ -361,7 +304,6 @@ def run_dag(closes, req):
|
|
| 361 |
|
| 362 |
|
| 363 |
def run_aropt(closes, horizon):
|
| 364 |
-
"""Autoregressive model via least-squares fitting."""
|
| 365 |
n = len(closes)
|
| 366 |
order = min(6, n - 1)
|
| 367 |
if order < 2:
|
|
@@ -378,66 +320,36 @@ def run_aropt(closes, horizon):
|
|
| 378 |
forecast = []
|
| 379 |
for _ in range(horizon):
|
| 380 |
nv = float(np.dot(coeffs, window[-order:]))
|
| 381 |
-
forecast.append(nv)
|
| 382 |
-
window.append(nv)
|
| 383 |
slope_pct = (forecast[-1] - float(closes[-1])) / float(closes[-1]) * 100
|
| 384 |
return slope_pct, "aropt-ls", \
|
| 385 |
f"AR({order}) lstsq: coeffs[:3]={[round(float(c),4) for c in coeffs[:3]]}, slope={slope_pct:.4f}%."
|
| 386 |
|
| 387 |
|
| 388 |
-
def run_patchtst(closes, horizon
|
| 389 |
-
"""
|
| 390 |
-
PatchTST numeric approximation.
|
| 391 |
-
|
| 392 |
-
FIX v14.1: Added funding fade + RSI context so PatchTST can output DOWN.
|
| 393 |
-
Previously relied only on patch-weighted returns which bias UP in uptrends.
|
| 394 |
-
"""
|
| 395 |
n = len(closes)
|
| 396 |
patch_size = 8
|
| 397 |
n_patches = n // patch_size
|
| 398 |
if n_patches < 2:
|
| 399 |
return 0.0, "patchtst", "Insufficient"
|
| 400 |
-
|
| 401 |
patches = []
|
| 402 |
for i in range(n_patches):
|
| 403 |
seg = closes[i * patch_size:(i + 1) * patch_size]
|
| 404 |
pr = (seg[-1] - seg[0]) / seg[0] if seg[0] != 0 else 0.0
|
| 405 |
pv = float(np.std(seg)) / float(np.mean(seg)) if np.mean(seg) != 0 else 0.0
|
| 406 |
patches.append((pr, pv))
|
| 407 |
-
|
| 408 |
raw_weights = np.array([math.exp(0.4 * i) for i in range(len(patches))])
|
| 409 |
att = raw_weights / raw_weights.sum()
|
| 410 |
weighted_return = sum(p[0] * w for p, w in zip(patches, att))
|
| 411 |
mean_vol = np.mean([p[1] for p in patches[-3:]])
|
| 412 |
vol_penalty = min(0.5, mean_vol * 10)
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
# FIX: Context adjustment — funding fade + RSI overbought
|
| 416 |
-
ctx_adj = 0.0
|
| 417 |
-
ctx_n = 0
|
| 418 |
-
if req is not None:
|
| 419 |
-
if req.funding is not None:
|
| 420 |
-
ctx_adj += -math.tanh(req.funding * 9000) * 0.35
|
| 421 |
-
ctx_n += 1
|
| 422 |
-
if req.rsi is not None:
|
| 423 |
-
ctx_adj += -math.tanh((req.rsi - 50) / 20) * 0.30
|
| 424 |
-
ctx_n += 1
|
| 425 |
-
if req.cvd is not None:
|
| 426 |
-
ctx_adj += math.tanh(req.cvd / 35_000_000) * 0.20
|
| 427 |
-
ctx_n += 1
|
| 428 |
-
if ctx_n > 0:
|
| 429 |
-
ctx_adj /= ctx_n
|
| 430 |
-
|
| 431 |
-
# Blend: 72% price patches, 28% context
|
| 432 |
-
slope_pct = price_slope * 0.72 + (ctx_adj * 100) * 0.28
|
| 433 |
-
|
| 434 |
-
ctx_note = f", ctx_adj={ctx_adj:.4f}" if ctx_n > 0 else ""
|
| 435 |
return slope_pct, "patchtst-numeric", \
|
| 436 |
-
f"PatchTST: {n_patches} patches, weighted_ret={weighted_return*100:.4f}%, vol_penalty={vol_penalty:.3f}
|
| 437 |
|
| 438 |
|
| 439 |
def run_tide(closes, req, horizon):
|
| 440 |
-
"""TiDE — time-series dense encoder, blends price trend + context signals."""
|
| 441 |
n = len(closes)
|
| 442 |
if n < 16:
|
| 443 |
return 0.0, "tide", "Insufficient"
|
|
@@ -454,26 +366,22 @@ def run_tide(closes, req, horizon):
|
|
| 454 |
|
| 455 |
|
| 456 |
def run_moirai(closes, horizon, req):
|
| 457 |
-
"""MOIRAI — Salesforce probabilistic forecaster with bootstrap fallback."""
|
| 458 |
model = get_moirai()
|
| 459 |
if model is not None:
|
| 460 |
try:
|
| 461 |
ctx = th.tensor(closes[-64:], dtype=th.float32).unsqueeze(0).unsqueeze(-1)
|
| 462 |
samples = model.predict(ctx)
|
| 463 |
arr = samples.squeeze().numpy()
|
| 464 |
-
if arr.ndim == 1:
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
p90 = float(np.percentile(arr[:, -1], 90))
|
| 469 |
slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
|
| 470 |
uncertainty = (p90 - p10) / float(closes[-1]) * 100
|
| 471 |
return slope_pct, "moirai-salesforce", \
|
| 472 |
f"MOIRAI: median={median:.2f}, uncertainty={uncertainty:.4f}%."
|
| 473 |
except Exception:
|
| 474 |
pass
|
| 475 |
-
|
| 476 |
-
# Bootstrap fallback
|
| 477 |
n = len(closes)
|
| 478 |
returns = np.diff(closes) / closes[:-1]
|
| 479 |
if len(returns) < 5:
|
|
@@ -485,9 +393,9 @@ def run_moirai(closes, horizon, req):
|
|
| 485 |
for _ in range(horizon):
|
| 486 |
path *= (1 + rng.choice(returns[-50:]))
|
| 487 |
samples.append(path)
|
| 488 |
-
median
|
| 489 |
-
p10
|
| 490 |
-
p90
|
| 491 |
slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
|
| 492 |
uncertainty = (p90 - p10) / float(closes[-1]) * 100
|
| 493 |
ctx_score = build_context_score(req)
|
|
@@ -497,7 +405,6 @@ def run_moirai(closes, horizon, req):
|
|
| 497 |
|
| 498 |
|
| 499 |
def run_nbeats(closes, horizon):
|
| 500 |
-
"""N-BEATS: polynomial trend + FFT seasonal + residual momentum."""
|
| 501 |
n = len(closes)
|
| 502 |
if n < 16:
|
| 503 |
return 0.0, "nbeats", "Insufficient"
|
|
@@ -511,17 +418,14 @@ def run_nbeats(closes, horizon):
|
|
| 511 |
except Exception:
|
| 512 |
trend_slope = 0.0
|
| 513 |
trend_forecast = np.full(horizon, closes[-1])
|
| 514 |
-
|
| 515 |
if n >= 32:
|
| 516 |
-
fft
|
| 517 |
-
dominant_freq
|
| 518 |
-
period
|
| 519 |
-
phase
|
| 520 |
seasonal_signal = math.sin(phase + math.pi / 2)
|
| 521 |
else:
|
| 522 |
-
seasonal_signal = 0.0
|
| 523 |
-
period = 32.0
|
| 524 |
-
|
| 525 |
residual = (closes[-1] - closes[-5]) / closes[-5] if n >= 5 else 0.0
|
| 526 |
slope_pct = trend_slope * 0.7 + seasonal_signal * 0.03 * 100 + float(residual) * 30
|
| 527 |
slope_pct = float(np.clip(slope_pct, -1.0, 1.0))
|
|
@@ -551,7 +455,7 @@ def health():
|
|
| 551 |
"ok": True,
|
| 552 |
"chronos": CHRONOS_AVAILABLE,
|
| 553 |
"moirai": MOIRAI_AVAILABLE,
|
| 554 |
-
"version": "14.
|
| 555 |
"models": list(STATIC_WEIGHTS.keys()),
|
| 556 |
}
|
| 557 |
|
|
@@ -563,32 +467,38 @@ def omega_forecast(req: OmegaRequest):
|
|
| 563 |
horizon = req.horizon
|
| 564 |
results: List[ModelResult] = []
|
| 565 |
|
| 566 |
-
# FIX 2:
|
| 567 |
tf_threshold = SLOPE_THRESHOLDS.get(req.timeframe, 0.003)
|
| 568 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 569 |
def add(name, slope_pct, note, reasoning, is_avail, threshold=None, conf_mult=1.0):
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
|
|
|
|
|
|
|
|
|
| 574 |
results.append(ModelResult(
|
| 575 |
name=name, direction=direction, confidence=conf,
|
| 576 |
-
slope_pct=round(
|
| 577 |
-
note=note, reasoning=reasoning,
|
| 578 |
))
|
| 579 |
|
| 580 |
-
# FIX 3: Pass req into tabpfn, patchtst, and chronos fallback so they
|
| 581 |
-
# can use RSI/funding/CVD context to output DOWN when appropriate
|
| 582 |
runners = [
|
| 583 |
("Chronos", lambda: run_chronos(closes, horizon),
|
| 584 |
-
lambda: run_chronos_fallback(closes, horizon
|
| 585 |
-
("TabPFN-TS", lambda: run_tabpfn(closes, horizon
|
| 586 |
-
("DAG", lambda: run_dag(closes, req),
|
| 587 |
-
("AROpt", lambda: run_aropt(closes, horizon),
|
| 588 |
-
("PatchTST", lambda: run_patchtst(closes, horizon
|
| 589 |
-
("TiDE", lambda: run_tide(closes, req, horizon),
|
| 590 |
-
("MOIRAI", lambda: run_moirai(closes, horizon, req),
|
| 591 |
-
("N-BEATS", lambda: run_nbeats(closes, horizon),
|
| 592 |
]
|
| 593 |
|
| 594 |
for name, fn, fb in runners:
|
|
@@ -606,7 +516,7 @@ def omega_forecast(req: OmegaRequest):
|
|
| 606 |
add(name, 0.0, str(e)[:60], f"Error in {name}", False)
|
| 607 |
|
| 608 |
# ── Adaptive weight blending ──────────────────────────────────────────────
|
| 609 |
-
adaptive
|
| 610 |
eff_weights = {}
|
| 611 |
for m, sw in STATIC_WEIGHTS.items():
|
| 612 |
aw = adaptive.get(m)
|
|
@@ -629,15 +539,9 @@ def omega_forecast(req: OmegaRequest):
|
|
| 629 |
total_weight += w
|
| 630 |
comp_score = composite / total_weight if total_weight > 0 else 0.0
|
| 631 |
|
| 632 |
-
# ── Composite direction
|
| 633 |
-
#
|
| 634 |
-
|
| 635 |
-
# New: consistent with how individual models are thresholded.
|
| 636 |
-
COMPOSITE_THRESHOLD = {
|
| 637 |
-
"5M": 0.018, # tighter — 5M signals are higher frequency
|
| 638 |
-
"15M": 0.015,
|
| 639 |
-
"1D": 0.012,
|
| 640 |
-
}.get(req.timeframe, 0.018)
|
| 641 |
|
| 642 |
if abs(comp_score) < COMPOSITE_THRESHOLD:
|
| 643 |
comp_dir = "NEUTRAL"
|
|
|
|
| 1 |
"""
|
| 2 |
+
PolyBloom ML Ensemble Service v14.2 — OMEGA COUNCIL (8 Models)
|
| 3 |
|
| 4 |
+
FIXES in v14.2 (reviewer-corrected from v14.1):
|
| 5 |
+
1. slope_to_direction: per-TF thresholds (5M=0.003, 15M=0.005, 1D=0.018)
|
| 6 |
+
Root cause of Chronos/PatchTST always-NEUTRAL.
|
|
|
|
| 7 |
|
| 8 |
+
2. add() closure: uses tf_threshold, not hardcoded 0.008.
|
| 9 |
|
| 10 |
+
3. Reviewer fix #4: Instead of patching each fallback individually, the
|
| 11 |
+
funding/RSI nudge is applied as a final context_nudge() pass inside
|
| 12 |
+
omega_forecast() AFTER all models have run. This means every model —
|
| 13 |
+
primary AND fallback — benefits uniformly. Cleaner than threading req
|
| 14 |
+
into each individual fallback.
|
| 15 |
|
| 16 |
+
4. run_tabpfn / run_patchtst / run_chronos_fallback: keep price-only logic
|
| 17 |
+
(no RSI/funding injected into model internals — preserves independence).
|
| 18 |
+
Context correction happens at the endpoint level via context_nudge().
|
| 19 |
|
| 20 |
+
5. Composite NEUTRAL threshold tightened per-TF.
|
|
|
|
| 21 |
"""
|
| 22 |
import os, time, math
|
| 23 |
from typing import List, Optional, Tuple
|
|
|
|
| 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 v14.2", version="14.2.0")
|
| 47 |
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
| 48 |
|
| 49 |
_chronos = None
|
|
|
|
| 72 |
# ── Request / Response models ─────────────────────────────────────────────────
|
| 73 |
|
| 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 |
+
spot: Optional[float] = None
|
| 91 |
+
strike: Optional[float] = None
|
| 92 |
+
nearest_support: Optional[float] = None
|
| 93 |
+
nearest_resistance: Optional[float] = None
|
| 94 |
+
market_regime: Optional[str] = None
|
| 95 |
+
htf_trend_15m: Optional[str] = None
|
| 96 |
+
htf_trend_1h: Optional[str] = None
|
| 97 |
+
open_interest: Optional[float] = None
|
| 98 |
+
ls_ratio: Optional[float] = None
|
| 99 |
+
fear_greed: Optional[float] = None
|
| 100 |
+
dxy_change_pct: Optional[float] = None
|
| 101 |
nasdaq_fut_change_pct: Optional[float] = None
|
| 102 |
+
polymarket_yes: Optional[float] = None
|
| 103 |
+
chainlink_price: Optional[float] = None
|
| 104 |
+
sentiment_polarity: Optional[float] = None
|
| 105 |
+
session: Optional[str] = None
|
| 106 |
+
adaptive_weights: Optional[dict] = None
|
| 107 |
|
| 108 |
class Config:
|
| 109 |
extra = "allow"
|
|
|
|
| 127 |
anti_bias_applied: bool
|
| 128 |
|
| 129 |
|
| 130 |
+
# ── FIX 1: Per-timeframe slope thresholds ─────────────────────────────────────
|
| 131 |
+
# Old: hardcoded 0.008% for every TF — caused Chronos NEUTRAL ~65% of runs.
|
| 132 |
+
# Chronos T5 median forecast moves ~$3–8 over 2 5M candles = 0.003–0.008% at $100k.
|
| 133 |
+
# The hardcoded threshold sat right at the top of Chronos's natural output range.
|
|
|
|
| 134 |
SLOPE_THRESHOLDS = {
|
| 135 |
+
"5M": 0.003, # $3 move at $100k — realistic 2-candle 5M forecast
|
| 136 |
+
"15M": 0.005, # $5 move — 15M window is slightly wider
|
| 137 |
+
"1D": 0.018, # $18 move — daily forecasts have much more range
|
| 138 |
}
|
| 139 |
|
| 140 |
def slope_to_direction(slope_pct: float, threshold: float = 0.003) -> Tuple[str, float]:
|
| 141 |
+
"""Convert a forecast slope % to direction + confidence."""
|
| 142 |
if abs(slope_pct) < threshold:
|
| 143 |
return "NEUTRAL", 50.0
|
| 144 |
+
# Steeper confidence scaling: at 2× threshold confidence = 62, at 5× = 98
|
| 145 |
conf = min(95.0, 50.0 + (abs(slope_pct) / threshold - 1.0) * 12.0)
|
| 146 |
return ("UP" if slope_pct > 0 else "DOWN"), conf
|
| 147 |
|
|
|
|
| 159 |
|
| 160 |
|
| 161 |
# ── Helper: Context score from exogenous signals ──────────────────────────────
|
| 162 |
+
# Used by TiDE, MOIRAI, and the endpoint-level context_nudge.
|
|
|
|
| 163 |
|
| 164 |
def build_context_score(req: OmegaRequest) -> float:
|
| 165 |
score = 0.0
|
| 166 |
count = 0
|
| 167 |
if req.funding is not None:
|
| 168 |
+
score += -math.tanh(req.funding * 10000) * 0.3; count += 1
|
|
|
|
|
|
|
| 169 |
if req.cvd is not None:
|
| 170 |
+
score += math.tanh(req.cvd / 50_000_000) * 0.4; count += 1
|
|
|
|
| 171 |
if req.ob_imbal is not None:
|
| 172 |
+
score += math.tanh(req.ob_imbal * 2) * 0.3; count += 1
|
|
|
|
| 173 |
if req.taker_buy_ratio is not None:
|
| 174 |
+
score += math.tanh((req.taker_buy_ratio - 0.5) * 6) * 0.25; count += 1
|
|
|
|
| 175 |
if req.rsi is not None:
|
| 176 |
+
score += -math.tanh((req.rsi - 50) / 20) * 0.2; count += 1
|
|
|
|
|
|
|
| 177 |
if req.sentiment_polarity is not None:
|
| 178 |
+
score += math.tanh(req.sentiment_polarity * 2) * 0.15; count += 1
|
|
|
|
| 179 |
if req.fear_greed is not None:
|
| 180 |
+
score += -math.tanh((req.fear_greed - 50) / 25) * 0.1; count += 1
|
|
|
|
| 181 |
if req.dxy_change_pct is not None:
|
| 182 |
+
score += math.tanh(-req.dxy_change_pct / 0.5) * 0.15; count += 1
|
|
|
|
| 183 |
if req.nasdaq_fut_change_pct is not None:
|
| 184 |
+
score += math.tanh(req.nasdaq_fut_change_pct / 0.5) * 0.1; count += 1
|
|
|
|
| 185 |
if req.chainlink_price is not None and req.strike is not None and req.strike > 0:
|
| 186 |
drift = (req.chainlink_price - req.strike) / req.strike
|
| 187 |
+
score += math.tanh(drift / 0.001) * 0.5; count += 1
|
|
|
|
| 188 |
return score / max(1, count)
|
| 189 |
|
| 190 |
|
| 191 |
+
# ── FIX (reviewer #4): Endpoint-level context nudge ──────────────────────────
|
| 192 |
+
# Instead of injecting RSI/funding into each model's internals (which would
|
| 193 |
+
# destroy their independence as separate "lenses"), we apply a small uniform
|
| 194 |
+
# nudge to each model's slope_pct AFTER all models have run.
|
| 195 |
+
#
|
| 196 |
+
# This is conceptually cleaner: price-structure models (Chronos, PatchTST)
|
| 197 |
+
# stay price-only. The context correction is applied once at the ensemble layer.
|
| 198 |
+
#
|
| 199 |
+
# Nudge magnitude is intentionally small (max ±0.008%) so it can tip a
|
| 200 |
+
# near-threshold model from NEUTRAL to UP/DOWN but cannot reverse a model
|
| 201 |
+
# that is already confident in a direction.
|
| 202 |
+
|
| 203 |
+
def compute_context_nudge(req: OmegaRequest, tf: str) -> float:
|
| 204 |
+
"""
|
| 205 |
+
Returns a slope_pct adjustment (typically -0.006 to +0.006) based on
|
| 206 |
+
funding rate and RSI mean-reversion signals.
|
| 207 |
+
Positive = nudge toward UP, Negative = nudge toward DOWN.
|
| 208 |
+
"""
|
| 209 |
+
nudge = 0.0
|
| 210 |
+
|
| 211 |
+
# Funding fade: high positive funding = crowded longs = bearish nudge
|
| 212 |
+
if req.funding is not None:
|
| 213 |
+
fp = req.funding * 100 # convert to percent
|
| 214 |
+
if fp > 0.04: nudge -= 0.006
|
| 215 |
+
elif fp > 0.02: nudge -= 0.003
|
| 216 |
+
elif fp < -0.025: nudge += 0.005
|
| 217 |
+
elif fp < -0.01: nudge += 0.002
|
| 218 |
+
|
| 219 |
+
# RSI mean-reversion: overbought = bearish nudge, oversold = bullish
|
| 220 |
+
if req.rsi is not None:
|
| 221 |
+
if req.rsi > 72: nudge -= 0.005
|
| 222 |
+
elif req.rsi > 65: nudge -= 0.002
|
| 223 |
+
elif req.rsi < 28: nudge += 0.005
|
| 224 |
+
elif req.rsi < 35: nudge += 0.002
|
| 225 |
+
|
| 226 |
+
# Scale nudge by timeframe (larger moves needed for 15M/1D to matter)
|
| 227 |
+
tf_scale = {"5M": 1.0, "15M": 1.4, "1D": 3.0}.get(tf, 1.0)
|
| 228 |
+
return nudge * tf_scale
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# ── Model runners (price-structure models stay price-only) ────────────────────
|
| 232 |
|
| 233 |
def run_chronos(closes, horizon):
|
|
|
|
| 234 |
pipe = get_chronos()
|
| 235 |
if pipe is None:
|
| 236 |
raise RuntimeError("not loaded")
|
|
|
|
| 245 |
f"Chronos T5: median={float(median[-1]):.2f}, uncertainty={uncertainty:.4f}%."
|
| 246 |
|
| 247 |
|
| 248 |
+
def run_chronos_fallback(closes, horizon):
|
| 249 |
+
"""Holt-Winters fallback — price-only, context nudge applied at endpoint level."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
n = len(closes)
|
| 251 |
if n < 4:
|
| 252 |
return 0.0, "holt-winters-fallback", "Insufficient data"
|
|
|
|
|
|
|
| 253 |
alpha, beta = 0.3, 0.2
|
| 254 |
level = float(closes[0])
|
| 255 |
trend = float(closes[1] - closes[0]) if n > 1 else 0.0
|
|
|
|
| 257 |
prev_level = level
|
| 258 |
level = alpha * float(price) + (1 - alpha) * (level + trend)
|
| 259 |
trend = beta * (level - prev_level) + (1 - beta) * trend
|
| 260 |
+
fval = level + trend * horizon
|
| 261 |
slope_pct = (fval - float(closes[-1])) / float(closes[-1]) * 100
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
return slope_pct, "holt-winters-fallback", \
|
| 263 |
f"Holt-Winters: level={level:.2f}, trend={trend:.2f}/candle, slope={slope_pct:.4f}%."
|
| 264 |
|
| 265 |
|
| 266 |
+
def run_tabpfn(closes, horizon):
|
| 267 |
+
"""TabPFN numeric ��� price-only. Context nudge applied at endpoint level."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
n = len(closes)
|
| 269 |
if n < 8:
|
| 270 |
return 0.0, "tabpfn", "Insufficient data"
|
| 271 |
+
last = float(closes[-1])
|
| 272 |
+
ret1 = (closes[-1] - closes[-2]) / closes[-2] if n >= 2 else 0.0
|
| 273 |
+
ret3 = (closes[-1] - closes[-4]) / closes[-4] if n >= 4 else 0.0
|
| 274 |
+
ret8 = (closes[-1] - closes[-9]) / closes[-9] if n >= 9 else 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
ema8 = float(np.mean(closes[-8:]))
|
| 276 |
ema16 = float(np.mean(closes[-16:])) if n >= 16 else ema8
|
| 277 |
ema_sig = (ema8 - ema16) / ema16 if ema16 != 0 else 0.0
|
| 278 |
+
vol = float(np.std(closes[-8:])) / last if last != 0 else 0.0
|
| 279 |
+
score = ret1 * 0.40 + ret3 * 0.30 + ret8 * 0.20 + ema_sig * 0.10 - vol * 0.05
|
| 280 |
+
slope_pct = score * horizon * 100
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
return slope_pct, "tabpfn-numeric", \
|
| 282 |
+
f"TabPFN: ret1={ret1*100:.4f}%, ret3={ret3*100:.4f}%, ema_sig={ema_sig*100:.4f}%, vol={vol*100:.3f}%."
|
| 283 |
|
| 284 |
|
| 285 |
def run_dag(closes, req):
|
|
|
|
| 286 |
n = len(closes)
|
| 287 |
if n < 8:
|
| 288 |
return 0.0, "dag", "Insufficient"
|
|
|
|
| 289 |
price_signal = 0.0
|
| 290 |
for lag in [1, 2, 3]:
|
| 291 |
if n > lag:
|
| 292 |
price_signal += (closes[-1] - closes[-(lag+1)]) / closes[-(lag+1)] * (0.5 ** lag)
|
| 293 |
+
exog = 0.0; exog_n = 0
|
| 294 |
+
if req.funding is not None: exog += -math.tanh(req.funding * 10000) * 0.3; exog_n += 1
|
| 295 |
+
if req.cvd is not None: exog += math.tanh(req.cvd / 30_000_000) * 0.4; exog_n += 1
|
| 296 |
+
if req.ob_imbal is not None: exog += math.tanh(req.ob_imbal * 2) * 0.3; exog_n += 1
|
| 297 |
+
if req.taker_buy_ratio is not None: exog += math.tanh((req.taker_buy_ratio - 0.5) * 6) * 0.2; exog_n += 1
|
| 298 |
+
if req.rsi is not None: exog += -math.tanh((req.rsi - 50) / 20) * 0.15; exog_n += 1
|
| 299 |
+
if exog_n > 0: exog /= exog_n
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
combined = price_signal * 0.6 + exog * 0.4
|
| 301 |
slope_pct = math.tanh(combined) * 0.15 * 100
|
| 302 |
return slope_pct, "dag-granger", \
|
|
|
|
| 304 |
|
| 305 |
|
| 306 |
def run_aropt(closes, horizon):
|
|
|
|
| 307 |
n = len(closes)
|
| 308 |
order = min(6, n - 1)
|
| 309 |
if order < 2:
|
|
|
|
| 320 |
forecast = []
|
| 321 |
for _ in range(horizon):
|
| 322 |
nv = float(np.dot(coeffs, window[-order:]))
|
| 323 |
+
forecast.append(nv); window.append(nv)
|
|
|
|
| 324 |
slope_pct = (forecast[-1] - float(closes[-1])) / float(closes[-1]) * 100
|
| 325 |
return slope_pct, "aropt-ls", \
|
| 326 |
f"AR({order}) lstsq: coeffs[:3]={[round(float(c),4) for c in coeffs[:3]]}, slope={slope_pct:.4f}%."
|
| 327 |
|
| 328 |
|
| 329 |
+
def run_patchtst(closes, horizon):
|
| 330 |
+
"""PatchTST numeric — price-only. Context nudge applied at endpoint level."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
n = len(closes)
|
| 332 |
patch_size = 8
|
| 333 |
n_patches = n // patch_size
|
| 334 |
if n_patches < 2:
|
| 335 |
return 0.0, "patchtst", "Insufficient"
|
|
|
|
| 336 |
patches = []
|
| 337 |
for i in range(n_patches):
|
| 338 |
seg = closes[i * patch_size:(i + 1) * patch_size]
|
| 339 |
pr = (seg[-1] - seg[0]) / seg[0] if seg[0] != 0 else 0.0
|
| 340 |
pv = float(np.std(seg)) / float(np.mean(seg)) if np.mean(seg) != 0 else 0.0
|
| 341 |
patches.append((pr, pv))
|
|
|
|
| 342 |
raw_weights = np.array([math.exp(0.4 * i) for i in range(len(patches))])
|
| 343 |
att = raw_weights / raw_weights.sum()
|
| 344 |
weighted_return = sum(p[0] * w for p, w in zip(patches, att))
|
| 345 |
mean_vol = np.mean([p[1] for p in patches[-3:]])
|
| 346 |
vol_penalty = min(0.5, mean_vol * 10)
|
| 347 |
+
slope_pct = weighted_return * horizon * 100 * (1 - vol_penalty)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
return slope_pct, "patchtst-numeric", \
|
| 349 |
+
f"PatchTST: {n_patches} patches, weighted_ret={weighted_return*100:.4f}%, vol_penalty={vol_penalty:.3f}."
|
| 350 |
|
| 351 |
|
| 352 |
def run_tide(closes, req, horizon):
|
|
|
|
| 353 |
n = len(closes)
|
| 354 |
if n < 16:
|
| 355 |
return 0.0, "tide", "Insufficient"
|
|
|
|
| 366 |
|
| 367 |
|
| 368 |
def run_moirai(closes, horizon, req):
|
|
|
|
| 369 |
model = get_moirai()
|
| 370 |
if model is not None:
|
| 371 |
try:
|
| 372 |
ctx = th.tensor(closes[-64:], dtype=th.float32).unsqueeze(0).unsqueeze(-1)
|
| 373 |
samples = model.predict(ctx)
|
| 374 |
arr = samples.squeeze().numpy()
|
| 375 |
+
if arr.ndim == 1: arr = arr.reshape(1, -1)
|
| 376 |
+
median = float(np.median(arr[:, -1]))
|
| 377 |
+
p10 = float(np.percentile(arr[:, -1], 10))
|
| 378 |
+
p90 = float(np.percentile(arr[:, -1], 90))
|
|
|
|
| 379 |
slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
|
| 380 |
uncertainty = (p90 - p10) / float(closes[-1]) * 100
|
| 381 |
return slope_pct, "moirai-salesforce", \
|
| 382 |
f"MOIRAI: median={median:.2f}, uncertainty={uncertainty:.4f}%."
|
| 383 |
except Exception:
|
| 384 |
pass
|
|
|
|
|
|
|
| 385 |
n = len(closes)
|
| 386 |
returns = np.diff(closes) / closes[:-1]
|
| 387 |
if len(returns) < 5:
|
|
|
|
| 393 |
for _ in range(horizon):
|
| 394 |
path *= (1 + rng.choice(returns[-50:]))
|
| 395 |
samples.append(path)
|
| 396 |
+
median = float(np.median(samples))
|
| 397 |
+
p10 = float(np.percentile(samples, 10))
|
| 398 |
+
p90 = float(np.percentile(samples, 90))
|
| 399 |
slope_pct = (median - float(closes[-1])) / float(closes[-1]) * 100
|
| 400 |
uncertainty = (p90 - p10) / float(closes[-1]) * 100
|
| 401 |
ctx_score = build_context_score(req)
|
|
|
|
| 405 |
|
| 406 |
|
| 407 |
def run_nbeats(closes, horizon):
|
|
|
|
| 408 |
n = len(closes)
|
| 409 |
if n < 16:
|
| 410 |
return 0.0, "nbeats", "Insufficient"
|
|
|
|
| 418 |
except Exception:
|
| 419 |
trend_slope = 0.0
|
| 420 |
trend_forecast = np.full(horizon, closes[-1])
|
|
|
|
| 421 |
if n >= 32:
|
| 422 |
+
fft = np.fft.rfft(closes[-32:] - np.mean(closes[-32:]))
|
| 423 |
+
dominant_freq = np.argmax(np.abs(fft[1:])) + 1
|
| 424 |
+
period = 32 / dominant_freq if dominant_freq > 0 else 32
|
| 425 |
+
phase = (n % period) / period * 2 * math.pi
|
| 426 |
seasonal_signal = math.sin(phase + math.pi / 2)
|
| 427 |
else:
|
| 428 |
+
seasonal_signal = 0.0; period = 32.0
|
|
|
|
|
|
|
| 429 |
residual = (closes[-1] - closes[-5]) / closes[-5] if n >= 5 else 0.0
|
| 430 |
slope_pct = trend_slope * 0.7 + seasonal_signal * 0.03 * 100 + float(residual) * 30
|
| 431 |
slope_pct = float(np.clip(slope_pct, -1.0, 1.0))
|
|
|
|
| 455 |
"ok": True,
|
| 456 |
"chronos": CHRONOS_AVAILABLE,
|
| 457 |
"moirai": MOIRAI_AVAILABLE,
|
| 458 |
+
"version": "14.2.0",
|
| 459 |
"models": list(STATIC_WEIGHTS.keys()),
|
| 460 |
}
|
| 461 |
|
|
|
|
| 467 |
horizon = req.horizon
|
| 468 |
results: List[ModelResult] = []
|
| 469 |
|
| 470 |
+
# FIX 2: per-TF threshold — was hardcoded 0.008 for all TFs
|
| 471 |
tf_threshold = SLOPE_THRESHOLDS.get(req.timeframe, 0.003)
|
| 472 |
|
| 473 |
+
# FIX (reviewer #4): compute context nudge ONCE here, apply to all models
|
| 474 |
+
# below. Keeps each model's internal logic price-only (preserves independence)
|
| 475 |
+
# while ensuring funding/RSI signals can tip near-threshold models to DOWN.
|
| 476 |
+
ctx_nudge = compute_context_nudge(req, req.timeframe)
|
| 477 |
+
|
| 478 |
def add(name, slope_pct, note, reasoning, is_avail, threshold=None, conf_mult=1.0):
|
| 479 |
+
t = threshold if threshold is not None else tf_threshold
|
| 480 |
+
# Apply context nudge to slope before direction decision.
|
| 481 |
+
# Nudge is small (max ±0.008%) — can tip near-threshold to DOWN/UP
|
| 482 |
+
# but cannot reverse a confident model.
|
| 483 |
+
nudged_slope = slope_pct + ctx_nudge
|
| 484 |
+
direction, conf = slope_to_direction(nudged_slope, t)
|
| 485 |
+
conf = min(95.0, conf * conf_mult)
|
| 486 |
results.append(ModelResult(
|
| 487 |
name=name, direction=direction, confidence=conf,
|
| 488 |
+
slope_pct=round(nudged_slope, 6), available=is_avail,
|
| 489 |
+
note=note, reasoning=reasoning + f" [nudge={ctx_nudge:+.4f}%]",
|
| 490 |
))
|
| 491 |
|
|
|
|
|
|
|
| 492 |
runners = [
|
| 493 |
("Chronos", lambda: run_chronos(closes, horizon),
|
| 494 |
+
lambda: run_chronos_fallback(closes, horizon)),
|
| 495 |
+
("TabPFN-TS", lambda: run_tabpfn(closes, horizon), None),
|
| 496 |
+
("DAG", lambda: run_dag(closes, req), None),
|
| 497 |
+
("AROpt", lambda: run_aropt(closes, horizon), None),
|
| 498 |
+
("PatchTST", lambda: run_patchtst(closes, horizon), None),
|
| 499 |
+
("TiDE", lambda: run_tide(closes, req, horizon), None),
|
| 500 |
+
("MOIRAI", lambda: run_moirai(closes, horizon, req), None),
|
| 501 |
+
("N-BEATS", lambda: run_nbeats(closes, horizon), None),
|
| 502 |
]
|
| 503 |
|
| 504 |
for name, fn, fb in runners:
|
|
|
|
| 516 |
add(name, 0.0, str(e)[:60], f"Error in {name}", False)
|
| 517 |
|
| 518 |
# ── Adaptive weight blending ──────────────────────────────────────────────
|
| 519 |
+
adaptive = req.adaptive_weights or {}
|
| 520 |
eff_weights = {}
|
| 521 |
for m, sw in STATIC_WEIGHTS.items():
|
| 522 |
aw = adaptive.get(m)
|
|
|
|
| 539 |
total_weight += w
|
| 540 |
comp_score = composite / total_weight if total_weight > 0 else 0.0
|
| 541 |
|
| 542 |
+
# ── Composite direction — tightened NEUTRAL threshold ────��───────────────
|
| 543 |
+
# Old: fixed 0.03 for all TFs. New: per-TF, consistent with model thresholds.
|
| 544 |
+
COMPOSITE_THRESHOLD = {"5M": 0.018, "15M": 0.015, "1D": 0.012}.get(req.timeframe, 0.018)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
|
| 546 |
if abs(comp_score) < COMPOSITE_THRESHOLD:
|
| 547 |
comp_dir = "NEUTRAL"
|