Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,53 +1,13 @@
|
|
| 1 |
"""
|
| 2 |
-
PolyBloom ML Service — v20.0
|
| 3 |
-
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
ROW 2 TRAINED XGBoost · LightGBM · CatBoost (bootstrap train on startup)
|
| 8 |
-
ROW 3 NEURAL-TS PatchTST · N-HiTS · iTransformer (NeuralForecast)
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
- REMOVED: Lag-Llama (LLM for TS, CPU timeout)
|
| 14 |
-
- REMOVED: N-BEATS (NeuralForecast NBEATS OOM on free HF tier; dropped)
|
| 15 |
-
- REMOVED: DAG (moved to frontend)
|
| 16 |
-
- REMOVED: TiDE (moved to frontend)
|
| 17 |
-
- Health endpoint now returns clean booleans only
|
| 18 |
-
- NeuralForecast returns boolean (not string)
|
| 19 |
-
- Reduced ensemble to 6 high-quality models for CPU inference
|
| 20 |
-
- Updated weights renormalized for 6-model ensemble
|
| 21 |
-
|
| 22 |
-
v19.1 changes:
|
| 23 |
-
- ADDED: CatBoost classifier (bootstrap-trained alongside XGBoost/LightGBM)
|
| 24 |
-
- Health endpoint now emits "catboost" boolean
|
| 25 |
-
- Ensemble expanded to 7 models; weights renormalized
|
| 26 |
-
|
| 27 |
-
v19.2 changes (dynamic reweighting):
|
| 28 |
-
- ADDED: in-memory win/loss tracker (_win_stats) per model
|
| 29 |
-
- ADDED: _effective_weight() — blends static base weight with rolling win-rate
|
| 30 |
-
- _aggregate() now uses dynamic weights; same API surface, richer internals
|
| 31 |
-
- ADDED: POST /record_outcome — call after each resolved prediction
|
| 32 |
-
- ADDED: GET /model_stats — returns per-model wins/losses/win_rate/weight
|
| 33 |
-
- No schema changes to /omega response; new field "dynamic_weights" appended
|
| 34 |
-
|
| 35 |
-
v20.0 changes (MiroFish role specialisation):
|
| 36 |
-
- ADDED: _price_memory_feats() — Chronos, PatchTST, N-HiTS see closes only
|
| 37 |
-
(RSI allowed as a price-derived indicator; no orderflow/sentiment)
|
| 38 |
-
- ADDED: _orderflow_feats() — XGBoost, CatBoost, iTransformer see CVD,
|
| 39 |
-
OB imbalance, taker buy ratio, funding, coinbase premium;
|
| 40 |
-
price slope included as context only (no sentiment/polymarket)
|
| 41 |
-
- ADDED: _sentiment_feats() — LightGBM sees polymarket_yes, fear_greed,
|
| 42 |
-
sentiment_polarity, DXY, NASDAQ, ETF flows; no raw orderflow
|
| 43 |
-
- Each model's _predict_* function now receives a role-filtered feats dict
|
| 44 |
-
- ADDED: _tier_verdict() helper — aggregates a tier's model predictions
|
| 45 |
-
- _aggregate() now computes and returns tier_verdicts + tier_agreement
|
| 46 |
-
- tier_agreement values: ALL_AGREE / 2_OF_3 / SPLIT / CONFLICT
|
| 47 |
-
- No existing API fields removed; all new fields are additive
|
| 48 |
-
|
| 49 |
-
Health endpoint GET /
|
| 50 |
-
Omega endpoint POST /omega
|
| 51 |
"""
|
| 52 |
|
| 53 |
import os
|
|
@@ -55,99 +15,23 @@ import math
|
|
| 55 |
import time
|
| 56 |
import logging
|
| 57 |
import numpy as np
|
| 58 |
-
import pandas as pd
|
| 59 |
-
from typing import Optional
|
| 60 |
|
| 61 |
from fastapi import FastAPI, Request
|
| 62 |
from fastapi.middleware.cors import CORSMiddleware
|
| 63 |
from fastapi.responses import JSONResponse
|
| 64 |
|
| 65 |
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
|
| 66 |
-
logger = logging.getLogger("
|
| 67 |
-
|
| 68 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 69 |
-
# App
|
| 70 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 71 |
|
| 72 |
-
app = FastAPI(title="PolyBloom
|
| 73 |
-
app.add_middleware(
|
| 74 |
-
CORSMiddleware,
|
| 75 |
-
allow_origins=["*"],
|
| 76 |
-
allow_methods=["*"],
|
| 77 |
-
allow_headers=["*"],
|
| 78 |
-
)
|
| 79 |
|
| 80 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 81 |
# Global state
|
| 82 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
"xgboost": False,
|
| 87 |
-
"lgbm": False,
|
| 88 |
-
"catboost": False,
|
| 89 |
-
"patchtst": False,
|
| 90 |
-
"nhits": False,
|
| 91 |
-
"itransformer": False,
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
_models: dict = {} # name → loaded object
|
| 95 |
-
|
| 96 |
-
# Weights — renormalized for 7 models (v19.1)
|
| 97 |
-
# These are BASE weights. At runtime _effective_weight() blends them with
|
| 98 |
-
# the rolling win-rate once a model has enough recorded outcomes.
|
| 99 |
-
WEIGHTS = {
|
| 100 |
-
"Chronos": 0.20,
|
| 101 |
-
"XGBoost": 0.18,
|
| 102 |
-
"LightGBM": 0.16,
|
| 103 |
-
"CatBoost": 0.14,
|
| 104 |
-
"PatchTST": 0.13,
|
| 105 |
-
"N-HiTS": 0.11,
|
| 106 |
-
"iTransformer": 0.08,
|
| 107 |
-
}
|
| 108 |
-
|
| 109 |
-
# ── Dynamic win/loss tracker (in-memory, resets on pod restart) ───────────────
|
| 110 |
-
# Structure: { model_name: {"wins": int, "losses": int} }
|
| 111 |
-
# Populated by POST /record_outcome. Used by _effective_weight().
|
| 112 |
-
_win_stats: dict = {name: {"wins": 0, "losses": 0} for name in WEIGHTS}
|
| 113 |
-
|
| 114 |
-
# Minimum resolved predictions before we start trusting win-rate over base weight.
|
| 115 |
-
# Below this threshold the model uses its full base weight (no penalty/boost).
|
| 116 |
-
_WIN_STATS_MIN_SAMPLES = 10
|
| 117 |
-
|
| 118 |
-
# How much the win-rate can shift a model's weight.
|
| 119 |
-
# At 60% win-rate → +20% boost. At 40% → -20% penalty. Capped at ±30%.
|
| 120 |
-
_WIN_RATE_SCALE = 0.6 # multiplier on (win_rate - 0.5)
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def _effective_weight(name: str) -> float:
|
| 124 |
-
"""
|
| 125 |
-
Blends the static base weight with recent win-rate performance.
|
| 126 |
-
|
| 127 |
-
Formula:
|
| 128 |
-
adj = clamp((win_rate - 0.5) * WIN_RATE_SCALE, -0.30, +0.30)
|
| 129 |
-
effective = base_weight * (1 + adj)
|
| 130 |
-
|
| 131 |
-
Below MIN_SAMPLES the adjustment is linearly ramped in so early noise
|
| 132 |
-
doesn't over-penalise a model in its first few predictions.
|
| 133 |
-
"""
|
| 134 |
-
base = WEIGHTS.get(name, 0.10)
|
| 135 |
-
stats = _win_stats.get(name)
|
| 136 |
-
if not stats:
|
| 137 |
-
return base
|
| 138 |
-
|
| 139 |
-
total = stats["wins"] + stats["losses"]
|
| 140 |
-
if total == 0:
|
| 141 |
-
return base
|
| 142 |
-
|
| 143 |
-
win_rate = stats["wins"] / total
|
| 144 |
-
raw_adj = _clamp((win_rate - 0.5) * _WIN_RATE_SCALE, -0.30, 0.30)
|
| 145 |
-
|
| 146 |
-
# Ramp: blend in adjustment gradually up to MIN_SAMPLES
|
| 147 |
-
ramp = min(1.0, total / _WIN_STATS_MIN_SAMPLES)
|
| 148 |
-
adj = raw_adj * ramp
|
| 149 |
-
|
| 150 |
-
return max(0.01, base * (1.0 + adj))
|
| 151 |
|
| 152 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 153 |
# Helpers
|
|
@@ -172,895 +56,114 @@ def _ema(arr: np.ndarray, p: int) -> float:
|
|
| 172 |
e = float(v) * k + e * (1.0 - k)
|
| 173 |
return e
|
| 174 |
|
| 175 |
-
def _score_to_prediction(
|
| 176 |
-
direction
|
| 177 |
confidence = _clamp(45.0 + abs(score) * 55.0, 40.0, 95.0)
|
| 178 |
return {
|
| 179 |
-
"name":
|
| 180 |
"direction": direction,
|
| 181 |
"confidence": round(confidence),
|
| 182 |
"slope_pct": round(score * 0.5, 6),
|
| 183 |
"reasoning": reasoning,
|
|
|
|
| 184 |
}
|
| 185 |
|
| 186 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 187 |
-
#
|
| 188 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 189 |
-
|
| 190 |
-
def _feature_vector(feats: dict, closes: list) -> np.ndarray:
|
| 191 |
-
c = np.array(closes, dtype=np.float64)
|
| 192 |
-
n = len(c)
|
| 193 |
-
|
| 194 |
-
sl3 = _slope(c, min(3, n - 1))
|
| 195 |
-
sl5 = _slope(c, min(5, n - 1))
|
| 196 |
-
sl10 = _slope(c, min(10, n - 1))
|
| 197 |
-
sl20 = _slope(c, min(20, n - 1))
|
| 198 |
-
|
| 199 |
-
e20 = _ema(c[-max(40, 20 * 2):], 20)
|
| 200 |
-
e50 = _ema(c[-max(80, 50 * 2):], min(50, max(n // 2, 5)))
|
| 201 |
-
last = float(c[-1]) if n > 0 else 1.0
|
| 202 |
-
ema_diff = (e20 - e50) / last if last != 0 else 0.0
|
| 203 |
-
|
| 204 |
-
std = float(np.std(c[-20:])) / max(1.0, last) if n >= 5 else 0.0
|
| 205 |
-
|
| 206 |
-
def f(key: str, default: float = 0.0) -> float:
|
| 207 |
-
v = feats.get(key)
|
| 208 |
-
return float(v) if v is not None else default
|
| 209 |
-
|
| 210 |
-
rsi = f("rsi", 50.0)
|
| 211 |
-
cvd = f("cvd", 0.0)
|
| 212 |
-
ob = f("ob_imbal", 0.0)
|
| 213 |
-
fund = f("funding", 0.0)
|
| 214 |
-
tbr = f("taker_buy_ratio", 0.5)
|
| 215 |
-
pyes = f("polymarket_yes", 0.5)
|
| 216 |
-
pdel = f("poly_yes_delta_1m", 0.0)
|
| 217 |
-
fg = f("fear_greed", 50.0)
|
| 218 |
-
dxy = f("dxy_change_pct", 0.0)
|
| 219 |
-
nq = f("nasdaq_fut_change_pct", 0.0)
|
| 220 |
-
etf = f("farside_net_flow_usd", 0.0)
|
| 221 |
-
cbp = f("coinbase_premium_pct", 0.0)
|
| 222 |
-
sk = f("stoch_rsi_k", 50.0)
|
| 223 |
-
vwap = f("vwap_dev", 0.0)
|
| 224 |
-
atr = f("atr_pct_of_spot", 0.5)
|
| 225 |
-
|
| 226 |
-
return np.array([
|
| 227 |
-
sl3, sl5, sl10, sl20, ema_diff, std,
|
| 228 |
-
(rsi - 50.0) / 50.0,
|
| 229 |
-
_tanh(cvd / 5e6),
|
| 230 |
-
_tanh(ob * 3.0),
|
| 231 |
-
fund * 1000.0,
|
| 232 |
-
tbr - 0.5,
|
| 233 |
-
pyes - 0.5,
|
| 234 |
-
_tanh(pdel * 20.0),
|
| 235 |
-
(fg - 50.0) / 50.0,
|
| 236 |
-
_tanh(-dxy * 0.5),
|
| 237 |
-
_tanh(nq * 0.5),
|
| 238 |
-
_tanh(etf / 1e8),
|
| 239 |
-
cbp / 0.3,
|
| 240 |
-
(sk - 50.0) / 50.0,
|
| 241 |
-
_tanh(vwap * 0.5),
|
| 242 |
-
1.0 / (1.0 + atr),
|
| 243 |
-
sl3 * sl5,
|
| 244 |
-
sl5 * sl20,
|
| 245 |
-
abs(ema_diff),
|
| 246 |
-
math.copysign(ema_diff ** 2, ema_diff),
|
| 247 |
-
_tanh(cvd / 5e6) * (pyes - 0.5),
|
| 248 |
-
sl20 * (rsi - 50.0) / 50.0,
|
| 249 |
-
max(0.0, sl20),
|
| 250 |
-
min(0.0, sl20),
|
| 251 |
-
(tbr - 0.5) * _tanh(ob * 3.0),
|
| 252 |
-
_tanh((pyes - 0.5) * 5.0),
|
| 253 |
-
fund * _tanh(cvd / 5e6),
|
| 254 |
-
abs(sl5 - sl20),
|
| 255 |
-
_tanh(nq * 0.3) * _tanh(-dxy * 0.3),
|
| 256 |
-
std * abs(ob),
|
| 257 |
-
], dtype=np.float32)
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 262 |
-
# MiroFish role-filtered feature dicts (v20)
|
| 263 |
-
#
|
| 264 |
-
# Each tier sees ONLY the features its signal type is best at reading.
|
| 265 |
-
# The disagreement between tiers is the meaningful swarm signal.
|
| 266 |
-
#
|
| 267 |
-
# PRICE MEMORY → Chronos, PatchTST, N-HiTS
|
| 268 |
-
# ORDERFLOW → XGBoost, CatBoost, iTransformer
|
| 269 |
-
# SENTIMENT → LightGBM
|
| 270 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 271 |
-
|
| 272 |
-
# Keys that every tier is allowed to see (price-derived, no counterparty signal)
|
| 273 |
-
_PRICE_KEYS = {"rsi", "stoch_rsi_k", "stoch_rsi_d", "vwap_dev",
|
| 274 |
-
"atr_pct_of_spot", "atr", "bollinger_squeeze",
|
| 275 |
-
"vol_regime", "vol_percentile", "garman_klass_vol"}
|
| 276 |
-
|
| 277 |
-
# Orderflow tier — market microstructure only; no polymarket / sentiment
|
| 278 |
-
_ORDERFLOW_KEYS = _PRICE_KEYS | {
|
| 279 |
-
"cvd", "ob_imbal", "taker_buy_ratio", "funding",
|
| 280 |
-
"bid_ask_spread_pct", "bid_vol_top20", "ask_vol_top20",
|
| 281 |
-
"coinbase_premium_pct", "exchange_net_inflow_btc_5m", "exchange_net_inflow",
|
| 282 |
-
"open_interest", "ls_ratio", "deribit_pcr",
|
| 283 |
-
"whale_transfer_btc", "whale_transfer_dest", "whale_exchange_count_15m",
|
| 284 |
-
"korea_premium_pct", "stablecoin_supply_change", "stablecoin_supply_chg",
|
| 285 |
-
}
|
| 286 |
-
|
| 287 |
-
# Sentiment tier — crowd + narrative only; no raw orderflow
|
| 288 |
-
_SENTIMENT_KEYS = _PRICE_KEYS | {
|
| 289 |
-
"polymarket_yes", "poly_yes_delta_1m",
|
| 290 |
-
"fear_greed", "sentiment_polarity",
|
| 291 |
-
"dxy_change_pct", "nasdaq_fut_change_pct",
|
| 292 |
-
"farside_net_flow_usd", "btc_dom", "chainlink_price",
|
| 293 |
-
"market_regime", "htf_trend_15m", "htf_trend_1h",
|
| 294 |
-
"session",
|
| 295 |
-
}
|
| 296 |
-
|
| 297 |
-
# Price-memory tier — closes + price-derived indicators only
|
| 298 |
-
_PRICE_MEMORY_KEYS = _PRICE_KEYS | {
|
| 299 |
-
"market_regime", "htf_trend_15m", "htf_trend_1h",
|
| 300 |
-
"candle_pattern", "nearest_support", "nearest_resistance",
|
| 301 |
-
"session",
|
| 302 |
-
}
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
def _filter_feats(feats: dict, allowed_keys: set) -> dict:
|
| 306 |
-
"""Return a copy of feats with only the allowed keys present.
|
| 307 |
-
Keys not in allowed_keys are set to None so _feature_vector() uses defaults."""
|
| 308 |
-
return {k: (v if k in allowed_keys else None) for k, v in feats.items()}
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
"""Bootstrap training set for XGBoost and LightGBM."""
|
| 312 |
-
rng = np.random.default_rng(42)
|
| 313 |
-
X, y = [], []
|
| 314 |
-
|
| 315 |
-
for _ in range(n_samples):
|
| 316 |
-
sl20_s = rng.uniform(-0.03, 0.03)
|
| 317 |
-
rsi_s = rng.uniform(25.0, 75.0)
|
| 318 |
-
cvd_s = rng.uniform(-1e7, 1e7)
|
| 319 |
-
ob_s = rng.uniform(-0.5, 0.5)
|
| 320 |
-
fund_s = rng.uniform(-0.02, 0.02)
|
| 321 |
-
tbr_s = rng.uniform(0.3, 0.7)
|
| 322 |
-
pyes_s = rng.uniform(0.2, 0.8)
|
| 323 |
-
pdel_s = rng.uniform(-0.02, 0.02)
|
| 324 |
-
fg_s = rng.uniform(20.0, 80.0)
|
| 325 |
-
dxy_s = rng.uniform(-0.8, 0.8)
|
| 326 |
-
nq_s = rng.uniform(-1.0, 1.0)
|
| 327 |
-
etf_s = rng.uniform(-5e8, 5e8)
|
| 328 |
-
cbp_s = rng.uniform(-0.5, 0.5)
|
| 329 |
-
sk_s = rng.uniform(10.0, 90.0)
|
| 330 |
-
vwap_s = rng.uniform(-1.0, 1.0)
|
| 331 |
-
atr_s = rng.uniform(0.1, 2.0)
|
| 332 |
-
|
| 333 |
-
trend = rng.choice([-1, 0, 1], p=[0.35, 0.30, 0.35])
|
| 334 |
-
closes = (100.0 + np.cumsum(
|
| 335 |
-
trend * rng.uniform(0, 0.002, 80) + rng.normal(0, 0.001, 80)
|
| 336 |
-
)).tolist()
|
| 337 |
-
|
| 338 |
-
feats = {
|
| 339 |
-
"rsi": rsi_s, "cvd": cvd_s, "ob_imbal": ob_s,
|
| 340 |
-
"funding": fund_s, "taker_buy_ratio": tbr_s,
|
| 341 |
-
"polymarket_yes": pyes_s, "poly_yes_delta_1m": pdel_s,
|
| 342 |
-
"fear_greed": fg_s, "dxy_change_pct": dxy_s,
|
| 343 |
-
"nasdaq_fut_change_pct": nq_s, "farside_net_flow_usd": etf_s,
|
| 344 |
-
"coinbase_premium_pct": cbp_s, "stoch_rsi_k": sk_s,
|
| 345 |
-
"vwap_dev": vwap_s, "atr_pct_of_spot": atr_s,
|
| 346 |
-
}
|
| 347 |
-
|
| 348 |
-
fv = _feature_vector(feats, closes)
|
| 349 |
-
X.append(fv)
|
| 350 |
-
|
| 351 |
-
label_score = (
|
| 352 |
-
sl20_s * 50.0 +
|
| 353 |
-
(rsi_s - 50.0) / 50.0 * 0.30 +
|
| 354 |
-
_tanh(cvd_s / 5e6) * 0.25 +
|
| 355 |
-
_tanh(ob_s * 3.0) * 0.20 +
|
| 356 |
-
(pyes_s - 0.5) * 0.15 +
|
| 357 |
-
_tanh(-dxy_s * 0.5) * 0.10 +
|
| 358 |
-
_tanh(nq_s * 0.5) * 0.10
|
| 359 |
-
)
|
| 360 |
-
y.append(1 if label_score > 0.02 else 0)
|
| 361 |
-
|
| 362 |
-
return np.array(X, dtype=np.float32), np.array(y, dtype=np.int32)
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 366 |
-
# NeuralForecast helpers
|
| 367 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 368 |
-
|
| 369 |
-
NF_HORIZON: int = 2 # predict next 2 candles
|
| 370 |
-
NF_INPUT_SIZE: int = 64 # lookback window
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
def _prepare_nf_df(closes: list, freq: str = "5min") -> pd.DataFrame:
|
| 374 |
-
"""Convert a closes list into the long DataFrame format NeuralForecast expects."""
|
| 375 |
-
n = len(closes)
|
| 376 |
-
end_ts = pd.Timestamp.utcnow().floor(freq)
|
| 377 |
-
timestamps = pd.date_range(end=end_ts, periods=n, freq=freq)
|
| 378 |
-
return pd.DataFrame({
|
| 379 |
-
"unique_id": "BTC",
|
| 380 |
-
"ds": timestamps,
|
| 381 |
-
"y": np.array(closes, dtype=np.float64),
|
| 382 |
-
})
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
def _synthetic_nf_training_data(n_series: int = 50, series_len: int = 200) -> pd.DataFrame:
|
| 386 |
-
"""Generate synthetic multivariate price series for NeuralForecast bootstrap training."""
|
| 387 |
-
rng = np.random.default_rng(42)
|
| 388 |
-
rows = []
|
| 389 |
-
base_ts = pd.Timestamp("2024-01-01", tz="UTC")
|
| 390 |
-
|
| 391 |
-
for i in range(n_series):
|
| 392 |
-
trend = rng.choice([-1, 0, 1], p=[0.35, 0.30, 0.35])
|
| 393 |
-
prices = 100.0 + np.cumsum(
|
| 394 |
-
trend * rng.uniform(0, 0.003, series_len)
|
| 395 |
-
+ rng.normal(0, 0.001, series_len)
|
| 396 |
-
)
|
| 397 |
-
timestamps = pd.date_range(start=base_ts, periods=series_len, freq="5min")
|
| 398 |
-
for ts, price in zip(timestamps, prices):
|
| 399 |
-
rows.append({"unique_id": f"SYN_{i:03d}", "ds": ts, "y": float(price)})
|
| 400 |
-
|
| 401 |
-
return pd.DataFrame(rows)
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
def build_neural_models(horizon: int = NF_HORIZON):
|
| 405 |
-
"""Instantiate PatchTST, N-HiTS, and iTransformer wrapped in NeuralForecast."""
|
| 406 |
-
from neuralforecast import NeuralForecast
|
| 407 |
-
from neuralforecast.models import PatchTST, NHITS, iTransformer
|
| 408 |
-
|
| 409 |
-
return NeuralForecast(
|
| 410 |
-
models=[
|
| 411 |
-
PatchTST(
|
| 412 |
-
h=horizon,
|
| 413 |
-
input_size=NF_INPUT_SIZE,
|
| 414 |
-
patch_len=16,
|
| 415 |
-
stride=8,
|
| 416 |
-
max_steps=50,
|
| 417 |
-
learning_rate=1e-3,
|
| 418 |
-
),
|
| 419 |
-
NHITS(
|
| 420 |
-
h=horizon,
|
| 421 |
-
input_size=NF_INPUT_SIZE,
|
| 422 |
-
max_steps=50,
|
| 423 |
-
n_freq_downsample=[2, 1, 1],
|
| 424 |
-
),
|
| 425 |
-
iTransformer(
|
| 426 |
-
h=horizon,
|
| 427 |
-
input_size=NF_INPUT_SIZE,
|
| 428 |
-
max_steps=50,
|
| 429 |
-
),
|
| 430 |
-
],
|
| 431 |
-
freq="5min",
|
| 432 |
-
)
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 436 |
-
# Startup — load / bootstrap models
|
| 437 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 438 |
|
| 439 |
@app.on_event("startup")
|
| 440 |
async def startup_event():
|
| 441 |
-
|
| 442 |
-
_load_lgbm()
|
| 443 |
-
_load_catboost()
|
| 444 |
-
_load_neuralforecast()
|
| 445 |
-
_load_chronos()
|
| 446 |
-
logger.info("Startup complete. flags=%s", _flags)
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
def _load_xgboost():
|
| 450 |
-
try:
|
| 451 |
-
import xgboost as xgb
|
| 452 |
-
path = os.environ.get("XGB_MODEL_PATH", "/app/xgb_model.json")
|
| 453 |
-
if os.path.exists(path):
|
| 454 |
-
clf = xgb.XGBClassifier()
|
| 455 |
-
clf.load_model(path)
|
| 456 |
-
logger.info("XGBoost loaded from %s", path)
|
| 457 |
-
else:
|
| 458 |
-
logger.info("XGBoost: bootstrap training…")
|
| 459 |
-
X, y = _synthetic_training_data(2000)
|
| 460 |
-
clf = xgb.XGBClassifier(
|
| 461 |
-
n_estimators=150, max_depth=5, learning_rate=0.07,
|
| 462 |
-
subsample=0.8, colsample_bytree=0.8, min_child_weight=3,
|
| 463 |
-
gamma=0.1, reg_alpha=0.1, reg_lambda=1.0,
|
| 464 |
-
eval_metric="logloss", random_state=42, n_jobs=2,
|
| 465 |
-
use_label_encoder=False,
|
| 466 |
-
)
|
| 467 |
-
clf.fit(X, y)
|
| 468 |
-
logger.info("XGBoost: bootstrap trained")
|
| 469 |
-
_models["xgboost"] = clf
|
| 470 |
-
_flags["xgboost"] = True
|
| 471 |
-
except Exception as exc:
|
| 472 |
-
logger.warning("XGBoost unavailable: %s", exc)
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
def _load_lgbm():
|
| 476 |
-
try:
|
| 477 |
-
import lightgbm as lgb
|
| 478 |
-
import pickle
|
| 479 |
-
|
| 480 |
-
path = os.environ.get("LGBM_MODEL_PATH", "/app/lgbm_model.pkl")
|
| 481 |
-
if os.path.exists(path):
|
| 482 |
-
with open(path, "rb") as fh:
|
| 483 |
-
clf = pickle.load(fh)
|
| 484 |
-
logger.info("LightGBM loaded from %s", path)
|
| 485 |
-
else:
|
| 486 |
-
logger.info("LightGBM: bootstrap training…")
|
| 487 |
-
X, y = _synthetic_training_data(2000)
|
| 488 |
-
clf = lgb.LGBMClassifier(
|
| 489 |
-
n_estimators=150, max_depth=5, learning_rate=0.07,
|
| 490 |
-
subsample=0.8, colsample_bytree=0.8,
|
| 491 |
-
class_weight="balanced", random_state=42,
|
| 492 |
-
n_jobs=2, verbose=-1,
|
| 493 |
-
)
|
| 494 |
-
clf.fit(X, y)
|
| 495 |
-
logger.info("LightGBM: bootstrap trained")
|
| 496 |
-
_models["lgbm"] = clf
|
| 497 |
-
_flags["lgbm"] = True
|
| 498 |
-
except Exception as exc:
|
| 499 |
-
logger.warning("LightGBM unavailable: %s", exc)
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
def _load_catboost():
|
| 503 |
-
try:
|
| 504 |
-
from catboost import CatBoostClassifier
|
| 505 |
-
import pickle
|
| 506 |
-
|
| 507 |
-
path = os.environ.get("CATBOOST_MODEL_PATH", "/app/catboost_model.cbm")
|
| 508 |
-
if os.path.exists(path):
|
| 509 |
-
clf = CatBoostClassifier()
|
| 510 |
-
clf.load_model(path)
|
| 511 |
-
logger.info("CatBoost loaded from %s", path)
|
| 512 |
-
else:
|
| 513 |
-
logger.info("CatBoost: bootstrap training…")
|
| 514 |
-
X, y = _synthetic_training_data(2000)
|
| 515 |
-
clf = CatBoostClassifier(
|
| 516 |
-
iterations=300,
|
| 517 |
-
depth=6,
|
| 518 |
-
learning_rate=0.07,
|
| 519 |
-
loss_function="Logloss",
|
| 520 |
-
eval_metric="AUC",
|
| 521 |
-
random_seed=42,
|
| 522 |
-
thread_count=2,
|
| 523 |
-
verbose=0,
|
| 524 |
-
)
|
| 525 |
-
clf.fit(X, y)
|
| 526 |
-
logger.info("CatBoost: bootstrap trained")
|
| 527 |
-
_models["catboost"] = clf
|
| 528 |
-
_flags["catboost"] = True
|
| 529 |
-
except Exception as exc:
|
| 530 |
-
logger.warning("CatBoost unavailable: %s", exc)
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
def _load_neuralforecast():
|
| 534 |
-
"""Bootstrap-train PatchTST, N-HiTS, and iTransformer on synthetic candle data."""
|
| 535 |
-
try:
|
| 536 |
-
nf = build_neural_models(horizon=NF_HORIZON)
|
| 537 |
-
train_df = _synthetic_nf_training_data(n_series=50, series_len=200)
|
| 538 |
-
logger.info("NeuralForecast: bootstrap training (PatchTST + N-HiTS + iTransformer)…")
|
| 539 |
-
nf.fit(train_df)
|
| 540 |
-
_models["neuralforecast"] = nf
|
| 541 |
-
_flags["patchtst"] = True
|
| 542 |
-
_flags["nhits"] = True
|
| 543 |
-
_flags["itransformer"] = True
|
| 544 |
-
logger.info("NeuralForecast: bootstrap trained ✓")
|
| 545 |
-
except Exception as exc:
|
| 546 |
-
logger.warning("NeuralForecast unavailable: %s", exc)
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
def _load_chronos():
|
| 550 |
try:
|
| 551 |
from chronos import ChronosPipeline
|
| 552 |
import torch
|
| 553 |
model_name = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-tiny")
|
| 554 |
logger.info("Chronos: loading %s …", model_name)
|
| 555 |
-
|
| 556 |
model_name,
|
| 557 |
device_map="cpu",
|
| 558 |
torch_dtype=torch.float32,
|
| 559 |
)
|
| 560 |
-
|
| 561 |
-
_flags["chronos"] = True
|
| 562 |
logger.info("Chronos loaded ✓")
|
| 563 |
except Exception as exc:
|
| 564 |
logger.warning("Chronos not loaded: %s", exc)
|
| 565 |
|
| 566 |
-
|
| 567 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 568 |
-
#
|
| 569 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 570 |
|
| 571 |
-
def
|
| 572 |
-
# v20: Chronos is price-memory tier — feats already price-only at call site
|
| 573 |
import torch
|
| 574 |
-
|
| 575 |
-
c = np.array(closes[-64:], dtype=np.float32)
|
| 576 |
context = torch.tensor(c).unsqueeze(0)
|
| 577 |
with torch.no_grad():
|
| 578 |
-
forecast =
|
| 579 |
median = float(forecast[0].median(dim=0).values.mean().item())
|
| 580 |
last = float(c[-1])
|
| 581 |
score = _tanh((median / last - 1.0) * 20.0) if last != 0 else 0.0
|
| 582 |
-
return _score_to_prediction(
|
| 583 |
-
"Chronos", score,
|
| 584 |
-
f"Chronos: median={median:.2f} last={last:.2f}",
|
| 585 |
-
)
|
| 586 |
|
| 587 |
|
| 588 |
-
def
|
| 589 |
-
c
|
| 590 |
-
n
|
| 591 |
last = float(c[-1]) if n > 0 else 1.0
|
| 592 |
-
e20
|
| 593 |
-
e50
|
| 594 |
sl20 = _slope(c, min(20, n - 1))
|
| 595 |
rsi = float(feats.get("rsi") or 50.0)
|
| 596 |
-
|
| 597 |
score = (
|
| 598 |
math.copysign(min(1.0, abs(sl20) * 150.0), sl20) * 0.45 +
|
| 599 |
math.copysign(min(1.0, abs((e20 - e50) / last) * 200.0), (e20 - e50)) * 0.35 +
|
| 600 |
((rsi - 50.0) / 50.0) * 0.20
|
| 601 |
)
|
| 602 |
return _score_to_prediction(
|
| 603 |
-
|
| 604 |
f"Chronos bootstrap: sl20={sl20*100:.4f}% ema_diff={((e20-e50)/last)*100:.4f}%",
|
| 605 |
)
|
| 606 |
|
| 607 |
-
|
| 608 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 609 |
-
# Model inference — trained classifiers
|
| 610 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 611 |
-
|
| 612 |
-
def _predict_xgboost(closes: list, feats: dict) -> dict:
|
| 613 |
-
clf = _models.get("xgboost")
|
| 614 |
-
role_feats = _filter_feats(feats, _ORDERFLOW_KEYS) # v20: orderflow tier
|
| 615 |
-
if clf is None:
|
| 616 |
-
return _predict_chronos_bootstrap(closes, feats)
|
| 617 |
-
try:
|
| 618 |
-
fv = _feature_vector(role_feats, closes).reshape(1, -1)
|
| 619 |
-
prob = float(clf.predict_proba(fv)[0][1])
|
| 620 |
-
score = (prob - 0.5) * 2.0
|
| 621 |
-
direction = "UP" if prob > 0.55 else ("DOWN" if prob < 0.45 else "NEUTRAL")
|
| 622 |
-
return {
|
| 623 |
-
"name": "XGBoost",
|
| 624 |
-
"direction": direction,
|
| 625 |
-
"confidence": _clamp(round(45.0 + abs(score) * 50.0), 40, 95),
|
| 626 |
-
"slope_pct": round(score * 0.5, 6),
|
| 627 |
-
"reasoning": f"XGB: P(UP)={prob:.4f}",
|
| 628 |
-
}
|
| 629 |
-
except Exception as exc:
|
| 630 |
-
logger.warning("XGBoost inference error: %s", exc)
|
| 631 |
-
return _predict_chronos_bootstrap(closes, feats)
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
def _predict_lightgbm(closes: list, feats: dict) -> dict:
|
| 635 |
-
clf = _models.get("lgbm")
|
| 636 |
-
role_feats = _filter_feats(feats, _SENTIMENT_KEYS) # v20: sentiment tier
|
| 637 |
-
if clf is None:
|
| 638 |
-
return _predict_chronos_bootstrap(closes, feats)
|
| 639 |
-
try:
|
| 640 |
-
fv = _feature_vector(role_feats, closes).reshape(1, -1)
|
| 641 |
-
prob = float(clf.predict_proba(fv)[0][1])
|
| 642 |
-
score = (prob - 0.5) * 2.0
|
| 643 |
-
direction = "UP" if prob > 0.55 else ("DOWN" if prob < 0.45 else "NEUTRAL")
|
| 644 |
-
return {
|
| 645 |
-
"name": "LightGBM",
|
| 646 |
-
"direction": direction,
|
| 647 |
-
"confidence": _clamp(round(45.0 + abs(score) * 50.0), 40, 95),
|
| 648 |
-
"slope_pct": round(score * 0.5, 6),
|
| 649 |
-
"reasoning": f"LGBM: P(UP)={prob:.4f}",
|
| 650 |
-
}
|
| 651 |
-
except Exception as exc:
|
| 652 |
-
logger.warning("LightGBM inference error: %s", exc)
|
| 653 |
-
return _predict_chronos_bootstrap(closes, feats)
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
def _predict_catboost(closes: list, feats: dict) -> dict:
|
| 657 |
-
clf = _models.get("catboost")
|
| 658 |
-
role_feats = _filter_feats(feats, _ORDERFLOW_KEYS) # v20: orderflow tier
|
| 659 |
-
if clf is None:
|
| 660 |
-
return _predict_chronos_bootstrap(closes, feats)
|
| 661 |
-
try:
|
| 662 |
-
fv = _feature_vector(role_feats, closes).reshape(1, -1)
|
| 663 |
-
prob = float(clf.predict_proba(fv)[0][1])
|
| 664 |
-
score = (prob - 0.5) * 2.0
|
| 665 |
-
direction = "UP" if prob > 0.55 else ("DOWN" if prob < 0.45 else "NEUTRAL")
|
| 666 |
-
return {
|
| 667 |
-
"name": "CatBoost",
|
| 668 |
-
"direction": direction,
|
| 669 |
-
"confidence": _clamp(round(45.0 + abs(score) * 50.0), 40, 95),
|
| 670 |
-
"slope_pct": round(score * 0.5, 6),
|
| 671 |
-
"reasoning": f"CatBoost: P(UP)={prob:.4f}",
|
| 672 |
-
}
|
| 673 |
-
except Exception as exc:
|
| 674 |
-
logger.warning("CatBoost inference error: %s", exc)
|
| 675 |
-
return _predict_chronos_bootstrap(closes, feats)
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 679 |
-
# Model inference — NeuralForecast (PatchTST, N-HiTS, iTransformer)
|
| 680 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 681 |
-
|
| 682 |
-
def _nf_score_from_forecast(df_pred: pd.DataFrame, col: str, last: float) -> float:
|
| 683 |
-
"""Derive a scalar direction score from a NeuralForecast prediction column."""
|
| 684 |
-
try:
|
| 685 |
-
pred_mean = float(df_pred[col].mean())
|
| 686 |
-
return _tanh((pred_mean / last - 1.0) * 20.0) if last != 0 else 0.0
|
| 687 |
-
except Exception:
|
| 688 |
-
return 0.0
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
def _predict_neuralforecast(closes: list, feats: dict) -> list:
|
| 692 |
-
"""Run PatchTST, N-HiTS, and iTransformer inference.
|
| 693 |
-
v20: PatchTST and N-HiTS are price-memory tier (no orderflow/sentiment).
|
| 694 |
-
iTransformer is orderflow tier (no sentiment).
|
| 695 |
-
"""
|
| 696 |
-
nf = _models.get("neuralforecast")
|
| 697 |
-
last = float(closes[-1]) if closes else 1.0
|
| 698 |
-
|
| 699 |
-
# Role-filtered feats per model
|
| 700 |
-
pm_feats = _filter_feats(feats, _PRICE_MEMORY_KEYS) # PatchTST, N-HiTS
|
| 701 |
-
of_feats = _filter_feats(feats, _ORDERFLOW_KEYS) # iTransformer
|
| 702 |
-
|
| 703 |
-
if nf is None:
|
| 704 |
-
c = np.array(closes, dtype=np.float64)
|
| 705 |
-
n = len(c)
|
| 706 |
-
sl20 = _slope(c, min(20, n - 1))
|
| 707 |
-
rsi = float(pm_feats.get("rsi") or 50.0)
|
| 708 |
-
base_pm = math.copysign(min(1.0, abs(sl20) * 80.0), sl20) * 0.60 + ((rsi - 50.0) / 50.0) * 0.40
|
| 709 |
-
cvd = float(of_feats.get("cvd") or 0.0)
|
| 710 |
-
ob = float(of_feats.get("ob_imbal") or 0.0)
|
| 711 |
-
base_of = (
|
| 712 |
-
math.copysign(min(1.0, abs(sl20) * 60.0), sl20) * 0.40 +
|
| 713 |
-
_tanh(cvd / 5e6) * 0.35 +
|
| 714 |
-
_tanh(ob * 3.0) * 0.25
|
| 715 |
-
)
|
| 716 |
-
return [
|
| 717 |
-
_score_to_prediction("PatchTST", base_pm, "PatchTST bootstrap formula (price-memory)"),
|
| 718 |
-
_score_to_prediction("N-HiTS", base_pm, "N-HiTS bootstrap formula (price-memory)"),
|
| 719 |
-
_score_to_prediction("iTransformer", base_of, "iTransformer bootstrap formula (orderflow)"),
|
| 720 |
-
]
|
| 721 |
-
|
| 722 |
-
try:
|
| 723 |
-
input_df = _prepare_nf_df(closes[-NF_INPUT_SIZE:])
|
| 724 |
-
df_pred = nf.predict(input_df)
|
| 725 |
-
|
| 726 |
-
results = []
|
| 727 |
-
# (display_name, col_prefix, role_feats_for_fallback)
|
| 728 |
-
model_col_map = [
|
| 729 |
-
("PatchTST", "PatchTST", pm_feats),
|
| 730 |
-
("N-HiTS", "NHITS", pm_feats),
|
| 731 |
-
("iTransformer", "iTransformer", of_feats),
|
| 732 |
-
]
|
| 733 |
-
for display_name, col_prefix, _ in model_col_map:
|
| 734 |
-
matching = [c for c in df_pred.columns if c.startswith(col_prefix)]
|
| 735 |
-
if not matching:
|
| 736 |
-
score = 0.0
|
| 737 |
-
reasoning = f"{display_name}: column not found"
|
| 738 |
-
else:
|
| 739 |
-
score = _nf_score_from_forecast(df_pred, matching[0], last)
|
| 740 |
-
pred_val = float(df_pred[matching[0]].mean())
|
| 741 |
-
reasoning = f"{display_name}: pred={pred_val:.4f} last={last:.4f}"
|
| 742 |
-
results.append(_score_to_prediction(display_name, score, reasoning))
|
| 743 |
-
return results
|
| 744 |
-
|
| 745 |
-
except Exception as exc:
|
| 746 |
-
logger.warning("NeuralForecast inference error: %s", exc)
|
| 747 |
-
c = np.array(closes, dtype=np.float64)
|
| 748 |
-
n = len(c)
|
| 749 |
-
sl20 = _slope(c, min(20, n - 1))
|
| 750 |
-
base = math.copysign(min(1.0, abs(sl20) * 80.0), sl20)
|
| 751 |
-
return [
|
| 752 |
-
_score_to_prediction("PatchTST", base, f"PatchTST fallback: {exc}"),
|
| 753 |
-
_score_to_prediction("N-HiTS", base, f"N-HiTS fallback: {exc}"),
|
| 754 |
-
_score_to_prediction("iTransformer", base, f"iTransformer fallback: {exc}"),
|
| 755 |
-
]
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 759 |
-
# Tier verdict helper (v20)
|
| 760 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 761 |
-
|
| 762 |
-
# Maps each model name → its tier
|
| 763 |
-
_MODEL_TIER: dict[str, str] = {
|
| 764 |
-
"Chronos": "price_memory",
|
| 765 |
-
"PatchTST": "price_memory",
|
| 766 |
-
"N-HiTS": "price_memory",
|
| 767 |
-
"XGBoost": "orderflow",
|
| 768 |
-
"CatBoost": "orderflow",
|
| 769 |
-
"iTransformer": "orderflow",
|
| 770 |
-
"LightGBM": "sentiment",
|
| 771 |
-
}
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
def _tier_verdict(predictions: list, tier: str) -> dict:
|
| 775 |
-
"""
|
| 776 |
-
Aggregate all predictions belonging to `tier` into a single verdict.
|
| 777 |
-
Returns: { direction, confidence, models: [names], agreement_pct }
|
| 778 |
-
"""
|
| 779 |
-
tier_preds = [p for p in predictions if _MODEL_TIER.get(p["name"]) == tier]
|
| 780 |
-
if not tier_preds:
|
| 781 |
-
return {"direction": "SKIP", "confidence": 0, "models": [], "agreement_pct": 0.0}
|
| 782 |
-
|
| 783 |
-
up_w = dn_w = total_w = 0.0
|
| 784 |
-
for p in tier_preds:
|
| 785 |
-
conf = p["confidence"] / 100.0
|
| 786 |
-
eff = _effective_weight(p["name"])
|
| 787 |
-
w = eff * conf
|
| 788 |
-
if p["direction"] == "UP":
|
| 789 |
-
up_w += w
|
| 790 |
-
elif p["direction"] == "DOWN":
|
| 791 |
-
dn_w += w
|
| 792 |
-
total_w += w
|
| 793 |
-
|
| 794 |
-
if total_w == 0:
|
| 795 |
-
direction = "SKIP"
|
| 796 |
-
agreement_pct = 0.0
|
| 797 |
-
elif up_w > dn_w:
|
| 798 |
-
direction = "UP"
|
| 799 |
-
agreement_pct = round(up_w / total_w, 4)
|
| 800 |
-
elif dn_w > up_w:
|
| 801 |
-
direction = "DOWN"
|
| 802 |
-
agreement_pct = round(dn_w / total_w, 4)
|
| 803 |
-
else:
|
| 804 |
-
direction = "SKIP"
|
| 805 |
-
agreement_pct = 0.0
|
| 806 |
-
|
| 807 |
-
matching = [p for p in tier_preds if p["direction"] == direction]
|
| 808 |
-
avg_conf = (
|
| 809 |
-
round(sum(p["confidence"] for p in matching) / len(matching))
|
| 810 |
-
if matching else 50
|
| 811 |
-
)
|
| 812 |
-
|
| 813 |
-
return {
|
| 814 |
-
"direction": direction,
|
| 815 |
-
"confidence": avg_conf,
|
| 816 |
-
"models": [p["name"] for p in tier_preds],
|
| 817 |
-
"agreement_pct": agreement_pct,
|
| 818 |
-
}
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
def _tier_agreement_label(tv: dict) -> str:
|
| 822 |
-
"""
|
| 823 |
-
Given tier_verdicts dict, return a human-readable agreement label.
|
| 824 |
-
|
| 825 |
-
ALL_AGREE — all three tiers point the same direction
|
| 826 |
-
2_OF_3 — two tiers agree, one diverges (lower conviction but real signal)
|
| 827 |
-
SPLIT — no majority (e.g. UP / DOWN / SKIP spread evenly)
|
| 828 |
-
CONFLICT — price_memory and orderflow directly oppose each other
|
| 829 |
-
"""
|
| 830 |
-
dirs = [tv["price_memory"]["direction"],
|
| 831 |
-
tv["orderflow"]["direction"],
|
| 832 |
-
tv["sentiment"]["direction"]]
|
| 833 |
-
|
| 834 |
-
non_skip = [d for d in dirs if d != "SKIP"]
|
| 835 |
-
if not non_skip:
|
| 836 |
-
return "SPLIT"
|
| 837 |
-
|
| 838 |
-
from collections import Counter
|
| 839 |
-
counts = Counter(non_skip)
|
| 840 |
-
top_dir, top_count = counts.most_common(1)[0]
|
| 841 |
-
|
| 842 |
-
# Direct conflict: price_memory and orderflow are opposite and both non-SKIP
|
| 843 |
-
pm_dir = tv["price_memory"]["direction"]
|
| 844 |
-
of_dir = tv["orderflow"]["direction"]
|
| 845 |
-
if pm_dir != "SKIP" and of_dir != "SKIP" and pm_dir != of_dir:
|
| 846 |
-
return "CONFLICT"
|
| 847 |
-
|
| 848 |
-
if top_count == len(non_skip):
|
| 849 |
-
return "ALL_AGREE"
|
| 850 |
-
if top_count >= 2:
|
| 851 |
-
return "2_OF_3"
|
| 852 |
-
return "SPLIT"
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 856 |
-
# Ensemble aggregation
|
| 857 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 858 |
-
|
| 859 |
-
def _aggregate(predictions: list) -> dict:
|
| 860 |
-
up_w = dn_w = total_w = 0.0
|
| 861 |
-
dynamic_weights: dict = {}
|
| 862 |
-
|
| 863 |
-
for p in predictions:
|
| 864 |
-
conf = p["confidence"] / 100.0
|
| 865 |
-
eff = _effective_weight(p["name"])
|
| 866 |
-
w = eff * conf
|
| 867 |
-
dynamic_weights[p["name"]] = round(eff, 6)
|
| 868 |
-
if p["direction"] == "UP":
|
| 869 |
-
up_w += w
|
| 870 |
-
elif p["direction"] == "DOWN":
|
| 871 |
-
dn_w += w
|
| 872 |
-
total_w += w
|
| 873 |
-
|
| 874 |
-
if total_w == 0:
|
| 875 |
-
return dict(
|
| 876 |
-
composite_direction="NEUTRAL",
|
| 877 |
-
composite_confidence=50,
|
| 878 |
-
composite_score=0.0,
|
| 879 |
-
models=predictions,
|
| 880 |
-
dynamic_weights=dynamic_weights,
|
| 881 |
-
tier_verdicts={
|
| 882 |
-
"price_memory": _tier_verdict(predictions, "price_memory"),
|
| 883 |
-
"orderflow": _tier_verdict(predictions, "orderflow"),
|
| 884 |
-
"sentiment": _tier_verdict(predictions, "sentiment"),
|
| 885 |
-
},
|
| 886 |
-
tier_agreement="SPLIT",
|
| 887 |
-
is_local_fallback=False,
|
| 888 |
-
)
|
| 889 |
-
|
| 890 |
-
if up_w > dn_w:
|
| 891 |
-
comp_dir = "UP"
|
| 892 |
-
win_preds = [p for p in predictions if p["direction"] == "UP"]
|
| 893 |
-
elif dn_w > up_w:
|
| 894 |
-
comp_dir = "DOWN"
|
| 895 |
-
win_preds = [p for p in predictions if p["direction"] == "DOWN"]
|
| 896 |
-
else:
|
| 897 |
-
comp_dir = "NEUTRAL"
|
| 898 |
-
win_preds = []
|
| 899 |
-
|
| 900 |
-
margin = abs(up_w - dn_w) / total_w
|
| 901 |
-
avg_conf = (
|
| 902 |
-
sum(p["confidence"] for p in win_preds) / len(win_preds)
|
| 903 |
-
if win_preds else 50.0
|
| 904 |
-
)
|
| 905 |
-
margin_boost = min(margin * 100.0, 10.0)
|
| 906 |
-
comp_conf = int(_clamp(avg_conf + margin_boost, 45.0, 95.0))
|
| 907 |
-
comp_score = round((up_w - dn_w) / total_w, 6)
|
| 908 |
-
|
| 909 |
-
# v20 — tier verdicts
|
| 910 |
-
tier_verdicts = {
|
| 911 |
-
"price_memory": _tier_verdict(predictions, "price_memory"),
|
| 912 |
-
"orderflow": _tier_verdict(predictions, "orderflow"),
|
| 913 |
-
"sentiment": _tier_verdict(predictions, "sentiment"),
|
| 914 |
-
}
|
| 915 |
-
tier_agreement = _tier_agreement_label(tier_verdicts)
|
| 916 |
-
|
| 917 |
-
return dict(
|
| 918 |
-
composite_direction=comp_dir,
|
| 919 |
-
composite_confidence=comp_conf,
|
| 920 |
-
composite_score=comp_score,
|
| 921 |
-
models=predictions,
|
| 922 |
-
dynamic_weights=dynamic_weights,
|
| 923 |
-
tier_verdicts=tier_verdicts,
|
| 924 |
-
tier_agreement=tier_agreement,
|
| 925 |
-
is_local_fallback=False,
|
| 926 |
-
)
|
| 927 |
-
|
| 928 |
-
|
| 929 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 930 |
# Endpoints
|
| 931 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 932 |
|
| 933 |
@app.get("/")
|
| 934 |
-
async def
|
| 935 |
return {
|
| 936 |
-
"ok":
|
| 937 |
-
"version":
|
| 938 |
-
"
|
| 939 |
-
"
|
| 940 |
-
"
|
| 941 |
-
"
|
| 942 |
-
"patchtst": _flags["patchtst"],
|
| 943 |
-
"nhits": _flags["nhits"],
|
| 944 |
-
"itransformer": _flags["itransformer"],
|
| 945 |
-
"neuralforecast": _flags["patchtst"] and _flags["nhits"] and _flags["itransformer"],
|
| 946 |
-
"models": ["Chronos", "XGBoost", "LightGBM", "CatBoost", "PatchTST", "N-HiTS", "iTransformer"],
|
| 947 |
-
"tiers": {
|
| 948 |
-
"price_memory": ["Chronos", "PatchTST", "N-HiTS"],
|
| 949 |
-
"orderflow": ["XGBoost", "CatBoost", "iTransformer"],
|
| 950 |
-
"sentiment": ["LightGBM"],
|
| 951 |
-
},
|
| 952 |
-
"removed": ["MOIRAI", "MOMENT", "TimesNet", "Lag-Llama", "DAG", "TiDE", "TabPFN-TS", "N-BEATS", "AROpt"],
|
| 953 |
-
"hf_space": True,
|
| 954 |
-
}
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
@app.get("/model_stats")
|
| 958 |
-
async def model_stats():
|
| 959 |
-
"""
|
| 960 |
-
Returns per-model win/loss record and current effective weight.
|
| 961 |
-
Frontend (useMlModelStats.ts) can call this to display live accuracy.
|
| 962 |
-
"""
|
| 963 |
-
result = {}
|
| 964 |
-
for name, base in WEIGHTS.items():
|
| 965 |
-
stats = _win_stats.get(name, {"wins": 0, "losses": 0})
|
| 966 |
-
total = stats["wins"] + stats["losses"]
|
| 967 |
-
win_rate = round(stats["wins"] / total, 4) if total > 0 else None
|
| 968 |
-
result[name] = {
|
| 969 |
-
"wins": stats["wins"],
|
| 970 |
-
"losses": stats["losses"],
|
| 971 |
-
"total": total,
|
| 972 |
-
"win_rate": win_rate,
|
| 973 |
-
"base_weight": base,
|
| 974 |
-
"effective_weight": round(_effective_weight(name), 6),
|
| 975 |
-
"min_samples": _WIN_STATS_MIN_SAMPLES,
|
| 976 |
-
"ramp_pct": round(min(1.0, total / _WIN_STATS_MIN_SAMPLES) * 100),
|
| 977 |
-
}
|
| 978 |
-
return {"models": result}
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
@app.post("/record_outcome")
|
| 982 |
-
async def record_outcome(request: Request):
|
| 983 |
-
"""
|
| 984 |
-
Call this after each Polymarket window resolves.
|
| 985 |
-
|
| 986 |
-
Expected body:
|
| 987 |
-
{
|
| 988 |
-
"outcomes": [
|
| 989 |
-
{ "model": "XGBoost", "predicted": "UP", "actual": "UP" },
|
| 990 |
-
{ "model": "LightGBM", "predicted": "DOWN", "actual": "UP" },
|
| 991 |
-
...
|
| 992 |
-
]
|
| 993 |
}
|
| 994 |
|
| 995 |
-
Each entry where predicted == actual increments wins; otherwise losses.
|
| 996 |
-
Models not in WEIGHTS are silently ignored.
|
| 997 |
-
Returns updated stats for every model mentioned.
|
| 998 |
-
"""
|
| 999 |
-
body = await request.json()
|
| 1000 |
-
outcomes = body.get("outcomes", [])
|
| 1001 |
-
|
| 1002 |
-
if not isinstance(outcomes, list):
|
| 1003 |
-
return JSONResponse(status_code=422, content={"error": "outcomes must be a list"})
|
| 1004 |
-
|
| 1005 |
-
updated = {}
|
| 1006 |
-
for entry in outcomes:
|
| 1007 |
-
name = entry.get("model", "")
|
| 1008 |
-
predicted = entry.get("predicted", "")
|
| 1009 |
-
actual = entry.get("actual", "")
|
| 1010 |
-
|
| 1011 |
-
if name not in _win_stats:
|
| 1012 |
-
continue # unknown model — ignore
|
| 1013 |
-
if predicted in ("UP", "DOWN") and actual in ("UP", "DOWN"):
|
| 1014 |
-
if predicted == actual:
|
| 1015 |
-
_win_stats[name]["wins"] += 1
|
| 1016 |
-
else:
|
| 1017 |
-
_win_stats[name]["losses"] += 1
|
| 1018 |
-
updated[name] = {
|
| 1019 |
-
**_win_stats[name],
|
| 1020 |
-
"effective_weight": round(_effective_weight(name), 6),
|
| 1021 |
-
}
|
| 1022 |
-
|
| 1023 |
-
logger.info("record_outcome: updated %d models — %s", len(updated), list(updated.keys()))
|
| 1024 |
-
return {"updated": updated}
|
| 1025 |
-
|
| 1026 |
|
| 1027 |
-
@app.post("/
|
| 1028 |
-
async def
|
| 1029 |
t0 = time.perf_counter()
|
| 1030 |
body = await request.json()
|
| 1031 |
|
| 1032 |
closes = list(body.get("closes") or [])
|
| 1033 |
if len(closes) < 16:
|
| 1034 |
-
return JSONResponse(
|
| 1035 |
-
status_code=422,
|
| 1036 |
-
content={"error": "closes array too short — need at least 16 values"},
|
| 1037 |
-
)
|
| 1038 |
-
|
| 1039 |
-
feats = {k: v for k, v in body.items() if k != "closes"}
|
| 1040 |
-
|
| 1041 |
-
# v20: pre-compute role-filtered feats for price-memory tier
|
| 1042 |
-
pm_feats = _filter_feats(feats, _PRICE_MEMORY_KEYS)
|
| 1043 |
|
| 1044 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1045 |
|
| 1046 |
-
|
| 1047 |
-
if _flags["chronos"] and "chronos" in _models:
|
| 1048 |
try:
|
| 1049 |
-
|
| 1050 |
except Exception as exc:
|
| 1051 |
logger.warning("Chronos real inference failed: %s", exc)
|
| 1052 |
-
|
| 1053 |
else:
|
| 1054 |
-
|
| 1055 |
-
|
| 1056 |
-
# Trained Classifiers
|
| 1057 |
-
predictions.append(_predict_xgboost(closes, feats))
|
| 1058 |
-
predictions.append(_predict_lightgbm(closes, feats))
|
| 1059 |
-
predictions.append(_predict_catboost(closes, feats))
|
| 1060 |
-
|
| 1061 |
-
# NeuralForecast (PatchTST, N-HiTS, iTransformer)
|
| 1062 |
-
predictions.extend(_predict_neuralforecast(closes, feats))
|
| 1063 |
|
| 1064 |
-
|
| 1065 |
-
|
| 1066 |
-
return result
|
|
|
|
| 1 |
"""
|
| 2 |
+
PolyBloom ML Service — Space A v20.0
|
| 3 |
+
PRICE MEMORY TIER: Chronos (zero-shot T5 foundation model)
|
| 4 |
|
| 5 |
+
Tier role: reads closes + price-derived indicators only.
|
| 6 |
+
No orderflow (CVD, OB, funding). No sentiment (polymarket, fear/greed).
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
Endpoints:
|
| 9 |
+
GET / health check
|
| 10 |
+
POST /predict returns single Chronos prediction
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
import os
|
|
|
|
| 15 |
import time
|
| 16 |
import logging
|
| 17 |
import numpy as np
|
|
|
|
|
|
|
| 18 |
|
| 19 |
from fastapi import FastAPI, Request
|
| 20 |
from fastapi.middleware.cors import CORSMiddleware
|
| 21 |
from fastapi.responses import JSONResponse
|
| 22 |
|
| 23 |
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
|
| 24 |
+
logger = logging.getLogger("space-a")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
app = FastAPI(title="PolyBloom Space A — Price Memory", version="20.0.0")
|
| 27 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 30 |
# Global state
|
| 31 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 32 |
|
| 33 |
+
_model = None
|
| 34 |
+
_chronos_loaded = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 37 |
# Helpers
|
|
|
|
| 56 |
e = float(v) * k + e * (1.0 - k)
|
| 57 |
return e
|
| 58 |
|
| 59 |
+
def _score_to_prediction(score: float, reasoning: str) -> dict:
|
| 60 |
+
direction = "UP" if score > 0.05 else ("DOWN" if score < -0.05 else "NEUTRAL")
|
| 61 |
confidence = _clamp(45.0 + abs(score) * 55.0, 40.0, 95.0)
|
| 62 |
return {
|
| 63 |
+
"name": "Chronos",
|
| 64 |
"direction": direction,
|
| 65 |
"confidence": round(confidence),
|
| 66 |
"slope_pct": round(score * 0.5, 6),
|
| 67 |
"reasoning": reasoning,
|
| 68 |
+
"tier": "price_memory",
|
| 69 |
}
|
| 70 |
|
| 71 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 72 |
+
# Startup
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 74 |
|
| 75 |
@app.on_event("startup")
|
| 76 |
async def startup_event():
|
| 77 |
+
global _model, _chronos_loaded
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
try:
|
| 79 |
from chronos import ChronosPipeline
|
| 80 |
import torch
|
| 81 |
model_name = os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-tiny")
|
| 82 |
logger.info("Chronos: loading %s …", model_name)
|
| 83 |
+
_model = ChronosPipeline.from_pretrained(
|
| 84 |
model_name,
|
| 85 |
device_map="cpu",
|
| 86 |
torch_dtype=torch.float32,
|
| 87 |
)
|
| 88 |
+
_chronos_loaded = True
|
|
|
|
| 89 |
logger.info("Chronos loaded ✓")
|
| 90 |
except Exception as exc:
|
| 91 |
logger.warning("Chronos not loaded: %s", exc)
|
| 92 |
|
|
|
|
| 93 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 94 |
+
# Inference
|
| 95 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 96 |
|
| 97 |
+
def _predict_real(closes: list, feats: dict) -> dict:
|
|
|
|
| 98 |
import torch
|
| 99 |
+
c = np.array(closes[-64:], dtype=np.float32)
|
|
|
|
| 100 |
context = torch.tensor(c).unsqueeze(0)
|
| 101 |
with torch.no_grad():
|
| 102 |
+
forecast = _model.predict(context, prediction_length=2)
|
| 103 |
median = float(forecast[0].median(dim=0).values.mean().item())
|
| 104 |
last = float(c[-1])
|
| 105 |
score = _tanh((median / last - 1.0) * 20.0) if last != 0 else 0.0
|
| 106 |
+
return _score_to_prediction(score, f"Chronos: median={median:.2f} last={last:.2f}")
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
+
def _predict_bootstrap(closes: list, feats: dict) -> dict:
|
| 110 |
+
c = np.array(closes, dtype=np.float64)
|
| 111 |
+
n = len(c)
|
| 112 |
last = float(c[-1]) if n > 0 else 1.0
|
| 113 |
+
e20 = _ema(c[-max(40, n):], 20)
|
| 114 |
+
e50 = _ema(c[-max(80, n):], min(50, max(n // 2, 5)))
|
| 115 |
sl20 = _slope(c, min(20, n - 1))
|
| 116 |
rsi = float(feats.get("rsi") or 50.0)
|
|
|
|
| 117 |
score = (
|
| 118 |
math.copysign(min(1.0, abs(sl20) * 150.0), sl20) * 0.45 +
|
| 119 |
math.copysign(min(1.0, abs((e20 - e50) / last) * 200.0), (e20 - e50)) * 0.35 +
|
| 120 |
((rsi - 50.0) / 50.0) * 0.20
|
| 121 |
)
|
| 122 |
return _score_to_prediction(
|
| 123 |
+
score,
|
| 124 |
f"Chronos bootstrap: sl20={sl20*100:.4f}% ema_diff={((e20-e50)/last)*100:.4f}%",
|
| 125 |
)
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 128 |
# Endpoints
|
| 129 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 130 |
|
| 131 |
@app.get("/")
|
| 132 |
+
async def health():
|
| 133 |
return {
|
| 134 |
+
"ok": True,
|
| 135 |
+
"version": "20.0.0",
|
| 136 |
+
"space": "A",
|
| 137 |
+
"tier": "price_memory",
|
| 138 |
+
"models": ["Chronos"],
|
| 139 |
+
"chronos": _chronos_loaded,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
}
|
| 141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
+
@app.post("/predict")
|
| 144 |
+
async def predict(request: Request):
|
| 145 |
t0 = time.perf_counter()
|
| 146 |
body = await request.json()
|
| 147 |
|
| 148 |
closes = list(body.get("closes") or [])
|
| 149 |
if len(closes) < 16:
|
| 150 |
+
return JSONResponse(status_code=422, content={"error": "closes too short — need 16+"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
# Price-memory tier: only price-derived features allowed
|
| 153 |
+
allowed = {"rsi", "stoch_rsi_k", "stoch_rsi_d", "vwap_dev", "atr_pct_of_spot",
|
| 154 |
+
"atr", "bollinger_squeeze", "vol_regime", "vol_percentile",
|
| 155 |
+
"garman_klass_vol", "market_regime", "htf_trend_15m", "htf_trend_1h",
|
| 156 |
+
"candle_pattern", "nearest_support", "nearest_resistance", "session"}
|
| 157 |
+
feats = {k: v for k, v in body.items() if k != "closes" and k in allowed}
|
| 158 |
|
| 159 |
+
if _chronos_loaded and _model is not None:
|
|
|
|
| 160 |
try:
|
| 161 |
+
pred = _predict_real(closes, feats)
|
| 162 |
except Exception as exc:
|
| 163 |
logger.warning("Chronos real inference failed: %s", exc)
|
| 164 |
+
pred = _predict_bootstrap(closes, feats)
|
| 165 |
else:
|
| 166 |
+
pred = _predict_bootstrap(closes, feats)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
pred["latency_ms"] = round((time.perf_counter() - t0) * 1000)
|
| 169 |
+
return pred
|
|
|