Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,762 +1,736 @@
|
|
| 1 |
"""
|
| 2 |
-
PolyBloom ML
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
KEPT + UPGRADED:
|
| 15 |
-
- Chronos (Amazon T5, upgraded to chronos-bolt when available)
|
| 16 |
-
- MOIRAI (Salesforce foundation — weight raised 7%→20%)
|
| 17 |
-
- MOMENT (CMU T5 zero-shot, replaces TabPFN)
|
| 18 |
-
|
| 19 |
-
TRAINED CLASSIFIERS (replace PatchTST + N-BEATS):
|
| 20 |
-
- XGBoost (trained on 35 live features your terminal sends)
|
| 21 |
-
- LightGBM (same features, handles class imbalance natively)
|
| 22 |
-
|
| 23 |
-
FORMULA UPGRADES (now consume polymarket_yes):
|
| 24 |
-
- DAG (orderflow + CVD + OBI + polymarket_yes)
|
| 25 |
-
- TiDE (macro: DXY + Nasdaq + funding + polymarket_yes)
|
| 26 |
-
|
| 27 |
-
NEW:
|
| 28 |
-
- Lag-Llama (zero-shot probabilistic AR, replaces AROpt)
|
| 29 |
-
|
| 30 |
-
CRITICAL FIX: polymarket_yes NOW READ BY DAG + TiDE + Lag-Llama proxy.
|
| 31 |
-
Previously 0 models used the Polymarket YES odds despite terminal sending it.
|
| 32 |
-
|
| 33 |
-
NEW WEIGHTS (sum = 1.0):
|
| 34 |
-
MOIRAI 20% | Chronos 18% | MOMENT 15% | XGBoost 15%
|
| 35 |
-
LightGBM 12% | Lag-Llama 10% | DAG 6% | TiDE 4%
|
| 36 |
-
|
| 37 |
-
HF SPACE NOTES:
|
| 38 |
-
- Set CHRONOS_MODEL=amazon/chronos-bolt-small in Space secrets
|
| 39 |
-
- Set MOIRAI_MODEL=Salesforce/moirai-1.1-R-small in Space secrets
|
| 40 |
-
- CPU-only Space is fine; all inference runs on CPU
|
| 41 |
-
- XGBoost/LightGBM bootstrap trains in ~30s on first request
|
| 42 |
-
- Upload xgb_model.json + lgbm_model.txt to Space files for real weights
|
| 43 |
"""
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
| 46 |
import numpy as np
|
| 47 |
-
from
|
|
|
|
|
|
|
| 48 |
from fastapi.middleware.cors import CORSMiddleware
|
| 49 |
-
from
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
MOIRAI_AVAILABLE = False
|
| 54 |
-
MOMENT_AVAILABLE = False
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
pass
|
| 62 |
-
|
| 63 |
-
try:
|
| 64 |
-
from uni2ts.model.moirai import MoiraiForecast, MoiraiModule
|
| 65 |
-
import torch as th
|
| 66 |
-
MOIRAI_AVAILABLE = True
|
| 67 |
-
except Exception:
|
| 68 |
-
pass
|
| 69 |
-
|
| 70 |
-
try:
|
| 71 |
-
import momentfm
|
| 72 |
-
MOMENT_AVAILABLE = True
|
| 73 |
-
except Exception:
|
| 74 |
-
pass
|
| 75 |
-
|
| 76 |
-
try:
|
| 77 |
-
import xgboost as xgb
|
| 78 |
-
XGB_AVAILABLE = True
|
| 79 |
-
except Exception:
|
| 80 |
-
XGB_AVAILABLE = False
|
| 81 |
-
|
| 82 |
-
try:
|
| 83 |
-
import lightgbm as lgb
|
| 84 |
-
LGBM_AVAILABLE = True
|
| 85 |
-
except Exception:
|
| 86 |
-
LGBM_AVAILABLE = False
|
| 87 |
-
|
| 88 |
-
# ── Env config ─────────────────────────────────────────────────────────────
|
| 89 |
-
CHRONOS_MODEL = os.environ.get("CHRONOS_MODEL", "amazon/chronos-bolt-small")
|
| 90 |
-
MOIRAI_MODEL = os.environ.get("MOIRAI_MODEL", "Salesforce/moirai-1.1-R-small")
|
| 91 |
-
|
| 92 |
-
app = FastAPI(title="PolyBloom ML Ensemble v17 (HF Space)", version="17.0.0")
|
| 93 |
app.add_middleware(
|
| 94 |
CORSMiddleware,
|
| 95 |
-
allow_origins=["*"],
|
|
|
|
|
|
|
| 96 |
)
|
| 97 |
|
| 98 |
-
# ──
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
|
|
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
| 118 |
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
-
def
|
| 121 |
-
|
| 122 |
-
if _moirai is None and MOIRAI_AVAILABLE:
|
| 123 |
-
try:
|
| 124 |
-
_moirai = MoiraiForecast.load_from_checkpoint(
|
| 125 |
-
prediction_length=4, context_length=64, patch_size="auto",
|
| 126 |
-
num_samples=100, target_dim=1, feat_dynamic_real_dim=0,
|
| 127 |
-
past_feat_dynamic_real_dim=0,
|
| 128 |
-
checkpoint_path=MoiraiModule.from_pretrained(MOIRAI_MODEL),
|
| 129 |
-
)
|
| 130 |
-
except Exception as e:
|
| 131 |
-
print(f"[moirai] load failed: {e}")
|
| 132 |
-
return _moirai
|
| 133 |
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
def
|
| 136 |
-
|
| 137 |
-
if _moment is None and MOMENT_AVAILABLE:
|
| 138 |
-
try:
|
| 139 |
-
_moment = momentfm.MOMENT.from_pretrained(
|
| 140 |
-
"AutonLab/MOMENT-1-large",
|
| 141 |
-
model_kwargs={"task_name": "classification"},
|
| 142 |
-
)
|
| 143 |
-
_moment.eval()
|
| 144 |
-
except Exception as e:
|
| 145 |
-
print(f"[moment] load failed: {e}")
|
| 146 |
-
return _moment
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
# ── Synthetic bootstrap for XGBoost + LightGBM (35 features) ──────────────
|
| 150 |
-
FEATURE_NAMES = [
|
| 151 |
-
"ret1", "ret3", "ret8", "ret20",
|
| 152 |
-
"ema_sig_8_20", "ema_sig_20_50",
|
| 153 |
-
"vol_8", "vol_20",
|
| 154 |
-
"funding", "cvd_norm", "ob_imbal", "taker_buy_ratio",
|
| 155 |
-
"rsi_norm", "macd_sign",
|
| 156 |
-
"dxy_change", "nasdaq_change",
|
| 157 |
-
"polymarket_yes", "poly_delta_1m",
|
| 158 |
-
"fear_greed_norm",
|
| 159 |
-
"coinbase_premium",
|
| 160 |
-
"korea_premium",
|
| 161 |
-
"deribit_pcr_norm",
|
| 162 |
-
"ls_ratio_norm",
|
| 163 |
-
"open_interest_norm",
|
| 164 |
-
"sentiment_polarity",
|
| 165 |
-
"vwap_dev",
|
| 166 |
-
"atr_pct",
|
| 167 |
-
"ema_align_sign",
|
| 168 |
-
"htf_trend_15m_sign",
|
| 169 |
-
"htf_trend_1h_sign",
|
| 170 |
-
"vol_regime_sign",
|
| 171 |
-
"sl5_norm",
|
| 172 |
-
"sl20_norm",
|
| 173 |
-
"whale_btc_norm",
|
| 174 |
-
"stablecoin_chg_norm",
|
| 175 |
-
]
|
| 176 |
-
N_FEATURES = len(FEATURE_NAMES) # 35
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
def _make_synth(n: int = 6000, seed: int = 42) -> Tuple[np.ndarray, np.ndarray]:
|
| 180 |
-
"""Generate realistic synthetic training data matching live feature space."""
|
| 181 |
-
rng = np.random.default_rng(seed)
|
| 182 |
-
X = rng.normal(0, 1, size=(n, N_FEATURES)).astype(np.float32)
|
| 183 |
-
score = (
|
| 184 |
-
X[:, 0] * 0.40 # ret1
|
| 185 |
-
+ X[:, 1] * 0.25 # ret3
|
| 186 |
-
+ X[:, 2] * 0.10 # ret8
|
| 187 |
-
+ X[:, 9] * 0.20 # cvd_norm
|
| 188 |
-
+ X[:, 10] * 0.25 # ob_imbal
|
| 189 |
-
+ X[:, 11] * 0.15 # taker_buy_ratio
|
| 190 |
-
+ X[:, 16] * 0.18 # polymarket_yes ← KEY: crowd wisdom
|
| 191 |
-
+ X[:, 17] * 0.12 # poly_delta_1m
|
| 192 |
-
+ X[:, 8] * -0.10 # funding (negative = bearish funding bias)
|
| 193 |
-
+ rng.normal(0, 0.4, size=n)
|
| 194 |
-
)
|
| 195 |
-
y = (score > 0).astype(np.int32)
|
| 196 |
-
return X, y
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
def bootstrap_boosters():
|
| 200 |
-
global _xgb, _lgbm, _bootstrap_done
|
| 201 |
-
with _bootstrap_lock:
|
| 202 |
-
if _bootstrap_done:
|
| 203 |
-
return
|
| 204 |
-
X, y = _make_synth()
|
| 205 |
-
xgb_path = os.path.join(os.path.dirname(__file__), "xgb_model.json")
|
| 206 |
-
lgbm_path = os.path.join(os.path.dirname(__file__), "lgbm_model.txt")
|
| 207 |
-
|
| 208 |
-
if XGB_AVAILABLE:
|
| 209 |
-
try:
|
| 210 |
-
m = xgb.XGBClassifier(
|
| 211 |
-
n_estimators=300, max_depth=5, learning_rate=0.04,
|
| 212 |
-
objective="binary:logistic", tree_method="hist",
|
| 213 |
-
eval_metric="logloss", verbosity=0,
|
| 214 |
-
subsample=0.8, colsample_bytree=0.8,
|
| 215 |
-
)
|
| 216 |
-
if os.path.exists(xgb_path):
|
| 217 |
-
m.load_model(xgb_path)
|
| 218 |
-
print("[xgb] loaded real weights from xgb_model.json")
|
| 219 |
-
else:
|
| 220 |
-
m.fit(X, y)
|
| 221 |
-
print("[xgb] synthetic bootstrap done (upload xgb_model.json for real weights)")
|
| 222 |
-
_xgb = m
|
| 223 |
-
except Exception as e:
|
| 224 |
-
print(f"[xgb] bootstrap failed: {e}")
|
| 225 |
-
|
| 226 |
-
if LGBM_AVAILABLE:
|
| 227 |
-
try:
|
| 228 |
-
if os.path.exists(lgbm_path):
|
| 229 |
-
m = lgb.Booster(model_file=lgbm_path)
|
| 230 |
-
print("[lgbm] loaded real weights from lgbm_model.txt")
|
| 231 |
-
_lgbm = m
|
| 232 |
-
else:
|
| 233 |
-
m = lgb.LGBMClassifier(
|
| 234 |
-
n_estimators=300, max_depth=5, learning_rate=0.04,
|
| 235 |
-
num_leaves=31, is_unbalance=True, verbosity=-1,
|
| 236 |
-
)
|
| 237 |
-
m.fit(X, y)
|
| 238 |
-
print("[lgbm] synthetic bootstrap done (upload lgbm_model.txt for real weights)")
|
| 239 |
-
_lgbm = m
|
| 240 |
-
except Exception as e:
|
| 241 |
-
print(f"[lgbm] bootstrap failed: {e}")
|
| 242 |
-
|
| 243 |
-
_bootstrap_done = True
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
threading.Thread(target=bootstrap_boosters, daemon=True).start()
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
# ── Request / Response schemas ─────────────────────────────────────────────
|
| 250 |
-
class OmegaRequest(BaseModel):
|
| 251 |
-
closes: List[float] = Field(..., min_length=16)
|
| 252 |
-
highs: Optional[List[float]] = None
|
| 253 |
-
lows: Optional[List[float]] = None
|
| 254 |
-
volumes: Optional[List[float]] = None
|
| 255 |
-
horizon: int = Field(3, ge=1, le=12)
|
| 256 |
-
timeframe: str = Field("5M")
|
| 257 |
-
|
| 258 |
-
# Orderflow
|
| 259 |
-
funding: Optional[float] = None
|
| 260 |
-
ob_imbal: Optional[float] = None
|
| 261 |
-
cvd: Optional[float] = None
|
| 262 |
-
taker_buy_ratio: Optional[float] = None
|
| 263 |
-
bid_ask_spread_pct: Optional[float] = None
|
| 264 |
-
bid_vol_top20: Optional[float] = None
|
| 265 |
-
ask_vol_top20: Optional[float] = None
|
| 266 |
-
|
| 267 |
-
# Technicals
|
| 268 |
-
rsi: Optional[float] = None
|
| 269 |
-
macd: Optional[str] = None
|
| 270 |
-
ema_align: Optional[str] = None
|
| 271 |
-
stoch_rsi_k: Optional[float] = None
|
| 272 |
-
vwap_dev: Optional[float] = None
|
| 273 |
-
atr_pct_of_spot: Optional[float] = None
|
| 274 |
-
bollinger_squeeze: Optional[bool] = None
|
| 275 |
-
vol_regime: Optional[str] = None
|
| 276 |
-
vol_percentile: Optional[float] = None
|
| 277 |
-
garman_klass_vol: Optional[float] = None
|
| 278 |
-
|
| 279 |
-
# Structure
|
| 280 |
-
spot: Optional[float] = None
|
| 281 |
-
strike: Optional[float] = None
|
| 282 |
-
nearest_support: Optional[float] = None
|
| 283 |
-
nearest_resistance: Optional[float] = None
|
| 284 |
-
market_regime: Optional[str] = None
|
| 285 |
-
htf_trend_15m: Optional[str] = None
|
| 286 |
-
htf_trend_1h: Optional[str] = None
|
| 287 |
-
candle_pattern: Optional[str] = None
|
| 288 |
-
|
| 289 |
-
# Derivatives
|
| 290 |
-
open_interest: Optional[float] = None
|
| 291 |
-
ls_ratio: Optional[float] = None
|
| 292 |
-
deribit_pcr: Optional[float] = None
|
| 293 |
-
|
| 294 |
-
# Macro
|
| 295 |
-
fear_greed: Optional[float] = None
|
| 296 |
-
dxy_change_pct: Optional[float] = None
|
| 297 |
-
nasdaq_fut_change_pct: Optional[float] = None
|
| 298 |
-
farside_net_flow_usd: Optional[float] = None
|
| 299 |
-
btc_dom: Optional[float] = None
|
| 300 |
-
stablecoin_supply_change: Optional[float] = None
|
| 301 |
-
chainlink_price: Optional[float] = None
|
| 302 |
-
|
| 303 |
-
# Polymarket ← CRITICAL INPUT — consumed by DAG, TiDE, Lag-Llama, XGBoost, LightGBM
|
| 304 |
-
polymarket_yes: Optional[float] = None
|
| 305 |
-
poly_yes_delta_1m: Optional[float] = None
|
| 306 |
-
|
| 307 |
-
# Sentiment / On-chain
|
| 308 |
-
sentiment_polarity: Optional[float] = None
|
| 309 |
-
coinbase_premium_pct: Optional[float] = None
|
| 310 |
-
exchange_net_inflow_btc_5m: Optional[float] = None
|
| 311 |
-
whale_transfer_btc: Optional[float] = None
|
| 312 |
-
whale_transfer_dest: Optional[str] = None
|
| 313 |
-
whale_exchange_count_15m: Optional[float] = None
|
| 314 |
-
korea_premium_pct: Optional[float] = None
|
| 315 |
-
|
| 316 |
-
# Session
|
| 317 |
-
session: Optional[str] = None
|
| 318 |
-
|
| 319 |
-
# Adaptive weights from front-end accuracy tracker
|
| 320 |
-
adaptive_weights: Optional[dict] = None
|
| 321 |
-
|
| 322 |
-
class Config:
|
| 323 |
-
extra = "allow"
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
class ModelResult(BaseModel):
|
| 327 |
-
name: str
|
| 328 |
-
direction: str
|
| 329 |
-
confidence: float
|
| 330 |
-
slope_pct: float
|
| 331 |
-
available: bool
|
| 332 |
-
note: str
|
| 333 |
-
reasoning: str
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
class OmegaResponse(BaseModel):
|
| 337 |
-
composite_direction: str
|
| 338 |
-
composite_confidence: float
|
| 339 |
-
composite_score: float
|
| 340 |
-
models: List[ModelResult]
|
| 341 |
-
elapsed_ms: int
|
| 342 |
-
timeframe: str
|
| 343 |
-
anti_bias_applied: bool
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
# ── Helpers ────────────────────────────────────────────────────────────────
|
| 347 |
-
def slope_to_direction(slope_pct: float, threshold: float = 0.008) -> Tuple[str, float]:
|
| 348 |
-
if abs(slope_pct) < threshold:
|
| 349 |
-
return "NEUTRAL", 50.0
|
| 350 |
-
conf = min(95.0, 50.0 + abs(slope_pct) / threshold * 8.0)
|
| 351 |
-
return ("UP" if slope_pct > 0 else "DOWN"), conf
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
def ema(arr: np.ndarray, period: int) -> float:
|
| 355 |
-
if len(arr) < period:
|
| 356 |
-
return float(np.mean(arr))
|
| 357 |
-
k = 2 / (period + 1)
|
| 358 |
-
val = float(arr[0])
|
| 359 |
-
for x in arr[1:]:
|
| 360 |
-
val = float(x) * k + val * (1 - k)
|
| 361 |
-
return val
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
def _sign_str(s: Optional[str], bull: list, bear: list) -> float:
|
| 365 |
-
if not s:
|
| 366 |
return 0.0
|
| 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 |
return np.array([
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 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 |
-
_sign_str(req.vol_regime, ["LOW","CALM"], ["HIGH","EXPAND"]),
|
| 423 |
-
sl5,
|
| 424 |
-
sl20,
|
| 425 |
-
-min(1.0, (req.whale_transfer_btc or 0) / 200),
|
| 426 |
-
math.tanh((req.stablecoin_supply_change or 0) * 100),
|
| 427 |
], dtype=np.float32)
|
| 428 |
|
| 429 |
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
trend
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 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 |
score = (
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
)
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
def run_xgboost(closes: np.ndarray, req: OmegaRequest):
|
| 531 |
-
if not _bootstrap_done:
|
| 532 |
-
raise RuntimeError("XGBoost not ready yet")
|
| 533 |
-
if _xgb is None:
|
| 534 |
-
raise RuntimeError("XGBoost unavailable")
|
| 535 |
-
fv = build_feature_vector(closes, req).reshape(1, -1)
|
| 536 |
-
p_up = float(_xgb.predict_proba(fv)[0, 1])
|
| 537 |
-
slope_pct = (p_up - 0.5) * 0.20 * 100
|
| 538 |
-
is_real = os.path.exists(os.path.join(os.path.dirname(__file__), "xgb_model.json"))
|
| 539 |
-
note = "xgboost-real-trained" if is_real else "xgboost-synthetic"
|
| 540 |
-
poly_str = f", poly_yes={req.polymarket_yes:.3f}" if req.polymarket_yes else ""
|
| 541 |
-
return slope_pct, note, f"XGBoost: P(UP)={p_up:.4f}{poly_str}"
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
def run_lightgbm(closes: np.ndarray, req: OmegaRequest):
|
| 545 |
-
if not _bootstrap_done:
|
| 546 |
-
raise RuntimeError("LightGBM not ready yet")
|
| 547 |
-
if _lgbm is None:
|
| 548 |
-
raise RuntimeError("LightGBM unavailable")
|
| 549 |
-
fv = build_feature_vector(closes, req).reshape(1, -1)
|
| 550 |
-
is_booster = isinstance(_lgbm, lgb.Booster)
|
| 551 |
-
if is_booster:
|
| 552 |
-
p_up = float(_lgbm.predict(fv)[0])
|
| 553 |
-
else:
|
| 554 |
-
p_up = float(_lgbm.predict_proba(fv)[0, 1])
|
| 555 |
-
slope_pct = (p_up - 0.5) * 0.18 * 100
|
| 556 |
-
is_real = os.path.exists(os.path.join(os.path.dirname(__file__), "lgbm_model.txt"))
|
| 557 |
-
note = "lightgbm-real-trained" if is_real else "lightgbm-synthetic"
|
| 558 |
-
return slope_pct, note, f"LightGBM: P(UP)={p_up:.4f}"
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
def run_lag_llama_proxy(closes: np.ndarray, req: OmegaRequest, horizon: int):
|
| 562 |
-
n = len(closes)
|
| 563 |
-
last = float(closes[-1])
|
| 564 |
-
returns = np.diff(closes[-50:]) / closes[-51:-1] if n >= 52 else np.diff(closes) / closes[:-1]
|
| 565 |
-
if len(returns) < 4:
|
| 566 |
-
return 0.0, "lag-llama-proxy", "Insufficient"
|
| 567 |
-
rng = np.random.default_rng(seed=int(last) % 2**31)
|
| 568 |
-
paths = []
|
| 569 |
-
for _ in range(500):
|
| 570 |
-
path = last
|
| 571 |
-
for _ in range(horizon):
|
| 572 |
-
path *= (1 + rng.choice(returns))
|
| 573 |
-
paths.append(path)
|
| 574 |
-
p10 = float(np.percentile(paths, 10))
|
| 575 |
-
p50 = float(np.median(paths))
|
| 576 |
-
p90 = float(np.percentile(paths, 90))
|
| 577 |
-
p_up = float(np.mean(np.array(paths) > last))
|
| 578 |
-
if req.polymarket_yes is not None:
|
| 579 |
-
poly_weight = 0.35
|
| 580 |
-
p_up = p_up * (1 - poly_weight) + req.polymarket_yes * poly_weight
|
| 581 |
-
slope_pct = (p50 - last) / last * 100
|
| 582 |
-
p_up_slope = (p_up - 0.5) * 0.12 * 100
|
| 583 |
-
final_slope = slope_pct * 0.5 + p_up_slope * 0.5
|
| 584 |
-
poly_str = f", poly_yes={req.polymarket_yes:.3f}" if req.polymarket_yes else ""
|
| 585 |
-
return final_slope, "lag-llama-proxy", (
|
| 586 |
-
f"LagLlama: P(UP)={p_up:.3f}, p50={p50:.2f}{poly_str}, unc={(p90-p10)/last*100:.4f}%"
|
| 587 |
)
|
| 588 |
|
| 589 |
|
| 590 |
-
def
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 597 |
)
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
if req.ob_imbal is not None: exog += math.tanh(req.ob_imbal * 2) * 0.3; cnt += 1
|
| 602 |
-
if req.taker_buy_ratio is not None:
|
| 603 |
-
exog += math.tanh((req.taker_buy_ratio - 0.5) * 6) * 0.2; cnt += 1
|
| 604 |
-
if req.rsi is not None:
|
| 605 |
-
exog += -math.tanh((req.rsi - 50) / 20) * 0.15; cnt += 1
|
| 606 |
-
poly_signal = 0.0
|
| 607 |
-
if req.polymarket_yes is not None:
|
| 608 |
-
poly_signal = math.tanh((req.polymarket_yes - 0.5) * 6) * 0.30
|
| 609 |
-
if req.poly_yes_delta_1m is not None:
|
| 610 |
-
poly_signal += math.tanh(req.poly_yes_delta_1m * 20) * 0.15
|
| 611 |
-
if cnt > 0:
|
| 612 |
-
exog /= cnt
|
| 613 |
-
combined = price_signal * 0.40 + exog * 0.35 + poly_signal * 0.25
|
| 614 |
-
slope_pct = math.tanh(combined) * 0.15 * 100
|
| 615 |
-
poly_str = f", poly={req.polymarket_yes:.3f}" if req.polymarket_yes else ""
|
| 616 |
-
return slope_pct, "dag-granger-v2", (
|
| 617 |
-
f"DAG: price={price_signal*100:.4f}%, exog={exog:.4f}{poly_str}, combined={combined:.4f}"
|
| 618 |
)
|
| 619 |
|
| 620 |
|
| 621 |
-
def
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
if req.poly_yes_delta_1m is not None:
|
| 639 |
-
poly_signal += math.tanh(req.poly_yes_delta_1m * 15) * 0.15
|
| 640 |
-
combined = ts_signal * 0.40 + macro * 0.30 + poly_signal * 0.30
|
| 641 |
-
slope_pct = math.tanh(combined * 3) * 0.12 * 100
|
| 642 |
-
poly_str = f", poly={req.polymarket_yes:.3f}" if req.polymarket_yes else ""
|
| 643 |
-
return slope_pct, "tide-macro-v2", (
|
| 644 |
-
f"TiDE: ts={ts_signal*100:.4f}%, macro={macro:.4f}{poly_str}, slope={slope_pct:.4f}%"
|
| 645 |
)
|
| 646 |
|
| 647 |
|
| 648 |
-
# ──
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
"Chronos": 0.18,
|
| 652 |
-
"MOMENT": 0.15,
|
| 653 |
-
"XGBoost": 0.15,
|
| 654 |
-
"LightGBM": 0.12,
|
| 655 |
-
"Lag-Llama": 0.10,
|
| 656 |
-
"DAG": 0.06,
|
| 657 |
-
"TiDE": 0.04,
|
| 658 |
-
}
|
| 659 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 660 |
|
| 661 |
@app.get("/")
|
| 662 |
-
def
|
| 663 |
return {
|
| 664 |
-
"ok":
|
| 665 |
-
"version":
|
| 666 |
-
"chronos":
|
| 667 |
-
"moirai":
|
| 668 |
-
"moment":
|
| 669 |
-
"xgboost":
|
| 670 |
-
"lgbm":
|
| 671 |
-
"lag_llama":
|
| 672 |
-
"dag":
|
| 673 |
-
"tide":
|
| 674 |
-
"models":
|
|
|
|
| 675 |
"polymarket_fix": "DAG+TiDE+LagLlama now consume polymarket_yes",
|
| 676 |
"removed": ["TabPFN-TS", "PatchTST", "N-BEATS", "AROpt"],
|
| 677 |
"hf_space": True,
|
| 678 |
}
|
| 679 |
|
| 680 |
|
| 681 |
-
@app.post("/omega"
|
| 682 |
-
def
|
| 683 |
-
t0
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
("Chronos", lambda: run_chronos(closes, req.horizon),
|
| 701 |
-
lambda: run_chronos_fallback(closes, req.horizon)),
|
| 702 |
-
("MOMENT", lambda: run_moment_proxy(closes, req, req.horizon), None),
|
| 703 |
-
("XGBoost", lambda: run_xgboost(closes, req), None),
|
| 704 |
-
("LightGBM", lambda: run_lightgbm(closes, req), None),
|
| 705 |
-
("Lag-Llama", lambda: run_lag_llama_proxy(closes, req, req.horizon), None),
|
| 706 |
-
("DAG", lambda: run_dag(closes, req), None),
|
| 707 |
-
("TiDE", lambda: run_tide(closes, req, req.horizon), None),
|
| 708 |
-
]
|
| 709 |
-
|
| 710 |
-
for name, fn, fb in runners:
|
| 711 |
try:
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
try:
|
| 717 |
-
sp, note, rsn = fb()
|
| 718 |
-
add(name, sp, note, rsn, False, conf_mult=0.75)
|
| 719 |
-
continue
|
| 720 |
-
except Exception:
|
| 721 |
-
pass
|
| 722 |
-
add(name, 0.0, str(e)[:80], f"Error in {name}: {str(e)[:60]}", False)
|
| 723 |
-
|
| 724 |
-
adaptive = req.adaptive_weights or {}
|
| 725 |
-
n_settled = adaptive.get("_n_settled", 0) or 0
|
| 726 |
-
eff_weights: dict = {}
|
| 727 |
-
for m, sw in STATIC_WEIGHTS.items():
|
| 728 |
-
aw = adaptive.get(m)
|
| 729 |
-
if isinstance(aw, (int, float)) and 0.01 <= aw <= 0.95:
|
| 730 |
-
blend = min(1.0, n_settled / 30)
|
| 731 |
-
eff_weights[m] = aw * blend + sw * (1 - blend)
|
| 732 |
-
else:
|
| 733 |
-
eff_weights[m] = sw
|
| 734 |
-
total_w = sum(eff_weights.values())
|
| 735 |
-
eff_weights = {k: v / total_w for k, v in eff_weights.items()}
|
| 736 |
-
|
| 737 |
-
composite = 0.0
|
| 738 |
-
total_weight = 0.0
|
| 739 |
-
for r in results:
|
| 740 |
-
w = eff_weights.get(r.name, 0.0)
|
| 741 |
-
sign = 1.0 if r.direction == "UP" else (-1.0 if r.direction == "DOWN" else 0.0)
|
| 742 |
-
composite += sign * (r.confidence / 100.0) * w
|
| 743 |
-
total_weight += w
|
| 744 |
-
comp_score = composite / total_weight if total_weight > 0 else 0.0
|
| 745 |
-
|
| 746 |
-
THRESHOLD = {"5M": 0.03, "15M": 0.025, "1D": 0.02}.get(req.timeframe, 0.03)
|
| 747 |
-
if abs(comp_score) < THRESHOLD:
|
| 748 |
-
comp_dir = "NEUTRAL"
|
| 749 |
-
comp_conf = 50.0 + abs(comp_score) / THRESHOLD * 10.0
|
| 750 |
else:
|
| 751 |
-
|
| 752 |
-
comp_conf = min(95.0, 50.0 + abs(comp_score) / 0.3 * 45.0)
|
| 753 |
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
PolyBloom ML Service — v17.0.0
|
| 3 |
+
Hugging Face Space: OMEGA COUNCIL (8 models)
|
| 4 |
+
|
| 5 |
+
Model roster:
|
| 6 |
+
ROW 1 FOUNDATION MOIRAI · Chronos · MOMENT (try real transformers, bootstrap fallback)
|
| 7 |
+
ROW 2 TRAINED XGBoost · LightGBM (bootstrap train on startup, always true)
|
| 8 |
+
ROW 3 SIGNAL Lag-Llama · DAG · TiDE (formula, always true)
|
| 9 |
+
|
| 10 |
+
v17 polymarket_yes fix: DAG + TiDE + Lag-Llama all consume polymarket_yes.
|
| 11 |
+
|
| 12 |
+
Health endpoint GET /
|
| 13 |
+
Omega endpoint POST /omega
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
"""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import math
|
| 18 |
+
import time
|
| 19 |
+
import logging
|
| 20 |
import numpy as np
|
| 21 |
+
from typing import Optional
|
| 22 |
+
|
| 23 |
+
from fastapi import FastAPI, Request
|
| 24 |
from fastapi.middleware.cors import CORSMiddleware
|
| 25 |
+
from fastapi.responses import JSONResponse
|
| 26 |
|
| 27 |
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
|
| 28 |
+
logger = logging.getLogger("polybloom")
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 31 |
+
# App
|
| 32 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 33 |
+
|
| 34 |
+
app = FastAPI(title="PolyBloom ML Service", version="17.0.0")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
app.add_middleware(
|
| 36 |
CORSMiddleware,
|
| 37 |
+
allow_origins=["*"],
|
| 38 |
+
allow_methods=["*"],
|
| 39 |
+
allow_headers=["*"],
|
| 40 |
)
|
| 41 |
|
| 42 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 43 |
+
# Global state
|
| 44 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 45 |
+
|
| 46 |
+
_flags: dict = {
|
| 47 |
+
"chronos": False,
|
| 48 |
+
"moirai": False,
|
| 49 |
+
"moment": False,
|
| 50 |
+
"xgboost": False,
|
| 51 |
+
"lgbm": False,
|
| 52 |
+
"lag_llama": True, # formula — always available
|
| 53 |
+
"dag": True, # formula — always available
|
| 54 |
+
"tide": True, # formula — always available
|
| 55 |
+
}
|
| 56 |
|
| 57 |
+
_models: dict = {} # name → loaded object
|
| 58 |
|
| 59 |
+
# Weights matching public/weights.json v17.0
|
| 60 |
+
WEIGHTS = {
|
| 61 |
+
"MOIRAI": 0.20,
|
| 62 |
+
"Chronos": 0.18,
|
| 63 |
+
"MOMENT": 0.15,
|
| 64 |
+
"XGBoost": 0.15,
|
| 65 |
+
"LightGBM": 0.12,
|
| 66 |
+
"Lag-Llama": 0.10,
|
| 67 |
+
"DAG": 0.06,
|
| 68 |
+
"TiDE": 0.04,
|
| 69 |
+
}
|
| 70 |
|
| 71 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 72 |
+
# Helpers
|
| 73 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 74 |
|
| 75 |
+
def _tanh(x: float) -> float:
|
| 76 |
+
return math.tanh(x)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
def _clamp(v: float, lo: float, hi: float) -> float:
|
| 79 |
+
return max(lo, min(hi, v))
|
| 80 |
|
| 81 |
+
def _slope(arr: np.ndarray, p: int) -> float:
|
| 82 |
+
if len(arr) < p + 1:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
return 0.0
|
| 84 |
+
b = arr[-p - 1]
|
| 85 |
+
return float((arr[-1] - b) / b) if b != 0 else 0.0
|
| 86 |
+
|
| 87 |
+
def _ema(arr: np.ndarray, p: int) -> float:
|
| 88 |
+
k = 2.0 / (p + 1)
|
| 89 |
+
e = float(arr[0])
|
| 90 |
+
for v in arr[1:]:
|
| 91 |
+
e = float(v) * k + e * (1.0 - k)
|
| 92 |
+
return e
|
| 93 |
+
|
| 94 |
+
def _score_to_prediction(name: str, score: float, reasoning: str) -> dict:
|
| 95 |
+
direction = "UP" if score > 0.05 else ("DOWN" if score < -0.05 else "NEUTRAL")
|
| 96 |
+
confidence = _clamp(45.0 + abs(score) * 55.0, 40.0, 95.0)
|
| 97 |
+
return {
|
| 98 |
+
"name": name,
|
| 99 |
+
"direction": direction,
|
| 100 |
+
"confidence": round(confidence),
|
| 101 |
+
"slope_pct": round(score * 0.5, 6),
|
| 102 |
+
"reasoning": reasoning,
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 106 |
+
# 35-feature vector (shared by XGBoost and LightGBM)
|
| 107 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 108 |
+
|
| 109 |
+
def _feature_vector(feats: dict, closes: list) -> np.ndarray:
|
| 110 |
+
c = np.array(closes, dtype=np.float64)
|
| 111 |
+
n = len(c)
|
| 112 |
+
|
| 113 |
+
sl3 = _slope(c, min(3, n - 1))
|
| 114 |
+
sl5 = _slope(c, min(5, n - 1))
|
| 115 |
+
sl10 = _slope(c, min(10, n - 1))
|
| 116 |
+
sl20 = _slope(c, min(20, n - 1))
|
| 117 |
+
|
| 118 |
+
e20 = _ema(c[-max(40, 20 * 2):], 20)
|
| 119 |
+
e50 = _ema(c[-max(80, 50 * 2):], min(50, max(n // 2, 5)))
|
| 120 |
+
last = float(c[-1]) if n > 0 else 1.0
|
| 121 |
+
ema_diff = (e20 - e50) / last if last != 0 else 0.0
|
| 122 |
+
|
| 123 |
+
std = float(np.std(c[-20:])) / max(1.0, last) if n >= 5 else 0.0
|
| 124 |
+
|
| 125 |
+
def f(key: str, default: float = 0.0) -> float:
|
| 126 |
+
v = feats.get(key)
|
| 127 |
+
return float(v) if v is not None else default
|
| 128 |
+
|
| 129 |
+
rsi = f("rsi", 50.0)
|
| 130 |
+
cvd = f("cvd", 0.0)
|
| 131 |
+
ob = f("ob_imbal", 0.0)
|
| 132 |
+
fund = f("funding", 0.0)
|
| 133 |
+
tbr = f("taker_buy_ratio", 0.5)
|
| 134 |
+
pyes = f("polymarket_yes", 0.5)
|
| 135 |
+
pdel = f("poly_yes_delta_1m", 0.0)
|
| 136 |
+
fg = f("fear_greed", 50.0)
|
| 137 |
+
dxy = f("dxy_change_pct", 0.0)
|
| 138 |
+
nq = f("nasdaq_fut_change_pct", 0.0)
|
| 139 |
+
etf = f("farside_net_flow_usd", 0.0)
|
| 140 |
+
cbp = f("coinbase_premium_pct", 0.0)
|
| 141 |
+
sk = f("stoch_rsi_k", 50.0)
|
| 142 |
+
vwap = f("vwap_dev", 0.0)
|
| 143 |
+
atr = f("atr_pct_of_spot", 0.5)
|
| 144 |
|
| 145 |
return np.array([
|
| 146 |
+
sl3, sl5, sl10, sl20, ema_diff, std,
|
| 147 |
+
(rsi - 50.0) / 50.0,
|
| 148 |
+
_tanh(cvd / 5e6),
|
| 149 |
+
_tanh(ob * 3.0),
|
| 150 |
+
fund * 1000.0,
|
| 151 |
+
tbr - 0.5,
|
| 152 |
+
pyes - 0.5,
|
| 153 |
+
_tanh(pdel * 20.0),
|
| 154 |
+
(fg - 50.0) / 50.0,
|
| 155 |
+
_tanh(-dxy * 0.5),
|
| 156 |
+
_tanh(nq * 0.5),
|
| 157 |
+
_tanh(etf / 1e8),
|
| 158 |
+
cbp / 0.3,
|
| 159 |
+
(sk - 50.0) / 50.0,
|
| 160 |
+
_tanh(vwap * 0.5),
|
| 161 |
+
1.0 / (1.0 + atr),
|
| 162 |
+
sl3 * sl5,
|
| 163 |
+
sl5 * sl20,
|
| 164 |
+
abs(ema_diff),
|
| 165 |
+
math.copysign(ema_diff ** 2, ema_diff),
|
| 166 |
+
_tanh(cvd / 5e6) * (pyes - 0.5),
|
| 167 |
+
sl20 * (rsi - 50.0) / 50.0,
|
| 168 |
+
max(0.0, sl20),
|
| 169 |
+
min(0.0, sl20),
|
| 170 |
+
(tbr - 0.5) * _tanh(ob * 3.0),
|
| 171 |
+
_tanh((pyes - 0.5) * 5.0),
|
| 172 |
+
fund * _tanh(cvd / 5e6),
|
| 173 |
+
abs(sl5 - sl20),
|
| 174 |
+
_tanh(nq * 0.3) * _tanh(-dxy * 0.3),
|
| 175 |
+
std * abs(ob),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
], dtype=np.float32)
|
| 177 |
|
| 178 |
|
| 179 |
+
def _synthetic_training_data(n_samples: int = 2000):
|
| 180 |
+
"""Bootstrap training set for XGBoost and LightGBM."""
|
| 181 |
+
rng = np.random.default_rng(42)
|
| 182 |
+
X, y = [], []
|
| 183 |
+
|
| 184 |
+
for _ in range(n_samples):
|
| 185 |
+
sl20_s = rng.uniform(-0.03, 0.03)
|
| 186 |
+
rsi_s = rng.uniform(25.0, 75.0)
|
| 187 |
+
cvd_s = rng.uniform(-1e7, 1e7)
|
| 188 |
+
ob_s = rng.uniform(-0.5, 0.5)
|
| 189 |
+
fund_s = rng.uniform(-0.02, 0.02)
|
| 190 |
+
tbr_s = rng.uniform(0.3, 0.7)
|
| 191 |
+
pyes_s = rng.uniform(0.2, 0.8)
|
| 192 |
+
pdel_s = rng.uniform(-0.02, 0.02)
|
| 193 |
+
fg_s = rng.uniform(20.0, 80.0)
|
| 194 |
+
dxy_s = rng.uniform(-0.8, 0.8)
|
| 195 |
+
nq_s = rng.uniform(-1.0, 1.0)
|
| 196 |
+
etf_s = rng.uniform(-5e8, 5e8)
|
| 197 |
+
cbp_s = rng.uniform(-0.5, 0.5)
|
| 198 |
+
sk_s = rng.uniform(10.0, 90.0)
|
| 199 |
+
vwap_s = rng.uniform(-1.0, 1.0)
|
| 200 |
+
atr_s = rng.uniform(0.1, 2.0)
|
| 201 |
+
|
| 202 |
+
trend = rng.choice([-1, 0, 1], p=[0.35, 0.30, 0.35])
|
| 203 |
+
closes = (100.0 + np.cumsum(
|
| 204 |
+
trend * rng.uniform(0, 0.002, 80) + rng.normal(0, 0.001, 80)
|
| 205 |
+
)).tolist()
|
| 206 |
+
|
| 207 |
+
feats = {
|
| 208 |
+
"rsi": rsi_s, "cvd": cvd_s, "ob_imbal": ob_s,
|
| 209 |
+
"funding": fund_s, "taker_buy_ratio": tbr_s,
|
| 210 |
+
"polymarket_yes": pyes_s, "poly_yes_delta_1m": pdel_s,
|
| 211 |
+
"fear_greed": fg_s, "dxy_change_pct": dxy_s,
|
| 212 |
+
"nasdaq_fut_change_pct": nq_s, "farside_net_flow_usd": etf_s,
|
| 213 |
+
"coinbase_premium_pct": cbp_s, "stoch_rsi_k": sk_s,
|
| 214 |
+
"vwap_dev": vwap_s, "atr_pct_of_spot": atr_s,
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
fv = _feature_vector(feats, closes)
|
| 218 |
+
X.append(fv)
|
| 219 |
+
|
| 220 |
+
label_score = (
|
| 221 |
+
sl20_s * 50.0 +
|
| 222 |
+
(rsi_s - 50.0) / 50.0 * 0.30 +
|
| 223 |
+
_tanh(cvd_s / 5e6) * 0.25 +
|
| 224 |
+
_tanh(ob_s * 3.0) * 0.20 +
|
| 225 |
+
(pyes_s - 0.5) * 0.15 +
|
| 226 |
+
_tanh(-dxy_s * 0.5) * 0.10 +
|
| 227 |
+
_tanh(nq_s * 0.5) * 0.10
|
| 228 |
+
)
|
| 229 |
+
y.append(1 if label_score > 0.02 else 0)
|
| 230 |
+
|
| 231 |
+
return np.array(X, dtype=np.float32), np.array(y, dtype=np.int32)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 235 |
+
# Startup — load / bootstrap models
|
| 236 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 237 |
+
|
| 238 |
+
@app.on_event("startup")
|
| 239 |
+
async def startup_event():
|
| 240 |
+
_load_xgboost()
|
| 241 |
+
_load_lgbm()
|
| 242 |
+
_load_chronos()
|
| 243 |
+
_load_moirai()
|
| 244 |
+
_load_moment()
|
| 245 |
+
logger.info("Startup complete. flags=%s", _flags)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _load_xgboost():
|
| 249 |
+
try:
|
| 250 |
+
import xgboost as xgb # type: ignore
|
| 251 |
+
path = os.environ.get("XGB_MODEL_PATH", "/app/xgb_model.json")
|
| 252 |
+
if os.path.exists(path):
|
| 253 |
+
clf = xgb.XGBClassifier()
|
| 254 |
+
clf.load_model(path)
|
| 255 |
+
logger.info("XGBoost loaded from %s", path)
|
| 256 |
+
else:
|
| 257 |
+
logger.info("XGBoost: bootstrap training…")
|
| 258 |
+
X, y = _synthetic_training_data(2000)
|
| 259 |
+
clf = xgb.XGBClassifier(
|
| 260 |
+
n_estimators=150, max_depth=5, learning_rate=0.07,
|
| 261 |
+
subsample=0.8, colsample_bytree=0.8, min_child_weight=3,
|
| 262 |
+
gamma=0.1, reg_alpha=0.1, reg_lambda=1.0,
|
| 263 |
+
eval_metric="logloss", random_state=42, n_jobs=2,
|
| 264 |
+
use_label_encoder=False,
|
| 265 |
+
)
|
| 266 |
+
clf.fit(X, y)
|
| 267 |
+
logger.info("XGBoost: bootstrap trained")
|
| 268 |
+
_models["xgboost"] = clf
|
| 269 |
+
_flags["xgboost"] = True
|
| 270 |
+
except Exception as exc:
|
| 271 |
+
logger.warning("XGBoost unavailable: %s", exc)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def _load_lgbm():
|
| 275 |
+
try:
|
| 276 |
+
import lightgbm as lgb # type: ignore
|
| 277 |
+
import pickle
|
| 278 |
+
|
| 279 |
+
path = os.environ.get("LGBM_MODEL_PATH", "/app/lgbm_model.pkl")
|
| 280 |
+
if os.path.exists(path):
|
| 281 |
+
with open(path, "rb") as fh:
|
| 282 |
+
clf = pickle.load(fh)
|
| 283 |
+
logger.info("LightGBM loaded from %s", path)
|
| 284 |
+
else:
|
| 285 |
+
logger.info("LightGBM: bootstrap training…")
|
| 286 |
+
X, y = _synthetic_training_data(2000)
|
| 287 |
+
clf = lgb.LGBMClassifier(
|
| 288 |
+
n_estimators=150, max_depth=5, learning_rate=0.07,
|
| 289 |
+
subsample=0.8, colsample_bytree=0.8,
|
| 290 |
+
class_weight="balanced", random_state=42,
|
| 291 |
+
n_jobs=2, verbose=-1,
|
| 292 |
+
)
|
| 293 |
+
clf.fit(X, y)
|
| 294 |
+
logger.info("LightGBM: bootstrap trained")
|
| 295 |
+
_models["lgbm"] = clf
|
| 296 |
+
_flags["lgbm"] = True
|
| 297 |
+
except Exception as exc:
|
| 298 |
+
logger.warning("LightGBM unavailable: %s", exc)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def _load_chronos():
|
| 302 |
+
try:
|
| 303 |
+
# Use tiny variant to fit in HF free tier RAM
|
| 304 |
+
from chronos import ChronosPipeline # type: ignore
|
| 305 |
+
import torch
|
| 306 |
+
model_name = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-tiny")
|
| 307 |
+
logger.info("Chronos: loading %s …", model_name)
|
| 308 |
+
pipe = ChronosPipeline.from_pretrained(
|
| 309 |
+
model_name,
|
| 310 |
+
device_map="cpu",
|
| 311 |
+
torch_dtype=torch.float32,
|
| 312 |
+
)
|
| 313 |
+
_models["chronos"] = pipe
|
| 314 |
+
_flags["chronos"] = True
|
| 315 |
+
logger.info("Chronos loaded ✓")
|
| 316 |
+
except Exception as exc:
|
| 317 |
+
logger.warning("Chronos not loaded: %s", exc)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _load_moirai():
|
| 321 |
+
try:
|
| 322 |
+
from uni2ts.model.moirai import MoiraiForecast, MoiraiModule # type: ignore
|
| 323 |
+
model_name = os.environ.get("MOIRAI_MODEL", "Salesforce/moirai-1.1-R-small")
|
| 324 |
+
logger.info("MOIRAI: loading %s …", model_name)
|
| 325 |
+
moirai = MoiraiForecast.load_from_checkpoint(
|
| 326 |
+
prediction_length=2,
|
| 327 |
+
context_length=64,
|
| 328 |
+
patch_size="auto",
|
| 329 |
+
num_samples=32,
|
| 330 |
+
target_dim=1,
|
| 331 |
+
feat_dynamic_real_dim=0,
|
| 332 |
+
past_feat_dynamic_real_dim=0,
|
| 333 |
+
module=MoiraiModule.from_pretrained(model_name),
|
| 334 |
+
)
|
| 335 |
+
_models["moirai"] = moirai
|
| 336 |
+
_flags["moirai"] = True
|
| 337 |
+
logger.info("MOIRAI loaded ✓")
|
| 338 |
+
except Exception as exc:
|
| 339 |
+
logger.warning("MOIRAI not loaded: %s", exc)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _load_moment():
|
| 343 |
+
try:
|
| 344 |
+
from momentfm import MOMENTPipeline # type: ignore
|
| 345 |
+
model_name = os.environ.get("MOMENT_MODEL", "AutonLab/MOMENT-1-large")
|
| 346 |
+
logger.info("MOMENT: loading %s …", model_name)
|
| 347 |
+
pipe = MOMENTPipeline.from_pretrained(
|
| 348 |
+
model_name,
|
| 349 |
+
model_kwargs={"task_name": "classification", "n_channels": 1, "num_class": 2},
|
| 350 |
+
)
|
| 351 |
+
pipe.init()
|
| 352 |
+
_models["moment"] = pipe
|
| 353 |
+
_flags["moment"] = True
|
| 354 |
+
logger.info("MOMENT loaded ✓")
|
| 355 |
+
except Exception as exc:
|
| 356 |
+
logger.warning("MOMENT not loaded: %s", exc)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 360 |
+
# Model inference — bootstrap formulas (always safe)
|
| 361 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 362 |
+
|
| 363 |
+
def _predict_chronos_bootstrap(closes: list, feats: dict) -> dict:
|
| 364 |
+
c = np.array(closes, dtype=np.float64)
|
| 365 |
+
n = len(c)
|
| 366 |
+
last = float(c[-1]) if n > 0 else 1.0
|
| 367 |
+
e20 = _ema(c[-max(40, n):], 20)
|
| 368 |
+
e50 = _ema(c[-max(80, n):], min(50, max(n // 2, 5)))
|
| 369 |
+
sl20 = _slope(c, min(20, n - 1))
|
| 370 |
+
rsi = float(feats.get("rsi") or 50.0)
|
| 371 |
+
|
| 372 |
score = (
|
| 373 |
+
math.copysign(min(1.0, abs(sl20) * 150.0), sl20) * 0.45 +
|
| 374 |
+
math.copysign(min(1.0, abs((e20 - e50) / last) * 200.0), (e20 - e50)) * 0.35 +
|
| 375 |
+
((rsi - 50.0) / 50.0) * 0.20
|
| 376 |
)
|
| 377 |
+
return _score_to_prediction(
|
| 378 |
+
"Chronos", score,
|
| 379 |
+
f"Chronos bootstrap: sl20={sl20*100:.4f}% ema_diff={((e20-e50)/last)*100:.4f}%",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
)
|
| 381 |
|
| 382 |
|
| 383 |
+
def _predict_moirai_bootstrap(closes: list, feats: dict) -> dict:
|
| 384 |
+
c = np.array(closes, dtype=np.float64)
|
| 385 |
+
n = len(c)
|
| 386 |
+
sl20 = _slope(c, min(20, n - 1))
|
| 387 |
+
rsi = float(feats.get("rsi") or 50.0)
|
| 388 |
+
mean_rev = -_tanh(sl20 * 100.0 / 0.3) * 0.15
|
| 389 |
+
|
| 390 |
+
score = (
|
| 391 |
+
math.copysign(min(1.0, abs(sl20) * 30.0), sl20) * 0.40 +
|
| 392 |
+
((rsi - 50.0) / 50.0) * 0.30 +
|
| 393 |
+
mean_rev
|
| 394 |
)
|
| 395 |
+
return _score_to_prediction(
|
| 396 |
+
"MOIRAI", score,
|
| 397 |
+
f"MOIRAI bootstrap: sl20={sl20*100:.4f}% rsi={rsi:.1f}",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
)
|
| 399 |
|
| 400 |
|
| 401 |
+
def _predict_moment_bootstrap(closes: list, feats: dict) -> dict:
|
| 402 |
+
c = np.array(closes, dtype=np.float64)
|
| 403 |
+
n = len(c)
|
| 404 |
+
last = float(c[-1]) if n > 0 else 1.0
|
| 405 |
+
e20 = _ema(c[-max(40, n):], 20)
|
| 406 |
+
e50 = _ema(c[-max(80, n):], min(50, max(n // 2, 5)))
|
| 407 |
+
sl20 = _slope(c, min(20, n - 1))
|
| 408 |
+
rsi = float(feats.get("rsi") or 50.0)
|
| 409 |
+
|
| 410 |
+
score = (
|
| 411 |
+
math.copysign(min(1.0, abs((e20 - e50) / last) * 250.0), (e20 - e50)) * 0.50 +
|
| 412 |
+
math.copysign(min(1.0, abs(sl20) * 140.0), sl20) * 0.30 +
|
| 413 |
+
((rsi - 50.0) / 50.0) * 0.20
|
| 414 |
+
)
|
| 415 |
+
return _score_to_prediction(
|
| 416 |
+
"MOMENT", score,
|
| 417 |
+
f"MOMENT bootstrap: ema_diff={((e20-e50)/last)*100:.4f}% sl20={sl20*100:.4f}%",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
)
|
| 419 |
|
| 420 |
|
| 421 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 422 |
+
# Model inference — real transformer inference (when loaded)
|
| 423 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
+
def _predict_chronos_real(closes: list, feats: dict) -> dict:
|
| 426 |
+
import torch
|
| 427 |
+
pipe = _models["chronos"]
|
| 428 |
+
c = np.array(closes[-64:], dtype=np.float32)
|
| 429 |
+
context = torch.tensor(c).unsqueeze(0) # (1, T)
|
| 430 |
+
with torch.no_grad():
|
| 431 |
+
forecast = pipe.predict(context, prediction_length=2) # (samples, 1, 2)
|
| 432 |
+
median = float(forecast[0].median(dim=0).values.mean().item())
|
| 433 |
+
last = float(c[-1])
|
| 434 |
+
score = _tanh((median / last - 1.0) * 20.0) if last != 0 else 0.0
|
| 435 |
+
return _score_to_prediction(
|
| 436 |
+
"Chronos", score,
|
| 437 |
+
f"Chronos T5: median={median:.2f} last={last:.2f}",
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def _predict_moirai_real(closes: list, feats: dict) -> dict:
|
| 442 |
+
import torch
|
| 443 |
+
moirai = _models["moirai"]
|
| 444 |
+
c = np.array(closes[-64:], dtype=np.float32)
|
| 445 |
+
context = torch.tensor(c).unsqueeze(0).unsqueeze(0) # (1, 1, T)
|
| 446 |
+
with torch.no_grad():
|
| 447 |
+
samples = moirai(context) # (num_samples, 1, prediction_length)
|
| 448 |
+
median = float(torch.median(samples).item())
|
| 449 |
+
last = float(c[-1])
|
| 450 |
+
score = _tanh((median / last - 1.0) * 20.0) if last != 0 else 0.0
|
| 451 |
+
return _score_to_prediction(
|
| 452 |
+
"MOIRAI", score,
|
| 453 |
+
f"MOIRAI: median_pred={median:.2f} last={last:.2f}",
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def _predict_moment_real(closes: list, feats: dict) -> dict:
|
| 458 |
+
import torch
|
| 459 |
+
pipe = _models["moment"]
|
| 460 |
+
c = np.array(closes[-512:], dtype=np.float32)
|
| 461 |
+
c_norm = (c - c.mean()) / (c.std() + 1e-8)
|
| 462 |
+
inp = torch.tensor(c_norm).unsqueeze(0).unsqueeze(0) # (1, 1, T)
|
| 463 |
+
with torch.no_grad():
|
| 464 |
+
out = pipe(inp)
|
| 465 |
+
logits = out.logits if hasattr(out, "logits") else out
|
| 466 |
+
prob = float(torch.softmax(logits[0], dim=-1)[1].item())
|
| 467 |
+
score = (prob - 0.5) * 2.0
|
| 468 |
+
return _score_to_prediction(
|
| 469 |
+
"MOMENT", score,
|
| 470 |
+
f"MOMENT: P(UP)={prob:.4f}",
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 475 |
+
# Model inference — trained classifiers
|
| 476 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 477 |
+
|
| 478 |
+
def _predict_xgboost(closes: list, feats: dict) -> dict:
|
| 479 |
+
clf = _models.get("xgboost")
|
| 480 |
+
if clf is None:
|
| 481 |
+
return _predict_chronos_bootstrap(closes, feats)
|
| 482 |
+
try:
|
| 483 |
+
fv = _feature_vector(feats, closes).reshape(1, -1)
|
| 484 |
+
prob = float(clf.predict_proba(fv)[0][1])
|
| 485 |
+
score = (prob - 0.5) * 2.0
|
| 486 |
+
direction = "UP" if prob > 0.55 else ("DOWN" if prob < 0.45 else "NEUTRAL")
|
| 487 |
+
return {
|
| 488 |
+
"name": "XGBoost",
|
| 489 |
+
"direction": direction,
|
| 490 |
+
"confidence": _clamp(round(45.0 + abs(score) * 50.0), 40, 95),
|
| 491 |
+
"slope_pct": round(score * 0.5, 6),
|
| 492 |
+
"reasoning": f"XGB: P(UP)={prob:.4f} pyes={feats.get('polymarket_yes', 0.5):.3f}",
|
| 493 |
+
}
|
| 494 |
+
except Exception as exc:
|
| 495 |
+
logger.warning("XGBoost inference error: %s", exc)
|
| 496 |
+
return _predict_chronos_bootstrap(closes, feats)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def _predict_lightgbm(closes: list, feats: dict) -> dict:
|
| 500 |
+
clf = _models.get("lgbm")
|
| 501 |
+
if clf is None:
|
| 502 |
+
return _predict_moirai_bootstrap(closes, feats)
|
| 503 |
+
try:
|
| 504 |
+
fv = _feature_vector(feats, closes).reshape(1, -1)
|
| 505 |
+
prob = float(clf.predict_proba(fv)[0][1])
|
| 506 |
+
score = (prob - 0.5) * 2.0
|
| 507 |
+
direction = "UP" if prob > 0.55 else ("DOWN" if prob < 0.45 else "NEUTRAL")
|
| 508 |
+
return {
|
| 509 |
+
"name": "LightGBM",
|
| 510 |
+
"direction": direction,
|
| 511 |
+
"confidence": _clamp(round(45.0 + abs(score) * 50.0), 40, 95),
|
| 512 |
+
"slope_pct": round(score * 0.5, 6),
|
| 513 |
+
"reasoning": f"LGBM: P(UP)={prob:.4f} pyes={feats.get('polymarket_yes', 0.5):.3f}",
|
| 514 |
+
}
|
| 515 |
+
except Exception as exc:
|
| 516 |
+
logger.warning("LightGBM inference error: %s", exc)
|
| 517 |
+
return _predict_moirai_bootstrap(closes, feats)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 521 |
+
# Model inference — signal models (formula, always available)
|
| 522 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 523 |
+
|
| 524 |
+
def _predict_lag_llama(closes: list, feats: dict) -> dict:
|
| 525 |
+
"""Lag-Llama — probabilistic AR proxy blended with polymarket_yes (v17 fix)."""
|
| 526 |
+
c = np.array(closes, dtype=np.float64)
|
| 527 |
+
n = len(c)
|
| 528 |
+
sl20 = _slope(c, min(20, n - 1))
|
| 529 |
+
sl5 = _slope(c, min(5, n - 1))
|
| 530 |
+
pyes = float(feats.get("polymarket_yes") or 0.5)
|
| 531 |
+
pdel = float(feats.get("poly_yes_delta_1m") or 0.0)
|
| 532 |
+
|
| 533 |
+
score = (
|
| 534 |
+
math.copysign(min(1.0, abs(sl20) * 90.0), sl20) * 0.45 +
|
| 535 |
+
math.copysign(min(1.0, abs(sl5) * 120.0), sl5) * 0.25 +
|
| 536 |
+
_tanh((pyes - 0.5) * 6.0) * 0.20 +
|
| 537 |
+
_tanh(pdel * 20.0) * 0.10
|
| 538 |
+
)
|
| 539 |
+
return _score_to_prediction(
|
| 540 |
+
"Lag-Llama", score,
|
| 541 |
+
f"LagLlama: sl20={sl20*100:.4f}% sl5={sl5*100:.4f}% pyes={pyes:.3f} pdel={pdel:.4f}",
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def _predict_dag(feats: dict) -> dict:
|
| 546 |
+
"""DAG — Directed Acyclic Graph orderflow formula.
|
| 547 |
+
v17 fix: now consumes polymarket_yes (was missing before)."""
|
| 548 |
+
cvd = float(feats.get("cvd") or 0.0)
|
| 549 |
+
ob = float(feats.get("ob_imbal") or 0.0)
|
| 550 |
+
fund = float(feats.get("funding") or 0.0)
|
| 551 |
+
tbr = float(feats.get("taker_buy_ratio") or 0.5)
|
| 552 |
+
bid = float(feats.get("bid_vol_top20") or 1.0)
|
| 553 |
+
ask = float(feats.get("ask_vol_top20") or 1.0)
|
| 554 |
+
pyes = float(feats.get("polymarket_yes") or 0.5)
|
| 555 |
+
pdel = float(feats.get("poly_yes_delta_1m") or 0.0)
|
| 556 |
+
|
| 557 |
+
score = (
|
| 558 |
+
_tanh(cvd / 5e6) * 0.30 +
|
| 559 |
+
_tanh(ob * 3.0) * 0.25 +
|
| 560 |
+
(tbr - 0.5) * 0.15 +
|
| 561 |
+
(math.copysign(0.08, -fund) if abs(fund) > 0.005 else 0.0) +
|
| 562 |
+
(_tanh((bid - ask) / max(bid + ask, 0.001)) * 0.07) +
|
| 563 |
+
# v17 polymarket fix ↓
|
| 564 |
+
_tanh((pyes - 0.5) * 5.0) * 0.12 +
|
| 565 |
+
_tanh(pdel * 20.0) * 0.03
|
| 566 |
+
)
|
| 567 |
+
return _score_to_prediction(
|
| 568 |
+
"DAG", score,
|
| 569 |
+
f"DAG: cvd={cvd/1e6:.1f}M ob={ob:.3f} taker={tbr:.3f} pyes={pyes:.3f}",
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def _predict_tide(feats: dict) -> dict:
|
| 574 |
+
"""TiDE — Time-series Dense Encoder macro formula.
|
| 575 |
+
v17 fix: now consumes polymarket_yes (was missing before)."""
|
| 576 |
+
dxy = float(feats.get("dxy_change_pct") or 0.0)
|
| 577 |
+
nq = float(feats.get("nasdaq_fut_change_pct") or 0.0)
|
| 578 |
+
fund = float(feats.get("funding") or 0.0)
|
| 579 |
+
etf = float(feats.get("farside_net_flow_usd") or 0.0)
|
| 580 |
+
fg = float(feats.get("fear_greed") or 50.0)
|
| 581 |
+
pyes = float(feats.get("polymarket_yes") or 0.5)
|
| 582 |
+
pdel = float(feats.get("poly_yes_delta_1m") or 0.0)
|
| 583 |
+
btcd = float(feats.get("btc_dom") or 50.0)
|
| 584 |
+
|
| 585 |
+
score = (
|
| 586 |
+
_tanh(-dxy * 0.6) * 0.22 + # DXY inverse
|
| 587 |
+
_tanh(nq * 0.6) * 0.18 + # NQ positive correlation
|
| 588 |
+
_tanh(etf / 1e8) * 0.14 + # ETF flow
|
| 589 |
+
(math.copysign(0.08, -fund) if abs(fund) > 0.005 else 0.0) +
|
| 590 |
+
((fg - 50.0) / 50.0) * 0.08 + # F&G
|
| 591 |
+
((btcd - 50.0) / 50.0) * 0.03 + # BTC dominance
|
| 592 |
+
# v17 polymarket fix ↓
|
| 593 |
+
_tanh((pyes - 0.5) * 5.0) * 0.12 +
|
| 594 |
+
_tanh(pdel * 20.0) * 0.03
|
| 595 |
+
)
|
| 596 |
+
return _score_to_prediction(
|
| 597 |
+
"TiDE", score,
|
| 598 |
+
f"TiDE: dxy={dxy:.2f}% nq={nq:.2f}% etf={etf/1e6:.0f}M pyes={pyes:.3f}",
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 603 |
+
# Ensemble aggregation
|
| 604 |
+
# ───────────────────────────────────────────────────────────────────���─────────
|
| 605 |
+
|
| 606 |
+
def _aggregate(predictions: list) -> dict:
|
| 607 |
+
up_w = dn_w = total_w = 0.0
|
| 608 |
+
|
| 609 |
+
for p in predictions:
|
| 610 |
+
conf = p["confidence"] / 100.0
|
| 611 |
+
w = WEIGHTS.get(p["name"], 0.05) * conf
|
| 612 |
+
if p["direction"] == "UP":
|
| 613 |
+
up_w += w
|
| 614 |
+
elif p["direction"] == "DOWN":
|
| 615 |
+
dn_w += w
|
| 616 |
+
total_w += w
|
| 617 |
+
|
| 618 |
+
if total_w == 0:
|
| 619 |
+
return dict(
|
| 620 |
+
composite_direction="NEUTRAL",
|
| 621 |
+
composite_confidence=50,
|
| 622 |
+
composite_score=0.0,
|
| 623 |
+
models=predictions,
|
| 624 |
+
is_local_fallback=False,
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
if up_w > dn_w:
|
| 628 |
+
comp_dir = "UP"
|
| 629 |
+
win_preds = [p for p in predictions if p["direction"] == "UP"]
|
| 630 |
+
elif dn_w > up_w:
|
| 631 |
+
comp_dir = "DOWN"
|
| 632 |
+
win_preds = [p for p in predictions if p["direction"] == "DOWN"]
|
| 633 |
+
else:
|
| 634 |
+
comp_dir = "NEUTRAL"
|
| 635 |
+
win_preds = []
|
| 636 |
+
|
| 637 |
+
margin = abs(up_w - dn_w) / total_w
|
| 638 |
+
avg_conf = (
|
| 639 |
+
sum(p["confidence"] for p in win_preds) / len(win_preds)
|
| 640 |
+
if win_preds else 50.0
|
| 641 |
+
)
|
| 642 |
+
margin_boost = min(margin * 100.0, 10.0)
|
| 643 |
+
comp_conf = int(_clamp(avg_conf + margin_boost, 45.0, 95.0))
|
| 644 |
+
comp_score = round((up_w - dn_w) / total_w, 6)
|
| 645 |
+
|
| 646 |
+
return dict(
|
| 647 |
+
composite_direction=comp_dir,
|
| 648 |
+
composite_confidence=comp_conf,
|
| 649 |
+
composite_score=comp_score,
|
| 650 |
+
models=predictions,
|
| 651 |
+
is_local_fallback=False,
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 656 |
+
# Endpoints
|
| 657 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 658 |
|
| 659 |
@app.get("/")
|
| 660 |
+
async def health_check():
|
| 661 |
return {
|
| 662 |
+
"ok": True,
|
| 663 |
+
"version": "17.0.0",
|
| 664 |
+
"chronos": _flags["chronos"],
|
| 665 |
+
"moirai": _flags["moirai"],
|
| 666 |
+
"moment": _flags["moment"],
|
| 667 |
+
"xgboost": _flags["xgboost"],
|
| 668 |
+
"lgbm": _flags["lgbm"],
|
| 669 |
+
"lag_llama": _flags["lag_llama"],
|
| 670 |
+
"dag": _flags["dag"],
|
| 671 |
+
"tide": _flags["tide"],
|
| 672 |
+
"models": ["MOIRAI", "Chronos", "MOMENT", "XGBoost", "LightGBM",
|
| 673 |
+
"Lag-Llama", "DAG", "TiDE"],
|
| 674 |
"polymarket_fix": "DAG+TiDE+LagLlama now consume polymarket_yes",
|
| 675 |
"removed": ["TabPFN-TS", "PatchTST", "N-BEATS", "AROpt"],
|
| 676 |
"hf_space": True,
|
| 677 |
}
|
| 678 |
|
| 679 |
|
| 680 |
+
@app.post("/omega")
|
| 681 |
+
async def omega(request: Request):
|
| 682 |
+
t0 = time.perf_counter()
|
| 683 |
+
body = await request.json()
|
| 684 |
+
|
| 685 |
+
closes = list(body.get("closes") or [])
|
| 686 |
+
if len(closes) < 16:
|
| 687 |
+
return JSONResponse(
|
| 688 |
+
status_code=422,
|
| 689 |
+
content={"error": "closes array too short — need at least 16 values"},
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
# All keys except closes become the feature dict
|
| 693 |
+
feats = {k: v for k, v in body.items() if k != "closes"}
|
| 694 |
+
|
| 695 |
+
predictions: list = []
|
| 696 |
+
|
| 697 |
+
# ── ROW 1: Foundation Models ────────────────────────────────────────────
|
| 698 |
+
if _flags["moirai"] and "moirai" in _models:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 699 |
try:
|
| 700 |
+
predictions.append(_predict_moirai_real(closes, feats))
|
| 701 |
+
except Exception as exc:
|
| 702 |
+
logger.warning("MOIRAI real inference failed: %s", exc)
|
| 703 |
+
predictions.append(_predict_moirai_bootstrap(closes, feats))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 704 |
else:
|
| 705 |
+
predictions.append(_predict_moirai_bootstrap(closes, feats))
|
|
|
|
| 706 |
|
| 707 |
+
if _flags["chronos"] and "chronos" in _models:
|
| 708 |
+
try:
|
| 709 |
+
predictions.append(_predict_chronos_real(closes, feats))
|
| 710 |
+
except Exception as exc:
|
| 711 |
+
logger.warning("Chronos real inference failed: %s", exc)
|
| 712 |
+
predictions.append(_predict_chronos_bootstrap(closes, feats))
|
| 713 |
+
else:
|
| 714 |
+
predictions.append(_predict_chronos_bootstrap(closes, feats))
|
| 715 |
+
|
| 716 |
+
if _flags["moment"] and "moment" in _models:
|
| 717 |
+
try:
|
| 718 |
+
predictions.append(_predict_moment_real(closes, feats))
|
| 719 |
+
except Exception as exc:
|
| 720 |
+
logger.warning("MOMENT real inference failed: %s", exc)
|
| 721 |
+
predictions.append(_predict_moment_bootstrap(closes, feats))
|
| 722 |
+
else:
|
| 723 |
+
predictions.append(_predict_moment_bootstrap(closes, feats))
|
| 724 |
+
|
| 725 |
+
# ── ROW 2: Trained Classifiers ───────────────────────────────────────────
|
| 726 |
+
predictions.append(_predict_xgboost(closes, feats))
|
| 727 |
+
predictions.append(_predict_lightgbm(closes, feats))
|
| 728 |
+
|
| 729 |
+
# ── ROW 3: Signal Models (formula, polymarket_yes consumed by all three) ──
|
| 730 |
+
predictions.append(_predict_lag_llama(closes, feats))
|
| 731 |
+
predictions.append(_predict_dag(feats))
|
| 732 |
+
predictions.append(_predict_tide(feats))
|
| 733 |
+
|
| 734 |
+
result = _aggregate(predictions)
|
| 735 |
+
result["latency_ms"] = round((time.perf_counter() - t0) * 1000)
|
| 736 |
+
return result
|