Spaces:
Paused
Paused
Update backtest_engine.py
Browse files- backtest_engine.py +139 -153
backtest_engine.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# ============================================================
|
| 2 |
-
# 🧪 backtest_engine.py (
|
| 3 |
# ============================================================
|
| 4 |
|
| 5 |
import asyncio
|
|
@@ -55,7 +55,7 @@ class HeavyDutyBacktester:
|
|
| 55 |
self.force_end_date = None
|
| 56 |
|
| 57 |
if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR)
|
| 58 |
-
print(f"🧪 [Backtest
|
| 59 |
|
| 60 |
def set_date_range(self, start_str, end_str):
|
| 61 |
self.force_start_date = start_str
|
|
@@ -104,7 +104,7 @@ class HeavyDutyBacktester:
|
|
| 104 |
return unique_candles
|
| 105 |
|
| 106 |
# ==============================================================
|
| 107 |
-
# 🏎️ VECTORIZED INDICATORS
|
| 108 |
# ==============================================================
|
| 109 |
def _calculate_indicators_vectorized(self, df, timeframe='1m'):
|
| 110 |
df['close'] = df['close'].astype(float)
|
|
@@ -118,7 +118,6 @@ class HeavyDutyBacktester:
|
|
| 118 |
df['ema50'] = ta.ema(df['close'], length=50)
|
| 119 |
df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)
|
| 120 |
|
| 121 |
-
# Hydra
|
| 122 |
if timeframe == '1m':
|
| 123 |
sma20 = df['close'].rolling(20).mean()
|
| 124 |
std20 = df['close'].rolling(20).std()
|
|
@@ -126,14 +125,12 @@ class HeavyDutyBacktester:
|
|
| 126 |
df['vol_ma50'] = df['volume'].rolling(50).mean()
|
| 127 |
df['rel_vol'] = df['volume'] / (df['vol_ma50'] + 1e-9)
|
| 128 |
|
| 129 |
-
# Oracle
|
| 130 |
df['slope'] = ta.slope(df['close'], length=7)
|
| 131 |
vol_mean = df['volume'].rolling(20).mean()
|
| 132 |
vol_std = df['volume'].rolling(20).std()
|
| 133 |
df['vol_z'] = (df['volume'] - vol_mean) / (vol_std + 1e-9)
|
| 134 |
df['atr_pct'] = df['atr'] / df['close']
|
| 135 |
|
| 136 |
-
# Sniper
|
| 137 |
if timeframe == '1m':
|
| 138 |
df['ret'] = df['close'].pct_change()
|
| 139 |
df['dollar_vol'] = df['close'] * df['volume']
|
|
@@ -159,7 +156,6 @@ class HeavyDutyBacktester:
|
|
| 159 |
s = df['volume'].rolling(500).std()
|
| 160 |
df['vol_zscore_50'] = ((df['volume'] - r) / s).fillna(0)
|
| 161 |
|
| 162 |
-
# Legacy Structure
|
| 163 |
df['log_ret'] = np.log(df['close'] / df['close'].shift(1))
|
| 164 |
roll_max = df['high'].rolling(50).max()
|
| 165 |
roll_min = df['low'].rolling(50).min()
|
|
@@ -173,7 +169,7 @@ class HeavyDutyBacktester:
|
|
| 173 |
df['ema200'] = ta.ema(df['close'], length=200)
|
| 174 |
df['dist_ema200'] = (df['close'] - df['ema200']) / df['close']
|
| 175 |
|
| 176 |
-
#
|
| 177 |
if timeframe == '1m':
|
| 178 |
for lag in [1, 2, 3, 5, 10, 20]:
|
| 179 |
df[f'log_ret_lag_{lag}'] = df['log_ret'].shift(lag).fillna(0)
|
|
@@ -185,7 +181,7 @@ class HeavyDutyBacktester:
|
|
| 185 |
return df
|
| 186 |
|
| 187 |
# ==============================================================
|
| 188 |
-
# 🧠 CPU PROCESSING (
|
| 189 |
# ==============================================================
|
| 190 |
async def _process_data_in_memory(self, sym, candles, start_ms, end_ms):
|
| 191 |
safe_sym = sym.replace('/', '_')
|
|
@@ -196,7 +192,7 @@ class HeavyDutyBacktester:
|
|
| 196 |
print(f" 📂 [{sym}] Data Exists -> Skipping.")
|
| 197 |
return
|
| 198 |
|
| 199 |
-
print(f" ⚙️ [CPU] Analyzing {sym} (
|
| 200 |
t0 = time.time()
|
| 201 |
|
| 202 |
df_1m = pd.DataFrame(candles, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
|
|
@@ -207,7 +203,7 @@ class HeavyDutyBacktester:
|
|
| 207 |
frames = {}
|
| 208 |
agg_dict = {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'}
|
| 209 |
|
| 210 |
-
# 1. Calc 1m
|
| 211 |
frames['1m'] = self._calculate_indicators_vectorized(df_1m.copy(), timeframe='1m')
|
| 212 |
frames['1m']['timestamp'] = frames['1m'].index.floor('1min').astype(np.int64) // 10**6
|
| 213 |
fast_1m = {col: frames['1m'][col].values for col in frames['1m'].columns}
|
|
@@ -221,19 +217,93 @@ class HeavyDutyBacktester:
|
|
| 221 |
frames[tf_str] = resampled
|
| 222 |
numpy_htf[tf_str] = {col: resampled[col].values for col in resampled.columns}
|
| 223 |
|
| 224 |
-
# 3.
|
| 225 |
-
# Allows instant mapping from 1m index -> 5m/15m index without searching inside loop
|
| 226 |
-
# Using searchsorted on the whole array once
|
| 227 |
map_1m_to_1h = np.searchsorted(numpy_htf['1h']['timestamp'], fast_1m['timestamp'])
|
| 228 |
map_1m_to_5m = np.searchsorted(numpy_htf['5m']['timestamp'], fast_1m['timestamp'])
|
| 229 |
map_1m_to_15m = np.searchsorted(numpy_htf['15m']['timestamp'], fast_1m['timestamp'])
|
| 230 |
|
| 231 |
-
#
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
-
#
|
| 237 |
df_1h = frames['1h'].reindex(frames['5m'].index, method='ffill')
|
| 238 |
df_5m = frames['5m'].copy()
|
| 239 |
is_valid = (df_1h['rsi'] <= 70)
|
|
@@ -242,41 +312,28 @@ class HeavyDutyBacktester:
|
|
| 242 |
final_valid_indices = [t for t in valid_indices if t >= start_dt]
|
| 243 |
|
| 244 |
total_signals = len(final_valid_indices)
|
| 245 |
-
print(f" 🎯 Candidates: {total_signals}. Running
|
| 246 |
|
| 247 |
-
# 5. Load Models
|
| 248 |
-
hydra_models = getattr(self.proc.guardian_hydra, 'models', {}) if self.proc.guardian_hydra else {}
|
| 249 |
-
hydra_cols = getattr(self.proc.guardian_hydra, 'feature_cols', []) if self.proc.guardian_hydra else []
|
| 250 |
-
|
| 251 |
-
legacy_v2 = getattr(self.proc.guardian_legacy, 'model_v2', None)
|
| 252 |
-
legacy_v3 = getattr(self.proc.guardian_legacy, 'model_v3', None)
|
| 253 |
-
v3_feat_names = getattr(self.proc.guardian_legacy, 'v3_feature_names', [])
|
| 254 |
-
|
| 255 |
oracle_dir_model = getattr(self.proc.oracle, 'model_direction', None)
|
| 256 |
oracle_cols = getattr(self.proc.oracle, 'feature_cols', [])
|
| 257 |
sniper_models = getattr(self.proc.sniper, 'models', [])
|
| 258 |
sniper_cols = getattr(self.proc.sniper, 'feature_names', [])
|
| 259 |
|
| 260 |
-
ai_results = []
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
-
# ---
|
| 263 |
for i, current_time in enumerate(final_valid_indices):
|
| 264 |
-
if i > 0 and i % 1000 == 0:
|
| 265 |
-
print(f" ⏳ [{sym}] Processing... {i}/{total_signals}", flush=True)
|
| 266 |
-
|
| 267 |
ts_val = int(current_time.timestamp() * 1000)
|
| 268 |
-
|
| 269 |
-
# Find Entry Index
|
| 270 |
idx_1m = np.searchsorted(fast_1m['timestamp'], ts_val)
|
| 271 |
|
| 272 |
-
# Safety Check
|
| 273 |
if idx_1m < 500 or idx_1m >= len(fast_1m['close']) - 245: continue
|
| 274 |
|
| 275 |
-
# Determine Indices
|
| 276 |
idx_1h = map_1m_to_1h[idx_1m]
|
| 277 |
-
idx_5m = map_1m_to_5m[idx_1m]
|
| 278 |
idx_15m = map_1m_to_15m[idx_1m]
|
| 279 |
-
idx_4h = np.searchsorted(numpy_htf['4h']['timestamp'], ts_val)
|
| 280 |
if idx_4h >= len(numpy_htf['4h']['close']): idx_4h = len(numpy_htf['4h']['close']) - 1
|
| 281 |
|
| 282 |
# === Oracle (Single Call) ===
|
|
@@ -311,138 +368,73 @@ class HeavyDutyBacktester:
|
|
| 311 |
sniper_score = np.mean(s_preds)
|
| 312 |
except: pass
|
| 313 |
|
| 314 |
-
# === RISK SIMULATION (
|
| 315 |
-
# We construct a matrix of 240 rows (4 hours) at once and predict ONCE.
|
| 316 |
-
# This replaces the minute-by-minute loop.
|
| 317 |
-
|
| 318 |
-
future_len = 240
|
| 319 |
start_idx = idx_1m + 1
|
| 320 |
-
end_idx = start_idx +
|
| 321 |
-
|
| 322 |
-
# Slices for 1m data
|
| 323 |
-
sl_close = fast_1m['close'][start_idx:end_idx]
|
| 324 |
-
sl_ts = fast_1m['timestamp'][start_idx:end_idx]
|
| 325 |
-
|
| 326 |
-
entry_price = fast_1m['close'][idx_1m]
|
| 327 |
|
| 328 |
-
#
|
| 329 |
-
sl_map_5m = map_1m_to_5m[start_idx:end_idx]
|
| 330 |
-
sl_map_15m = map_1m_to_15m[start_idx:end_idx]
|
| 331 |
-
|
| 332 |
-
max_hydra_crash = 0.0; hydra_crash_time = 0
|
| 333 |
max_legacy_v2 = 0.0; legacy_panic_time = 0
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
|
| 346 |
-
# Calc
|
| 347 |
sl_dist = 1.5 * sl_atr
|
| 348 |
sl_dist = np.where(sl_dist > 0, sl_dist, entry_price * 0.015)
|
| 349 |
|
| 350 |
-
# PnL & Max PnL
|
| 351 |
sl_pnl = sl_close - entry_price
|
| 352 |
sl_norm_pnl = sl_pnl / sl_dist
|
| 353 |
|
| 354 |
-
# Max PnL needs cumulative max (rolling max from start of trade)
|
| 355 |
sl_cum_max = np.maximum.accumulate(sl_close)
|
| 356 |
-
# Correction: cum max of trade needs to start from entry price
|
| 357 |
sl_cum_max = np.maximum(sl_cum_max, entry_price)
|
| 358 |
sl_max_pnl_r = (sl_cum_max - entry_price) / sl_dist
|
| 359 |
|
| 360 |
sl_atr_pct = sl_atr / sl_close
|
| 361 |
-
sl_time = np.arange(1, future_len + 1)
|
| 362 |
|
| 363 |
-
#
|
| 364 |
-
#
|
| 365 |
-
# Map cols manually to speed up
|
| 366 |
|
| 367 |
-
#
|
| 368 |
-
|
| 369 |
-
'rsi_1m': sl_rsi_1m, 'rsi_5m': sl_rsi_5m, 'rsi_15m': sl_rsi_15m,
|
| 370 |
-
'bb_width': sl_bb, 'rel_vol': sl_vol,
|
| 371 |
-
'dist_ema20_1h': np.zeros(future_len),
|
| 372 |
-
'atr_pct': sl_atr_pct, 'norm_pnl_r': sl_norm_pnl, 'max_pnl_r': sl_max_pnl_r,
|
| 373 |
-
'dist_tp_atr': np.zeros(future_len), 'dist_sl_atr': np.zeros(future_len),
|
| 374 |
-
'time_in_trade': sl_time,
|
| 375 |
-
'entry_type': np.zeros(future_len), 'oracle_conf': np.full(future_len, oracle_conf),
|
| 376 |
-
'l2_score': np.full(future_len, 0.7), 'target_class': np.full(future_len, 3.0)
|
| 377 |
-
}
|
| 378 |
|
| 379 |
-
#
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
try:
|
| 383 |
-
# ONE PREDICTION FOR 240 ROWS
|
| 384 |
probs_crash = hydra_models['crash'].predict_proba(X_hydra)[:, 1]
|
| 385 |
-
|
| 386 |
-
# Find Max
|
| 387 |
max_hydra_crash = np.max(probs_crash)
|
| 388 |
-
|
| 389 |
-
# Find Time
|
| 390 |
crash_indices = np.where(probs_crash > 0.6)[0]
|
| 391 |
if len(crash_indices) > 0:
|
| 392 |
-
hydra_crash_time = int(
|
| 393 |
except: pass
|
| 394 |
|
| 395 |
-
# --- B. Legacy V2 Batch ---
|
| 396 |
-
if legacy_v2:
|
| 397 |
-
# 1m Feats
|
| 398 |
-
l_log = fast_1m['log_ret'][start_idx:end_idx]
|
| 399 |
-
l_rsi = fast_1m['rsi'][start_idx:end_idx] / 100.0
|
| 400 |
-
l_fib = fast_1m['fib_pos'][start_idx:end_idx]
|
| 401 |
-
l_vol = fast_1m['volatility'][start_idx:end_idx]
|
| 402 |
-
|
| 403 |
-
# 5m Feats (Mapped)
|
| 404 |
-
l5_log = numpy_htf['5m']['log_ret'][sl_map_5m]
|
| 405 |
-
l5_rsi = numpy_htf['5m']['rsi'][sl_map_5m] / 100.0
|
| 406 |
-
l5_fib = numpy_htf['5m']['fib_pos'][sl_map_5m]
|
| 407 |
-
l5_trd = numpy_htf['5m']['trend_slope'][sl_map_5m]
|
| 408 |
-
|
| 409 |
-
# 15m Feats (Mapped)
|
| 410 |
-
l15_log = numpy_htf['15m']['log_ret'][sl_map_15m]
|
| 411 |
-
l15_rsi = numpy_htf['15m']['rsi'][sl_map_15m] / 100.0
|
| 412 |
-
l15_fib618 = numpy_htf['15m']['dist_fib618'][sl_map_15m]
|
| 413 |
-
l15_trd = numpy_htf['15m']['trend_slope'][sl_map_15m]
|
| 414 |
-
|
| 415 |
-
# Lags (Pre-calculated in _calculate_indicators_vectorized)
|
| 416 |
-
# We just pull them from fast_1m
|
| 417 |
-
lag_cols = []
|
| 418 |
-
for lag in [1, 2, 3, 5, 10, 20]:
|
| 419 |
-
lag_cols.append(fast_1m[f'log_ret_lag_{lag}'][start_idx:end_idx])
|
| 420 |
-
lag_cols.append(fast_1m[f'rsi_lag_{lag}'][start_idx:end_idx])
|
| 421 |
-
lag_cols.append(fast_1m[f'fib_pos_lag_{lag}'][start_idx:end_idx])
|
| 422 |
-
lag_cols.append(fast_1m[f'volatility_lag_{lag}'][start_idx:end_idx])
|
| 423 |
-
|
| 424 |
-
# Stack All
|
| 425 |
-
X_v2 = np.column_stack([
|
| 426 |
-
l_log, l_rsi, l_fib, l_vol,
|
| 427 |
-
l5_log, l5_rsi, l5_fib, l5_trd,
|
| 428 |
-
l15_log, l15_rsi, l15_fib618, l15_trd,
|
| 429 |
-
*lag_cols
|
| 430 |
-
])
|
| 431 |
-
|
| 432 |
-
try:
|
| 433 |
-
# PREDICT BATCH
|
| 434 |
-
dm_v2 = xgb.DMatrix(X_v2)
|
| 435 |
-
preds_v2 = legacy_v2.predict(dm_v2)
|
| 436 |
-
# Handle Multiclass
|
| 437 |
-
probs_v2 = preds_v2[:, 2] if len(preds_v2.shape) > 1 else preds_v2
|
| 438 |
-
|
| 439 |
-
max_legacy_v2 = np.max(probs_v2)
|
| 440 |
-
panic_idx = np.where(probs_v2 > 0.8)[0]
|
| 441 |
-
if len(panic_idx) > 0 and legacy_panic_time == 0:
|
| 442 |
-
legacy_panic_time = int(sl_ts[panic_idx[0]])
|
| 443 |
-
except: pass
|
| 444 |
-
|
| 445 |
-
# --- Store Result ---
|
| 446 |
ai_results.append({
|
| 447 |
'timestamp': ts_val, 'symbol': sym, 'close': entry_price,
|
| 448 |
'real_titan': 0.6,
|
|
@@ -459,11 +451,11 @@ class HeavyDutyBacktester:
|
|
| 459 |
dt = time.time() - t0
|
| 460 |
if ai_results:
|
| 461 |
pd.DataFrame(ai_results).to_pickle(scores_file)
|
| 462 |
-
print(f" ✅ [{sym}]
|
| 463 |
else:
|
| 464 |
print(f" ⚠️ [{sym}] No valid signals. Time: {dt:.2f}s", flush=True)
|
| 465 |
|
| 466 |
-
del frames, fast_1m, numpy_htf
|
| 467 |
gc.collect()
|
| 468 |
|
| 469 |
# ==============================================================
|
|
@@ -508,16 +500,13 @@ class HeavyDutyBacktester:
|
|
| 508 |
for ts, group in grouped_by_time:
|
| 509 |
active = list(wallet["positions"].keys())
|
| 510 |
current_prices = {row['symbol']: row['close'] for _, row in group.iterrows()}
|
| 511 |
-
|
| 512 |
for sym in active:
|
| 513 |
if sym in current_prices:
|
| 514 |
curr = current_prices[sym]
|
| 515 |
pos = wallet["positions"][sym]
|
| 516 |
-
|
| 517 |
h_risk = pos.get('risk_hydra_crash', 0)
|
| 518 |
h_time = pos.get('time_hydra_crash', 0)
|
| 519 |
is_crash = (h_risk > hydra_thresh) and (h_time > 0) and (ts >= h_time)
|
| 520 |
-
|
| 521 |
pnl = (curr - pos['entry']) / pos['entry']
|
| 522 |
if is_crash or pnl > 0.04 or pnl < -0.02:
|
| 523 |
wallet['balance'] += pos['size'] * (1 + pnl - (fees_pct*2))
|
|
@@ -569,7 +558,6 @@ class HeavyDutyBacktester:
|
|
| 569 |
'config': config, 'final_balance': final_bal, 'net_profit': net_profit,
|
| 570 |
'total_trades': total_t, 'win_count': win_count, 'loss_count': loss_count,
|
| 571 |
'win_rate': win_rate, 'max_single_win': max_win, 'max_single_loss': max_loss,
|
| 572 |
-
'max_win_streak': max_win_streak, 'max_loss_streak': max_loss_streak,
|
| 573 |
'max_drawdown': max_drawdown * 100
|
| 574 |
})
|
| 575 |
|
|
@@ -577,11 +565,9 @@ class HeavyDutyBacktester:
|
|
| 577 |
|
| 578 |
async def run_optimization(self, target_regime="RANGE"):
|
| 579 |
await self.generate_truth_data()
|
| 580 |
-
|
| 581 |
oracle_range = [0.5, 0.6, 0.7]
|
| 582 |
sniper_range = [0.4, 0.5, 0.6]
|
| 583 |
hydra_range = [0.75, 0.85, 0.95]
|
| 584 |
-
|
| 585 |
combinations = []
|
| 586 |
for o, s, h in itertools.product(oracle_range, sniper_range, hydra_range):
|
| 587 |
combinations.append({
|
|
@@ -595,7 +581,6 @@ class HeavyDutyBacktester:
|
|
| 595 |
|
| 596 |
print(f"\n🧩 [Phase 2] Optimizing {len(combinations)} Configs (Full Stack) for {target_regime}...")
|
| 597 |
best_res = self._worker_optimize(combinations, current_period_files, self.INITIAL_CAPITAL, self.TRADING_FEES, self.MAX_SLOTS)
|
| 598 |
-
|
| 599 |
if not best_res: return None, None
|
| 600 |
best = sorted(best_res, key=lambda x: x['final_balance'], reverse=True)[0]
|
| 601 |
|
|
@@ -618,6 +603,7 @@ class HeavyDutyBacktester:
|
|
| 618 |
print("-" * 60)
|
| 619 |
print(f" ⚙️ Oracle={best['config']['oracle_thresh']} | Sniper={best['config']['sniper_thresh']} | Hydra={best['config']['hydra_thresh']}")
|
| 620 |
print("="*60)
|
|
|
|
| 621 |
|
| 622 |
async def run_strategic_optimization_task():
|
| 623 |
print("\n🧪 [STRATEGIC BACKTEST] Full Stack Mode...")
|
|
|
|
| 1 |
# ============================================================
|
| 2 |
+
# 🧪 backtest_engine.py (V113.0 - GEM-Architect: Global Pre-Inference)
|
| 3 |
# ============================================================
|
| 4 |
|
| 5 |
import asyncio
|
|
|
|
| 55 |
self.force_end_date = None
|
| 56 |
|
| 57 |
if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR)
|
| 58 |
+
print(f"🧪 [Backtest V113.0] Pre-Inference Velocity Mode (Target: 60s).")
|
| 59 |
|
| 60 |
def set_date_range(self, start_str, end_str):
|
| 61 |
self.force_start_date = start_str
|
|
|
|
| 104 |
return unique_candles
|
| 105 |
|
| 106 |
# ==============================================================
|
| 107 |
+
# 🏎️ VECTORIZED INDICATORS
|
| 108 |
# ==============================================================
|
| 109 |
def _calculate_indicators_vectorized(self, df, timeframe='1m'):
|
| 110 |
df['close'] = df['close'].astype(float)
|
|
|
|
| 118 |
df['ema50'] = ta.ema(df['close'], length=50)
|
| 119 |
df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)
|
| 120 |
|
|
|
|
| 121 |
if timeframe == '1m':
|
| 122 |
sma20 = df['close'].rolling(20).mean()
|
| 123 |
std20 = df['close'].rolling(20).std()
|
|
|
|
| 125 |
df['vol_ma50'] = df['volume'].rolling(50).mean()
|
| 126 |
df['rel_vol'] = df['volume'] / (df['vol_ma50'] + 1e-9)
|
| 127 |
|
|
|
|
| 128 |
df['slope'] = ta.slope(df['close'], length=7)
|
| 129 |
vol_mean = df['volume'].rolling(20).mean()
|
| 130 |
vol_std = df['volume'].rolling(20).std()
|
| 131 |
df['vol_z'] = (df['volume'] - vol_mean) / (vol_std + 1e-9)
|
| 132 |
df['atr_pct'] = df['atr'] / df['close']
|
| 133 |
|
|
|
|
| 134 |
if timeframe == '1m':
|
| 135 |
df['ret'] = df['close'].pct_change()
|
| 136 |
df['dollar_vol'] = df['close'] * df['volume']
|
|
|
|
| 156 |
s = df['volume'].rolling(500).std()
|
| 157 |
df['vol_zscore_50'] = ((df['volume'] - r) / s).fillna(0)
|
| 158 |
|
|
|
|
| 159 |
df['log_ret'] = np.log(df['close'] / df['close'].shift(1))
|
| 160 |
roll_max = df['high'].rolling(50).max()
|
| 161 |
roll_min = df['low'].rolling(50).min()
|
|
|
|
| 169 |
df['ema200'] = ta.ema(df['close'], length=200)
|
| 170 |
df['dist_ema200'] = (df['close'] - df['ema200']) / df['close']
|
| 171 |
|
| 172 |
+
# Lags for V2
|
| 173 |
if timeframe == '1m':
|
| 174 |
for lag in [1, 2, 3, 5, 10, 20]:
|
| 175 |
df[f'log_ret_lag_{lag}'] = df['log_ret'].shift(lag).fillna(0)
|
|
|
|
| 181 |
return df
|
| 182 |
|
| 183 |
# ==============================================================
|
| 184 |
+
# 🧠 CPU PROCESSING (PRE-INFERENCE OPTIMIZED)
|
| 185 |
# ==============================================================
|
| 186 |
async def _process_data_in_memory(self, sym, candles, start_ms, end_ms):
|
| 187 |
safe_sym = sym.replace('/', '_')
|
|
|
|
| 192 |
print(f" 📂 [{sym}] Data Exists -> Skipping.")
|
| 193 |
return
|
| 194 |
|
| 195 |
+
print(f" ⚙️ [CPU] Analyzing {sym} (Global Pre-Inference)...", flush=True)
|
| 196 |
t0 = time.time()
|
| 197 |
|
| 198 |
df_1m = pd.DataFrame(candles, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
|
|
|
|
| 203 |
frames = {}
|
| 204 |
agg_dict = {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum'}
|
| 205 |
|
| 206 |
+
# 1. Calc 1m
|
| 207 |
frames['1m'] = self._calculate_indicators_vectorized(df_1m.copy(), timeframe='1m')
|
| 208 |
frames['1m']['timestamp'] = frames['1m'].index.floor('1min').astype(np.int64) // 10**6
|
| 209 |
fast_1m = {col: frames['1m'][col].values for col in frames['1m'].columns}
|
|
|
|
| 217 |
frames[tf_str] = resampled
|
| 218 |
numpy_htf[tf_str] = {col: resampled[col].values for col in resampled.columns}
|
| 219 |
|
| 220 |
+
# 3. Global Index Maps
|
|
|
|
|
|
|
| 221 |
map_1m_to_1h = np.searchsorted(numpy_htf['1h']['timestamp'], fast_1m['timestamp'])
|
| 222 |
map_1m_to_5m = np.searchsorted(numpy_htf['5m']['timestamp'], fast_1m['timestamp'])
|
| 223 |
map_1m_to_15m = np.searchsorted(numpy_htf['15m']['timestamp'], fast_1m['timestamp'])
|
| 224 |
|
| 225 |
+
# Clip
|
| 226 |
+
max_idx_1h = len(numpy_htf['1h']['timestamp']) - 1
|
| 227 |
+
max_idx_5m = len(numpy_htf['5m']['timestamp']) - 1
|
| 228 |
+
max_idx_15m = len(numpy_htf['15m']['timestamp']) - 1
|
| 229 |
+
|
| 230 |
+
map_1m_to_1h = np.clip(map_1m_to_1h, 0, max_idx_1h)
|
| 231 |
+
map_1m_to_5m = np.clip(map_1m_to_5m, 0, max_idx_5m)
|
| 232 |
+
map_1m_to_15m = np.clip(map_1m_to_15m, 0, max_idx_15m)
|
| 233 |
+
|
| 234 |
+
# 4. Load Models
|
| 235 |
+
hydra_models = getattr(self.proc.guardian_hydra, 'models', {}) if self.proc.guardian_hydra else {}
|
| 236 |
+
hydra_cols = getattr(self.proc.guardian_hydra, 'feature_cols', []) if self.proc.guardian_hydra else []
|
| 237 |
+
legacy_v2 = getattr(self.proc.guardian_legacy, 'model_v2', None)
|
| 238 |
+
|
| 239 |
+
# 5. 🔥 PRE-CALCULATE LEGACY V2 (GLOBAL) 🔥
|
| 240 |
+
# V2 depends only on structure, not entry price. We can predict for ALL rows at once.
|
| 241 |
+
global_v2_probs = np.zeros(len(fast_1m['close']))
|
| 242 |
+
|
| 243 |
+
if legacy_v2:
|
| 244 |
+
print(f" 🚀 Pre-calculating Legacy V2 for entire history...", flush=True)
|
| 245 |
+
try:
|
| 246 |
+
# 1m Feats
|
| 247 |
+
l_log = fast_1m['log_ret']
|
| 248 |
+
l_rsi = fast_1m['rsi'] / 100.0
|
| 249 |
+
l_fib = fast_1m['fib_pos']
|
| 250 |
+
l_vol = fast_1m['volatility']
|
| 251 |
+
|
| 252 |
+
# HTF Feats Mapped to 1m
|
| 253 |
+
l5_log = numpy_htf['5m']['log_ret'][map_1m_to_5m]
|
| 254 |
+
l5_rsi = numpy_htf['5m']['rsi'][map_1m_to_5m] / 100.0
|
| 255 |
+
l5_fib = numpy_htf['5m']['fib_pos'][map_1m_to_5m]
|
| 256 |
+
l5_trd = numpy_htf['5m']['trend_slope'][map_1m_to_5m]
|
| 257 |
+
|
| 258 |
+
l15_log = numpy_htf['15m']['log_ret'][map_1m_to_15m]
|
| 259 |
+
l15_rsi = numpy_htf['15m']['rsi'][map_1m_to_15m] / 100.0
|
| 260 |
+
l15_fib618 = numpy_htf['15m']['dist_fib618'][map_1m_to_15m]
|
| 261 |
+
l15_trd = numpy_htf['15m']['trend_slope'][map_1m_to_15m]
|
| 262 |
+
|
| 263 |
+
# Lags
|
| 264 |
+
lag_cols = []
|
| 265 |
+
for lag in [1, 2, 3, 5, 10, 20]:
|
| 266 |
+
lag_cols.append(fast_1m[f'log_ret_lag_{lag}'])
|
| 267 |
+
lag_cols.append(fast_1m[f'rsi_lag_{lag}'])
|
| 268 |
+
lag_cols.append(fast_1m[f'fib_pos_lag_{lag}'])
|
| 269 |
+
lag_cols.append(fast_1m[f'volatility_lag_{lag}'])
|
| 270 |
+
|
| 271 |
+
# Huge Matrix
|
| 272 |
+
X_GLOBAL_V2 = np.column_stack([
|
| 273 |
+
l_log, l_rsi, l_fib, l_vol,
|
| 274 |
+
l5_log, l5_rsi, l5_fib, l5_trd,
|
| 275 |
+
l15_log, l15_rsi, l15_fib618, l15_trd,
|
| 276 |
+
*lag_cols
|
| 277 |
+
])
|
| 278 |
+
|
| 279 |
+
# Predict All in One Go
|
| 280 |
+
dm_glob = xgb.DMatrix(X_GLOBAL_V2)
|
| 281 |
+
preds_glob = legacy_v2.predict(dm_glob)
|
| 282 |
+
global_v2_probs = preds_glob[:, 2] if len(preds_glob.shape) > 1 else preds_glob
|
| 283 |
+
|
| 284 |
+
except Exception as e: print(f"V2 Error: {e}")
|
| 285 |
+
|
| 286 |
+
# 6. 🔥 PRE-ASSEMBLE HYDRA STATIC (GLOBAL) 🔥
|
| 287 |
+
# Hydra needs PnL (dynamic), but 90% features are static.
|
| 288 |
+
global_hydra_static = None
|
| 289 |
+
if hydra_models:
|
| 290 |
+
print(f" 🚀 Pre-assembling Hydra features...", flush=True)
|
| 291 |
+
try:
|
| 292 |
+
# Map columns that don't depend on PnL
|
| 293 |
+
h_rsi_1m = fast_1m['rsi']
|
| 294 |
+
h_rsi_5m = numpy_htf['5m']['rsi'][map_1m_to_5m]
|
| 295 |
+
h_rsi_15m = numpy_htf['15m']['rsi'][map_1m_to_15m]
|
| 296 |
+
h_bb = fast_1m['bb_width']
|
| 297 |
+
h_vol = fast_1m['rel_vol']
|
| 298 |
+
h_atr = fast_1m['atr']
|
| 299 |
+
h_close = fast_1m['close']
|
| 300 |
+
|
| 301 |
+
# We store these separate to combine inside loop efficiently
|
| 302 |
+
# [rsi1, rsi5, rsi15, bb, vol, atr, close]
|
| 303 |
+
global_hydra_static = np.column_stack([h_rsi_1m, h_rsi_5m, h_rsi_15m, h_bb, h_vol, h_atr, h_close])
|
| 304 |
+
except: pass
|
| 305 |
|
| 306 |
+
# 7. Candidate Filtering
|
| 307 |
df_1h = frames['1h'].reindex(frames['5m'].index, method='ffill')
|
| 308 |
df_5m = frames['5m'].copy()
|
| 309 |
is_valid = (df_1h['rsi'] <= 70)
|
|
|
|
| 312 |
final_valid_indices = [t for t in valid_indices if t >= start_dt]
|
| 313 |
|
| 314 |
total_signals = len(final_valid_indices)
|
| 315 |
+
print(f" 🎯 Candidates: {total_signals}. Running Models...", flush=True)
|
| 316 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
oracle_dir_model = getattr(self.proc.oracle, 'model_direction', None)
|
| 318 |
oracle_cols = getattr(self.proc.oracle, 'feature_cols', [])
|
| 319 |
sniper_models = getattr(self.proc.sniper, 'models', [])
|
| 320 |
sniper_cols = getattr(self.proc.sniper, 'feature_names', [])
|
| 321 |
|
| 322 |
+
ai_results = []
|
| 323 |
+
|
| 324 |
+
# Pre-allocate Hydra time vector (0 to 240)
|
| 325 |
+
time_vec = np.arange(1, 241)
|
| 326 |
|
| 327 |
+
# --- MAIN LOOP (Optimized Lookups) ---
|
| 328 |
for i, current_time in enumerate(final_valid_indices):
|
|
|
|
|
|
|
|
|
|
| 329 |
ts_val = int(current_time.timestamp() * 1000)
|
|
|
|
|
|
|
| 330 |
idx_1m = np.searchsorted(fast_1m['timestamp'], ts_val)
|
| 331 |
|
|
|
|
| 332 |
if idx_1m < 500 or idx_1m >= len(fast_1m['close']) - 245: continue
|
| 333 |
|
|
|
|
| 334 |
idx_1h = map_1m_to_1h[idx_1m]
|
|
|
|
| 335 |
idx_15m = map_1m_to_15m[idx_1m]
|
| 336 |
+
idx_4h = np.searchsorted(numpy_htf['4h']['timestamp'], ts_val)
|
| 337 |
if idx_4h >= len(numpy_htf['4h']['close']): idx_4h = len(numpy_htf['4h']['close']) - 1
|
| 338 |
|
| 339 |
# === Oracle (Single Call) ===
|
|
|
|
| 368 |
sniper_score = np.mean(s_preds)
|
| 369 |
except: pass
|
| 370 |
|
| 371 |
+
# === RISK SIMULATION (ULTRA FAST) ===
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
start_idx = idx_1m + 1
|
| 373 |
+
end_idx = start_idx + 240
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
|
| 375 |
+
# 1. LEGACY V2 (Instant Lookup)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
max_legacy_v2 = 0.0; legacy_panic_time = 0
|
| 377 |
+
if legacy_v2:
|
| 378 |
+
# Just slice the pre-calculated array!
|
| 379 |
+
probs_slice = global_v2_probs[start_idx:end_idx]
|
| 380 |
+
max_legacy_v2 = np.max(probs_slice)
|
| 381 |
+
panic_indices = np.where(probs_slice > 0.8)[0]
|
| 382 |
+
if len(panic_indices) > 0:
|
| 383 |
+
legacy_panic_time = int(fast_1m['timestamp'][start_idx + panic_indices[0]])
|
| 384 |
+
|
| 385 |
+
# 2. HYDRA (Semi-Vectorized)
|
| 386 |
+
max_hydra_crash = 0.0; hydra_crash_time = 0
|
| 387 |
+
if hydra_models and global_hydra_static is not None:
|
| 388 |
+
# Slice Static Feats
|
| 389 |
+
sl_static = global_hydra_static[start_idx:end_idx] # [rsi1, rsi5, rsi15, bb, vol, atr, close]
|
| 390 |
|
| 391 |
+
entry_price = fast_1m['close'][idx_1m]
|
| 392 |
+
sl_close = sl_static[:, 6]
|
| 393 |
+
sl_atr = sl_static[:, 5]
|
| 394 |
|
| 395 |
+
# Calc Dynamic Feats
|
| 396 |
sl_dist = 1.5 * sl_atr
|
| 397 |
sl_dist = np.where(sl_dist > 0, sl_dist, entry_price * 0.015)
|
| 398 |
|
|
|
|
| 399 |
sl_pnl = sl_close - entry_price
|
| 400 |
sl_norm_pnl = sl_pnl / sl_dist
|
| 401 |
|
|
|
|
| 402 |
sl_cum_max = np.maximum.accumulate(sl_close)
|
|
|
|
| 403 |
sl_cum_max = np.maximum(sl_cum_max, entry_price)
|
| 404 |
sl_max_pnl_r = (sl_cum_max - entry_price) / sl_dist
|
| 405 |
|
| 406 |
sl_atr_pct = sl_atr / sl_close
|
|
|
|
| 407 |
|
| 408 |
+
# Map to Hydra Cols Order (Hardcoded for max speed)
|
| 409 |
+
# Cols: rsi_1m, rsi_5m, rsi_15m, bb_width, rel_vol, dist_ema20_1h, atr_pct, norm_pnl_r, max_pnl_r, dists..., time, entry, oracle, l2, target
|
|
|
|
| 410 |
|
| 411 |
+
# Re-assemble only what is needed
|
| 412 |
+
# (Static 0-4) + (Zeros) + (Dynamic) + (Constants)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
|
| 414 |
+
# Create arrays for constants
|
| 415 |
+
zeros = np.zeros(240)
|
| 416 |
+
oracle_arr = np.full(240, oracle_conf)
|
| 417 |
+
l2_arr = np.full(240, 0.7)
|
| 418 |
+
target_arr = np.full(240, 3.0)
|
| 419 |
+
|
| 420 |
+
X_hydra = np.column_stack([
|
| 421 |
+
sl_static[:, 0], sl_static[:, 1], sl_static[:, 2], # RSIs
|
| 422 |
+
sl_static[:, 3], sl_static[:, 4], # BB, Vol
|
| 423 |
+
zeros, # dist_ema
|
| 424 |
+
sl_atr_pct, sl_norm_pnl, sl_max_pnl_r,
|
| 425 |
+
zeros, zeros, # dists
|
| 426 |
+
time_vec, # time
|
| 427 |
+
zeros, oracle_arr, l2_arr, target_arr
|
| 428 |
+
])
|
| 429 |
|
| 430 |
try:
|
|
|
|
| 431 |
probs_crash = hydra_models['crash'].predict_proba(X_hydra)[:, 1]
|
|
|
|
|
|
|
| 432 |
max_hydra_crash = np.max(probs_crash)
|
|
|
|
|
|
|
| 433 |
crash_indices = np.where(probs_crash > 0.6)[0]
|
| 434 |
if len(crash_indices) > 0:
|
| 435 |
+
hydra_crash_time = int(fast_1m['timestamp'][start_idx + crash_indices[0]])
|
| 436 |
except: pass
|
| 437 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
ai_results.append({
|
| 439 |
'timestamp': ts_val, 'symbol': sym, 'close': entry_price,
|
| 440 |
'real_titan': 0.6,
|
|
|
|
| 451 |
dt = time.time() - t0
|
| 452 |
if ai_results:
|
| 453 |
pd.DataFrame(ai_results).to_pickle(scores_file)
|
| 454 |
+
print(f" ✅ [{sym}] Completed {len(ai_results)} signals in {dt:.2f} seconds.", flush=True)
|
| 455 |
else:
|
| 456 |
print(f" ⚠️ [{sym}] No valid signals. Time: {dt:.2f}s", flush=True)
|
| 457 |
|
| 458 |
+
del frames, fast_1m, numpy_htf, global_v2_probs, global_hydra_static
|
| 459 |
gc.collect()
|
| 460 |
|
| 461 |
# ==============================================================
|
|
|
|
| 500 |
for ts, group in grouped_by_time:
|
| 501 |
active = list(wallet["positions"].keys())
|
| 502 |
current_prices = {row['symbol']: row['close'] for _, row in group.iterrows()}
|
|
|
|
| 503 |
for sym in active:
|
| 504 |
if sym in current_prices:
|
| 505 |
curr = current_prices[sym]
|
| 506 |
pos = wallet["positions"][sym]
|
|
|
|
| 507 |
h_risk = pos.get('risk_hydra_crash', 0)
|
| 508 |
h_time = pos.get('time_hydra_crash', 0)
|
| 509 |
is_crash = (h_risk > hydra_thresh) and (h_time > 0) and (ts >= h_time)
|
|
|
|
| 510 |
pnl = (curr - pos['entry']) / pos['entry']
|
| 511 |
if is_crash or pnl > 0.04 or pnl < -0.02:
|
| 512 |
wallet['balance'] += pos['size'] * (1 + pnl - (fees_pct*2))
|
|
|
|
| 558 |
'config': config, 'final_balance': final_bal, 'net_profit': net_profit,
|
| 559 |
'total_trades': total_t, 'win_count': win_count, 'loss_count': loss_count,
|
| 560 |
'win_rate': win_rate, 'max_single_win': max_win, 'max_single_loss': max_loss,
|
|
|
|
| 561 |
'max_drawdown': max_drawdown * 100
|
| 562 |
})
|
| 563 |
|
|
|
|
| 565 |
|
| 566 |
async def run_optimization(self, target_regime="RANGE"):
|
| 567 |
await self.generate_truth_data()
|
|
|
|
| 568 |
oracle_range = [0.5, 0.6, 0.7]
|
| 569 |
sniper_range = [0.4, 0.5, 0.6]
|
| 570 |
hydra_range = [0.75, 0.85, 0.95]
|
|
|
|
| 571 |
combinations = []
|
| 572 |
for o, s, h in itertools.product(oracle_range, sniper_range, hydra_range):
|
| 573 |
combinations.append({
|
|
|
|
| 581 |
|
| 582 |
print(f"\n🧩 [Phase 2] Optimizing {len(combinations)} Configs (Full Stack) for {target_regime}...")
|
| 583 |
best_res = self._worker_optimize(combinations, current_period_files, self.INITIAL_CAPITAL, self.TRADING_FEES, self.MAX_SLOTS)
|
|
|
|
| 584 |
if not best_res: return None, None
|
| 585 |
best = sorted(best_res, key=lambda x: x['final_balance'], reverse=True)[0]
|
| 586 |
|
|
|
|
| 603 |
print("-" * 60)
|
| 604 |
print(f" ⚙️ Oracle={best['config']['oracle_thresh']} | Sniper={best['config']['sniper_thresh']} | Hydra={best['config']['hydra_thresh']}")
|
| 605 |
print("="*60)
|
| 606 |
+
return best['config'], best
|
| 607 |
|
| 608 |
async def run_strategic_optimization_task():
|
| 609 |
print("\n🧪 [STRATEGIC BACKTEST] Full Stack Mode...")
|