#!/usr/bin/env python3 """ Fire Eye V8 — Walk-Forward Backtest Engine (Cross-Sectional Stock Selection). Reads features (all_features_2018_2026.parquet) + raw OHLCV (cn_and_us_unified.parquet), trains LightGBM in 5 walk-forward windows, simulates a top-K long/short portfolio with configurable rebalance, stop-loss, and trading costs. Usage: python backtest.py --run python backtest.py --run --top-k 50 --rebalance-days 10 --label top20_binary python backtest.py --run --local-parquet /path/to/all_features.parquet --local-raw /path/to/raw.parquet """ import argparse import gc import json import os import sys import warnings from datetime import datetime, timedelta from pathlib import Path import duckdb import numpy as np import pandas as pd import lightgbm as lgb import pyarrow.parquet as pq from sklearn.metrics import roc_auc_score warnings.filterwarnings("ignore") # ────────── Constants ────────── HF_REPO = "cedwyh/jinjing-shared-data" HF_FILE = "all_features_2018_2026.parquet" HF_RAW = "cn_and_us_unified.parquet" OUT_DIR = Path(__file__).parent RESULTS_DIR = OUT_DIR / "results" TRADING_DAYS_PER_YEAR = 242 # Same 5 walk-forward windows as train_v2.py WINDOWS = [ # Window 1: train end 2022-11-30 → ~20 trading day gap before test 2023-01-01 ('2018-01-01', '2022-11-30', '2023-01-01', '2024-06-30'), # Window 2: train end 2023-06-01 → ~20 trading day gap before test 2023-07-01 ('2018-06-01', '2023-06-01', '2023-07-01', '2024-12-31'), # Window 3: train end 2024-05-31 → ~20 trading day gap before test 2024-07-01 ('2019-01-01', '2024-05-31', '2024-07-01', '2025-06-30'), # Window 4: contiguous (last windows need maximal test data) ('2019-06-01', '2024-12-31', '2025-01-01', '2025-12-31'), # Window 5: last window — no gap, test goes to data end ('2020-01-01', '2024-12-31', '2025-01-01', '2026-04-10'), ] EXCLUDE_COLS = {"symbol", "date", "label"} # All 66 feature columns from the parquet schema ALL_FEATURE_COLS = [ 'ret_1d', 'ret_2d', 'ret_3d', 'ret_5d', 'ret_10d', 'ret_20d', 'ret_30d', 'ret_60d', 'ma_5', 'ma_10', 'ma_20', 'ma_30', 'ma_60', 'ma_120', 'ma_200', 'close_above_ma5', 'close_above_ma10', 'close_above_ma20', 'close_above_ma30', 'close_above_ma60', 'close_above_ma120', 'close_above_ma200', 'ema_12', 'ema_26', 'macd', 'macd_signal', 'macd_hist', 'rsi_6', 'rsi_12', 'rsi_24', 'volatility_10d', 'volatility_20d', 'vol_ma5', 'vol_ratio_5', 'vol_ma20', 'vol_ratio_20', 'roc_5', 'roc_10', 'roc_20', 'roc_30', 'bb_upper_10', 'bb_lower_10', 'bb_pos_10', 'bb_upper_20', 'bb_lower_20', 'bb_pos_20', 'atr_14', 'atr_30', 'kdj_k_9', 'kdj_d_9', 'kdj_j_9', 'kdj_k_14', 'kdj_d_14', 'kdj_j_14', 'close_pos_20d', 'close_pos_60d', 'buy1', 'buy2', 'buy3', 'sell1', 'sell2', 'sell3', 'bi_strength', 'zhongshu_amplitude', 'dist_last_buy', 'bi_zhongshu_count', ] # Pruned feature set (~15) based on IC/IC-IR analysis across 6 redundancy clusters. # Selects 1-2 best representatives per cluster + independently useful features. SELECTED_FEATURE_COLS = [ # RETURN cluster: ret_1d + ret_20d (short + medium momentum) 'ret_1d', 'ret_20d', # MA cluster: ma_20 + ma_200 (medium trend + long-term trend) 'ma_20', 'ma_200', # MACD cluster: macd_hist (momentum oscillator) 'macd_hist', # KDJ cluster: kdj_j_14 (stochastic oscillator, J-line) 'kdj_j_14', # BB + VOLATILITY cluster: bb_pos_20 + volatility_20d 'bb_pos_20', 'volatility_20d', # CHAN cluster: bi_strength + sell2 (structural break + supply signal) 'bi_strength', 'sell2', # Independently useful features 'rsi_12', 'vol_ratio_20', 'close_pos_60d', 'atr_14', 'roc_20', ] # Default LightGBM params DEFAULT_LGB_PARAMS = { 'n_estimators': 300, 'learning_rate': 0.05, 'max_depth': 6, 'num_leaves': 64, 'subsample': 0.8, 'colsample_bytree': 0.8, 'reg_alpha': 0.1, 'reg_lambda': 0.1, 'min_child_samples': 50, 'random_state': 42, 'verbose': -1, } # ═══════════════════════════════════════════════════════ # Helper: HF Token / Download # ═══════════════════════════════════════════════════════ def resolve_hf_token(): """Get HF token from env or cache file.""" token = os.environ.get("HF_TOKEN", "") if not token: token_path = Path(os.path.expanduser("~/.cache/huggingface/token")) if token_path.exists(): token = token_path.read_text().strip() return token def download_hf(token, repo, filename): """Download a file from HF dataset, returns local path.""" from huggingface_hub import hf_hub_download return hf_hub_download( repo_id=repo, filename=filename, repo_type="dataset", token=token, ) # ═══════════════════════════════════════════════════════ # Data Loading & Label Creation # ═══════════════════════════════════════════════════════ def load_raw_data(raw_path: str, forward_period: int = 20): """Load raw OHLCV, compute daily returns and forward returns. Uses DuckDB window functions to compute returns without loading the full dataset into pandas. Returns: DataFrame with columns: symbol, date, daily_ret, future_{forward_period}d_ret """ print(" Loading raw OHLCV and computing returns (DuckDB)...") con = duckdb.connect(":memory:") con.execute("SET memory_limit = '4GB'") # Compute returns using DuckDB window functions ret_col = f'future_{forward_period}d_ret' query = f""" SELECT symbol, date::VARCHAR AS date_str, adj_close / LAG(adj_close, 1) OVER ( PARTITION BY symbol ORDER BY date ) - 1 AS daily_ret, LEAD(adj_close, {forward_period}) OVER ( PARTITION BY symbol ORDER BY date ) / adj_close - 1 AS {ret_col} FROM read_parquet('{raw_path}') ORDER BY symbol, date """ df = con.execute(query).fetchdf() con.close() df['date'] = pd.to_datetime(df['date_str'], format='mixed') df = df.drop(columns=['date_str']) df = df.reset_index(drop=True) print(f" {len(df):,} rows, {df['symbol'].nunique():,} stocks") return df def load_features(features_path: str, feature_cols: list = None): """Load features from parquet using PyArrow (memory-mapped, lower overhead). Returns: DataFrame with columns: symbol, date, feature_cols: list of actual feature column names used """ print(" Loading features (PyArrow memory-mapped)...") # Use PyArrow with memory mapping — no DuckDB double-copy overhead pf = pq.ParquetFile(features_path) all_cols = pf.schema.names if feature_cols is None: feature_cols = [c for c in all_cols if c not in EXCLUDE_COLS] select_cols = ["symbol", "date"] + feature_cols # Read only needed columns, memory-mapped table = pf.read(columns=select_cols, use_pandas_metadata=True) df = table.to_pandas() del table # free PyArrow table memory gc.collect() # Downcast numerics to float32 to save ~50% memory float_cols = df.select_dtypes(include=['float64', 'float32']).columns for c in float_cols: if c not in ('symbol', 'date'): df[c] = pd.to_numeric(df[c], downcast='float') df['date'] = pd.to_datetime(df['date'], format='mixed') print(f" {len(df):,} rows, {len(feature_cols)} features " f"({df.memory_usage(deep=True).sum() / 1024**3:.2f} GB)") return df, feature_cols def create_labels(df: pd.DataFrame, label_type: str, forward_period: int = 20) -> pd.DataFrame: """Create label column based on label_type. Adds 'label' column to df and returns it. For top20_binary / top30_binary: middle quantiles become NaN and are discarded during training. """ ret_col = f'future_{forward_period}d_ret' ret = df[ret_col] valid_mask = ret.notna() if label_type == 'median_binary': med = df.groupby('date')[ret_col].transform('median') label = np.where( ret > med, 1.0, np.where(valid_mask, 0.0, np.nan) ) elif label_type == 'top20_binary': p20 = df.groupby('date')[ret_col].transform( lambda x: x.quantile(0.2) ) p80 = df.groupby('date')[ret_col].transform( lambda x: x.quantile(0.8) ) label = np.where( ret > p80, 1.0, np.where(ret < p20, 0.0, np.nan) ) elif label_type == 'top30_binary': p30 = df.groupby('date')[ret_col].transform( lambda x: x.quantile(0.3) ) p70 = df.groupby('date')[ret_col].transform( lambda x: x.quantile(0.7) ) label = np.where( ret > p70, 1.0, np.where(ret < p30, 0.0, np.nan) ) elif label_type == '3class': p30 = df.groupby('date')[ret_col].transform( lambda x: x.quantile(0.3) ) p70 = df.groupby('date')[ret_col].transform( lambda x: x.quantile(0.7) ) label = np.where( ret > p70, 2.0, np.where(ret < p30, 0.0, 1.0) ) label[~valid_mask] = np.nan else: raise ValueError(f"Unknown label_type: {label_type}") df['label'] = label n_valid = pd.Series(label).notna().sum() print(f" label='{label_type}': {n_valid:,} labeled samples " f"(of {len(df):,} total)") return df def load_and_prepare(features_path: str, raw_path: str, label_type: str = 'top20_binary', feature_cols: list = None, forward_period: int = 20): """Full data loading + merging + label creation. Uses DuckDB for the join to avoid loading both full datasets into pandas simultaneously. When *feature_cols* is None, uses the pruned SELECTED_FEATURE_COLS (~15 features) instead of all 66. Returns: merged_df: DataFrame with features, daily_ret, label feature_cols: list of actual feature column names used """ if feature_cols is None: feature_cols = SELECTED_FEATURE_COLS # 1. Load features from parquet (DuckDB → pandas) feat_df, feature_cols = load_features(features_path, feature_cols) # 2. Load raw returns (DuckDB window functions → pandas) raw_df = load_raw_data(raw_path, forward_period=forward_period) # 3. Merge in pandas (feat_df is the larger one, raw_df is small ~500MB) print(" Merging features with forward returns ...") merge_keys = ['symbol', 'date'] ret_col = f'future_{forward_period}d_ret' merged = feat_df.merge( raw_df[merge_keys + ['daily_ret', ret_col]], on=merge_keys, how='inner', ) # Free raw_df before creating labels del raw_df, feat_df gc.collect() print(f" Merged: {len(merged):,} rows") # 4. Create labels merged = create_labels(merged, label_type, forward_period) # 5. Drop rows where ALL features are NaN before = len(merged) merged = merged.dropna(subset=feature_cols, how='all') if len(merged) < before: print(f" Dropped {before - len(merged)} rows with all-NaN features") return merged, feature_cols # ═══════════════════════════════════════════════════════ # Walk-Forward Training & Prediction # ═══════════════════════════════════════════════════════ def walk_forward_predict(df: pd.DataFrame, feature_cols: list, label_col: str = 'label', windows: list = None, model_params: dict = None, verbose: bool = True) -> pd.DataFrame: """Walk-forward: train on each window, predict on test window. For overlapping test periods, the latest (most recent) window's prediction is kept. Returns: DataFrame with columns: [date, symbol, pred_prob, window_idx] """ if windows is None: windows = WINDOWS if model_params is None: model_params = DEFAULT_LGB_PARAMS.copy() # Ensure date is datetime df = df.copy() df['date'] = pd.to_datetime(df['date']) all_preds = [] for w_idx, (tr_s, tr_e, te_s, te_e) in enumerate(windows): if verbose: print(f"\n ── Window {w_idx + 1}/{len(windows)}: " f"{tr_s} ~ {tr_e} → {te_s} ~ {te_e} ──") train_mask = ( (df['date'] >= tr_s) & (df['date'] <= tr_e) & df[label_col].notna() ) test_mask = (df['date'] >= te_s) & (df['date'] <= te_e) df_tr = df[train_mask].copy() df_te = df[test_mask].copy() if df_tr.empty or df_te.empty: if verbose: print(" SKIP: no data in window") continue X_tr = df_tr[feature_cols].values.astype(np.float32) y_tr = df_tr[label_col].values.astype(np.int32) X_te = df_te[feature_cols].values.astype(np.float32) # Handle NaN in features (shouldn't happen after dropna, but guard) X_tr = np.nan_to_num(X_tr, nan=0.0) X_te = np.nan_to_num(X_te, nan=0.0) # Detect number of classes for multi-class support n_classes = df_tr[label_col].nunique() is_multiclass = n_classes > 2 if is_multiclass: effective_params = dict(model_params) effective_params['objective'] = 'multiclass' effective_params['metric'] = 'multi_logloss' effective_params['num_class'] = n_classes else: effective_params = model_params if verbose: if is_multiclass: class_counts = pd.Series(y_tr).value_counts().sort_index() dist_str = ", ".join(f"class{k}={v}" for k, v in class_counts.items()) print(f" Train: {len(X_tr):,} ({dist_str}) " f"Test: {len(X_te):,}") else: n_pos = (y_tr == 1).sum() n_neg = (y_tr == 0).sum() print(f" Train: {len(X_tr):,} (pos={n_pos:,}, neg={n_neg:,}) " f"Test: {len(X_te):,}") # Train with early stopping # Split last 20% of training dates as validation set tr_dates = sorted(df_tr['date'].unique()) val_cut_idx = int(len(tr_dates) * 0.8) use_early_stopping = val_cut_idx > 1 and val_cut_idx < len(tr_dates) - 1 if use_early_stopping: val_cut_date = tr_dates[val_cut_idx] train_mask_inner = df_tr['date'] < val_cut_date val_mask_inner = df_tr['date'] >= val_cut_date X_tr_fit = df_tr.loc[train_mask_inner, feature_cols].values.astype(np.float32) y_tr_fit = df_tr.loc[train_mask_inner, label_col].values.astype(np.int32) X_val = df_tr.loc[val_mask_inner, feature_cols].values.astype(np.float32) y_val = df_tr.loc[val_mask_inner, label_col].values.astype(np.int32) X_tr_fit = np.nan_to_num(X_tr_fit, nan=0.0) X_val = np.nan_to_num(X_val, nan=0.0) model = lgb.LGBMClassifier(**effective_params) model.fit( X_tr_fit, y_tr_fit, eval_set=[(X_val, y_val)], eval_metric='multi_logloss' if is_multiclass else 'auc', callbacks=[lgb.early_stopping(50)], ) if verbose: n_iter = getattr(model, 'best_iteration_', model_params.get('n_estimators', 300)) print(f" Early stopping: {n_iter} iterations used") del X_tr_fit, y_tr_fit, X_val, y_val else: model = lgb.LGBMClassifier(**effective_params) model.fit(X_tr, y_tr) # Predict if df_tr[label_col].nunique() <= 2: y_pred = model.predict_proba(X_te)[:, 1] else: # Multi-class (3class): use probability of top class (class 2) y_pred = model.predict_proba(X_te)[:, -1] pred_df = df_te[['date', 'symbol']].copy() pred_df['pred_prob'] = y_pred pred_df['window_idx'] = w_idx all_preds.append(pred_df) # Test AUC te_valid = df_te[label_col].notna() if te_valid.sum() > 100: y_te_valid = df_te.loc[te_valid, label_col].values y_pred_valid = y_pred[te_valid.values] if is_multiclass: if verbose: n_classes_te = df_te.loc[te_valid, label_col].nunique() print(f" Test: {len(y_te_valid):,} labeled samples ({n_classes_te} classes)") elif df_te.loc[te_valid, label_col].nunique() >= 2: try: auc = roc_auc_score(y_te_valid, y_pred_valid) if verbose: print(f" Test AUC: {auc:.4f}") except Exception: pass del df_tr, df_te, X_tr, y_tr, X_te, y_pred, model gc.collect() if not all_preds: print(" WARNING: no predictions generated from any window!") return pd.DataFrame(columns=['date', 'symbol', 'pred_prob', 'window_idx']) # Combine: for overlapping dates, keep latest window prediction result = pd.concat(all_preds, ignore_index=True) result['date'] = pd.to_datetime(result['date']) # keep='last' = highest window_idx wins (most recent model) result = result.sort_values('window_idx').drop_duplicates( subset=['date', 'symbol'], keep='last' ) result = result.sort_values(['date', 'pred_prob'], ascending=[True, False]).reset_index(drop=True) if verbose: print(f"\n Total predictions: {len(result):,}") print(f" Date range: {result['date'].min().date()} ~ " f"{result['date'].max().date()}") print(f" Unique stocks: {result['symbol'].nunique():,}") return result # ═══════════════════════════════════════════════════════ # Backtest Simulation # ═══════════════════════════════════════════════════════ def run_backtest(predictions: pd.DataFrame, daily_ret_data: pd.DataFrame, top_k: int = 30, bottom_k: int = 0, rebalance_days: int = 20, score_threshold: float = 0.0, stop_loss: float = 0.0, trading_cost: float = 0.001, hold_weights: str = 'equal', verbose: bool = True) -> dict: """Run cross-sectional long/short portfolio backtest. Args: predictions: DataFrame with [date, symbol, pred_prob] daily_ret_data: DataFrame with [symbol, date, daily_ret] top_k: number of top stocks to long (per rebalance) bottom_k: number of bottom stocks to short rebalance_days: rebalance every N trading days score_threshold: min pred_prob to enter a position stop_loss: max cumulative loss before closing (0 = disabled) trading_cost: round-trip cost fraction (both entry and exit) hold_weights: 'equal' or 'score_weighted' Returns: dict with keys: equity_curve: list of (date, equity) daily_returns: list of daily portfolio returns metrics: dict with performance stats trades: list of trade dicts """ # ── Prepare data ── preds = predictions.copy() preds['date'] = pd.to_datetime(preds['date']) ret_data = daily_ret_data.copy() ret_data['date'] = pd.to_datetime(ret_data['date']) # Build sorted date list from predictions all_dates = sorted(preds['date'].unique()) if len(all_dates) < rebalance_days: raise ValueError( f"Not enough trading days ({len(all_dates)}) for " f"rebalance_days={rebalance_days}" ) # Build fast lookups # ret_map: (symbol, date) -> daily_ret ret_map = {} for _, row in ret_data.iterrows(): ret_map[(row['symbol'], row['date'])] = row['daily_ret'] # pred_map: date -> list of (symbol, prob) sorted by prob descending pred_map = {} for date, grp in preds.groupby('date'): sorted_grp = grp.sort_values('pred_prob', ascending=False) pred_map[date] = list(zip(sorted_grp['symbol'], sorted_grp['pred_prob'])) # ── Rebalance schedule ── rebalance_dates = all_dates[::rebalance_days] rebalance_set = set(rebalance_dates) if verbose: print(f"\n{'=' * 60}") print(f"BACKTEST: top_k={top_k}, bottom_k={bottom_k}, " f"rebalance={rebalance_days}d") print(f" score_threshold={score_threshold:.2f}, " f"stop_loss={stop_loss:.2f}") print(f" trading_cost={trading_cost:.4f}, " f"hold_weights='{hold_weights}'") print(f"{'=' * 60}") print(f" Trading days: {len(all_dates)}") print(f" Rebalance days: {len(rebalance_dates)}") print(f" Period: {all_dates[0].date()} ~ {all_dates[-1].date()}") # ── Simulation state ── positions = {} # symbol -> {'weight': float, 'entry_date': date, # 'cum_ret': float, 'stop_pct': float} equity_curve = [(all_dates[0], 1.0)] daily_returns_list = [] trades = [] current_equity = 1.0 total_entries = 0 total_exits = 0 for i, date in enumerate(all_dates): if date not in pred_map: # No predictions for this date — skip (might be non-trading day # for some stocks, but we only have preds on trading days) equity_curve.append((date, current_equity)) daily_returns_list.append(0.0) continue is_rebalance = date in rebalance_set # ── Stop-loss check before rebalance ── if stop_loss > 0: for sym in list(positions.keys()): pos = positions[sym] if pos['cum_ret'] < -stop_loss: if verbose > 1: print(f" STOP LOSS: {sym} " f"cum_ret={pos['cum_ret']:.4f} on {date.date()}") del positions[sym] total_exits += 1 # ── Rebalance ── if is_rebalance: # Close existing positions (exit cost) if positions: # Compute exit cost proportional to position value exit_cost = trading_cost * sum( abs(p['weight']) for p in positions.values() ) current_equity *= (1 - exit_cost) total_exits += len(positions) positions = {} # Get ranked stocks for this date stock_list = pred_map.get(date, []) if not stock_list: if verbose: print(f" No predictions on {date.date()}, skipping") equity_curve.append((date, current_equity)) daily_returns_list.append(0.0) continue # Filter by score threshold if score_threshold > 0: stock_list = [ (s, p) for s, p in stock_list if p >= score_threshold ] if len(stock_list) < top_k: if verbose: print(f" Only {len(stock_list)} stocks available " f"(need {top_k}), using all") n_long = len(stock_list) else: n_long = top_k # Long positions long_stocks = stock_list[:n_long] long_weight = 1.0 / n_long if n_long > 0 else 0.0 if hold_weights == 'score_weighted': total_score = sum(p for _, p in long_stocks) or 1.0 else: total_score = n_long for sym, prob in long_stocks: if hold_weights == 'score_weighted': w = prob / total_score else: w = long_weight positions[sym] = { 'weight': w, 'entry_date': date, 'cum_ret': 0.0, 'entry_prob': prob, } trades.append({ 'entry_date': date, 'symbol': sym, 'direction': 'long', 'weight': w, 'entry_prob': prob, }) total_entries += n_long # Short positions if bottom_k > 0 and len(stock_list) > top_k + bottom_k: short_stocks = stock_list[-bottom_k:] short_weight = -1.0 / bottom_k if hold_weights == 'score_weighted': # For shorts, lower prob = stronger signal inv_total = sum( (1 - p) for _, p in short_stocks ) or 1.0 else: inv_total = bottom_k for sym, prob in short_stocks: if hold_weights == 'score_weighted': w = -(1 - prob) / inv_total else: w = short_weight positions[sym] = { 'weight': w, 'entry_date': date, 'cum_ret': 0.0, 'entry_prob': prob, } trades.append({ 'entry_date': date, 'symbol': sym, 'direction': 'short', 'weight': w, 'entry_prob': prob, }) total_entries += bottom_k # Entry cost if positions: entry_cost = trading_cost * sum( abs(p['weight']) for p in positions.values() ) current_equity *= (1 - entry_cost) # ── Daily P&L ── daily_port_ret = 0.0 for sym in list(positions.keys()): ret = ret_map.get((sym, date), np.nan) if pd.isna(ret): ret = 0.0 positions[sym]['cum_ret'] += ret daily_port_ret += positions[sym]['weight'] * ret current_equity *= (1 + daily_port_ret) equity_curve.append((date, current_equity)) daily_returns_list.append(daily_port_ret) # ── Final close-out on last date ── if positions: exit_cost = trading_cost * sum( abs(p['weight']) for p in positions.values() ) current_equity *= (1 - exit_cost) equity_curve[-1] = (equity_curve[-1][0], current_equity) metrics = compute_metrics( equity_curve, daily_returns_list, trading_cost ) metrics['total_entries'] = total_entries metrics['total_exits'] = total_exits metrics['n_trades'] = len(trades) if verbose: print_metrics(metrics) return { 'equity_curve': equity_curve, 'daily_returns': daily_returns_list, 'metrics': metrics, 'trades': trades, 'params': { 'top_k': top_k, 'bottom_k': bottom_k, 'rebalance_days': rebalance_days, 'score_threshold': score_threshold, 'stop_loss': stop_loss, 'trading_cost': trading_cost, 'hold_weights': hold_weights, }, } # ═══════════════════════════════════════════════════════ # Permutation Test # ═══════════════════════════════════════════════════════ def permutation_test(predictions: pd.DataFrame, daily_ret_data: pd.DataFrame, backtest_params: dict, n_shuffles: int = 100, seed: int = 42) -> dict: """Shuffle prediction probabilities within each date, re-run backtest, compare the resulting Sharpe distribution against the actual Sharpe. Preserves cross-sectional rank distribution by shuffling *within* each date (stocks trade places), destroying any temporal signal. Returns: dict with keys: actual_sharpe: Sharpe from unshuffled predictions shuffled_sharpes: list of Sharpe values from shuffled runs p_value: one-sided p-value (fraction of shuffled >= actual) """ actual_result = run_backtest( predictions=predictions, daily_ret_data=daily_ret_data, **backtest_params, ) actual_sharpe = actual_result['metrics']['sharpe_ratio'] print(f" Actual Sharpe (unshuffled): {actual_sharpe:.4f}") shuffled_sharpes = [] preds_copy = predictions.copy() rng = np.random.RandomState(seed) for i in range(n_shuffles): # Shuffle pred_prob within each date (preserve cross-sectional structure) shuffled = preds_copy.copy() shuffled['pred_prob'] = shuffled.groupby('date')['pred_prob'].transform( lambda x: x.sample(frac=1, random_state=rng).values ) result = run_backtest( predictions=shuffled, daily_ret_data=daily_ret_data, verbose=False, **backtest_params, ) s = result['metrics']['sharpe_ratio'] shuffled_sharpes.append(s) if (i + 1) % 20 == 0: print(f" Permutation {i+1}/{n_shuffles}: Sharpe={s:.4f}") # One-sided p-value: fraction of shuffled Sharpes >= actual n_extreme = sum(s >= actual_sharpe for s in shuffled_sharpes) p_value = (1 + n_extreme) / (1 + n_shuffles) print(f" Permutation test: p-value={p_value:.4f} " f"({n_extreme}/{n_shuffles} shuffled >= actual)") return { 'actual_sharpe': float(round(actual_sharpe, 4)), 'shuffled_sharpes': [float(round(s, 4)) for s in shuffled_sharpes], 'p_value': float(round(p_value, 4)), 'n_shuffles': n_shuffles, } # ═══════════════════════════════════════════════════════ # Layered (N-quintile) Backtest # ═══════════════════════════════════════════════════════ def run_layered_backtest(predictions: pd.DataFrame, daily_ret_data: pd.DataFrame, n_groups: int = 5, rebalance_days: int = 20, trading_cost: float = 0.001) -> dict: """N-quintile grouping backtest. Each rebalance day, stocks are ranked by predicted probability and divided into *n_groups* equal-sized portfolios. Each group is held equal-weight until the next rebalance. Returns: dict with keys: group_returns: list of daily return lists (one per group, group 0 = lowest) long_short_returns: daily returns of top-minus-bottom portfolio metrics: dict with long_short_sharpe, avg_ic, monotonicity, etc. """ preds = predictions.copy() preds['date'] = pd.to_datetime(preds['date']) ret_data = daily_ret_data.copy() ret_data['date'] = pd.to_datetime(ret_data['date']) all_dates = sorted(preds['date'].unique()) if len(all_dates) < rebalance_days: raise ValueError( f"Not enough trading days ({len(all_dates)}) for " f"rebalance_days={rebalance_days}" ) # Build return lookup ret_map = {} for _, row in ret_data.iterrows(): ret_map[(row['symbol'], row['date'])] = row['daily_ret'] # Build prediction lookup per date pred_map = {} for date, grp in preds.groupby('date'): sorted_grp = grp.sort_values('pred_prob', ascending=False) pred_map[date] = list(zip(sorted_grp['symbol'], sorted_grp['pred_prob'])) rebalance_dates = set(all_dates[::rebalance_days]) # Initialise group portfolios (group index → {symbol: weight}) group_portfolios = {g: {} for g in range(n_groups)} group_daily_rets = {g: [] for g in range(n_groups)} for i, date in enumerate(all_dates): if date not in pred_map: for g in range(n_groups): group_daily_rets[g].append(0.0) continue is_rebalance = date in rebalance_dates stock_list = pred_map[date] n_stocks = len(stock_list) # ── Rebalance: assign stocks to groups ── if is_rebalance and n_stocks >= n_groups: # Divide into n_groups equal-sized buckets stocks_per_group = n_stocks // n_groups remainder = n_stocks % n_groups idx = 0 for g in range(n_groups): size = stocks_per_group + (1 if g < remainder else 0) group_stocks = stock_list[idx:idx + size] idx += size w = 1.0 / size if size > 0 else 0.0 group_portfolios[g] = {sym: w for sym, _ in group_stocks} # ── Daily P&L for each group ── for g in range(n_groups): daily_ret = 0.0 for sym, w in group_portfolios[g].items(): ret = ret_map.get((sym, date), np.nan) daily_ret += w * (ret if not pd.isna(ret) else 0.0) group_daily_rets[g].append(daily_ret) # ── Compute metrics ── group_rets_arr = [np.array(group_daily_rets[g]) for g in range(n_groups)] # Long-short (top - bottom) ls_returns = group_rets_arr[-1] - group_rets_arr[0] ls_sharpe = ( np.mean(ls_returns) / np.std(ls_returns, ddof=1) * np.sqrt(TRADING_DAYS_PER_YEAR) if np.std(ls_returns, ddof=1) > 0 else 0.0 ) # Average IC (Spearman rank correlation per date) ics = [] for date in all_dates: if date in pred_map: stocks = pred_map[date] if len(stocks) >= 10: probs = [p for _, p in stocks] actuals = [ret_map.get((s, date), 0.0) for s, _ in stocks] from scipy.stats import spearmanr ic, _ = spearmanr(probs, actuals) ics.append(ic) avg_ic = float(np.mean(ics)) if ics else 0.0 # Monotonicity: average group returns should be increasing group_avg_rets = [float(np.mean(group_rets_arr[g])) for g in range(n_groups)] strictly_increasing = all( group_avg_rets[g] < group_avg_rets[g + 1] for g in range(n_groups - 1) ) non_decreasing = all( group_avg_rets[g] <= group_avg_rets[g + 1] for g in range(n_groups - 1) ) return { 'group_returns': [r.tolist() for r in group_rets_arr], 'long_short_returns': ls_returns.tolist(), 'metrics': { 'long_short_sharpe': float(round(ls_sharpe, 4)), 'avg_ic': float(round(avg_ic, 6)), 'monotonic_strict': strictly_increasing, 'monotonic_non_decreasing': non_decreasing, 'group_avg_returns': [float(round(r, 8)) for r in group_avg_rets], 'n_groups': n_groups, 'rebalance_days': rebalance_days, }, } # ═══════════════════════════════════════════════════════ # Performance Metrics # ═══════════════════════════════════════════════════════ def compute_metrics(equity_curve: list, daily_returns: list, trading_cost: float = 0.001) -> dict: """Compute performance metrics from equity curve and daily returns.""" if len(equity_curve) < 2: return {'error': 'insufficient data'} dates = [e[0] for e in equity_curve] equity = np.array([e[1] for e in equity_curve]) daily_rets = np.array(daily_returns) # Total return total_return = equity[-1] / equity[0] - 1 # Number of trading days n_days = len(daily_rets) n_years = n_days / TRADING_DAYS_PER_YEAR # Annualized return (CAGR) annual_return = (1 + total_return) ** (1 / n_years) - 1 if n_years > 0 else 0.0 # Annualized volatility daily_vol = np.std(daily_rets, ddof=1) annual_vol = daily_vol * np.sqrt(TRADING_DAYS_PER_YEAR) # Sharpe Ratio (assuming 0% risk-free rate) excess_daily = daily_rets sharpe = (np.mean(excess_daily) / daily_vol * np.sqrt(TRADING_DAYS_PER_YEAR) if daily_vol > 0 else 0.0) # Maximum drawdown peak = np.maximum.accumulate(equity) drawdown = (equity - peak) / peak max_drawdown = float(np.min(drawdown)) max_dd_date = dates[int(np.argmin(drawdown))] if len(dates) > 0 else None # Win rate (daily) win_days = np.sum(daily_rets > 0) loss_days = np.sum(daily_rets < 0) total_signed = win_days + loss_days win_rate = win_days / total_signed if total_signed > 0 else 0.0 # Profit factor gross_profit = np.sum(daily_rets[daily_rets > 0]) gross_loss = abs(np.sum(daily_rets[daily_rets < 0])) profit_factor = gross_profit / gross_loss if gross_loss > 0 else float('inf') # Calmar ratio calmar = annual_return / abs(max_drawdown) if max_drawdown != 0 else 0.0 # Monthly returns equity_series = pd.Series(equity, index=pd.to_datetime(dates)) monthly_rets = equity_series.resample('ME').last().pct_change().dropna() monthly_positive = (monthly_rets > 0).sum() monthly_total = len(monthly_rets) monthly_win_rate = monthly_positive / monthly_total if monthly_total > 0 else 0.0 return { 'total_return': float(round(total_return, 6)), 'annual_return': float(round(annual_return, 6)), 'annual_volatility': float(round(annual_vol, 6)), 'sharpe_ratio': float(round(sharpe, 4)), 'max_drawdown': float(round(max_drawdown, 6)), 'max_drawdown_date': str(max_dd_date.date()) if max_dd_date else None, 'calmar_ratio': float(round(calmar, 4)), 'daily_win_rate': float(round(win_rate, 4)), 'profit_factor': float(round(profit_factor, 4)), 'n_trading_days': n_days, 'n_trading_years': round(n_years, 2), 'monthly_win_rate': float(round(monthly_win_rate, 4)), 'monthly_total': int(monthly_total), 'avg_daily_return': float(round(float(np.mean(daily_rets)), 8)), 'std_daily_return': float(round(float(daily_vol), 8)), } def print_metrics(metrics: dict): """Pretty-print backtest metrics.""" print(f"\n{'─' * 50}") print(f" PERFORMANCE METRICS") print(f"{'─' * 50}") print(f" Total Return: {metrics.get('total_return', 0) * 100:>8.2f}%") print(f" Annual Return: {metrics.get('annual_return', 0) * 100:>8.2f}%") print(f" Annual Volatility: {metrics.get('annual_volatility', 0) * 100:>8.2f}%") print(f" Sharpe Ratio: {metrics.get('sharpe_ratio', 0):>8.4f}") print(f" Max Drawdown: {metrics.get('max_drawdown', 0) * 100:>8.2f}%") print(f" Calmar Ratio: {metrics.get('calmar_ratio', 0):>8.4f}") print(f" Win Rate (daily): {metrics.get('daily_win_rate', 0) * 100:>8.2f}%") print(f" Profit Factor: {metrics.get('profit_factor', 0):>8.4f}") print(f" Monthly Win Rate: {metrics.get('monthly_win_rate', 0) * 100:>8.2f}%") print(f" Trading Days: {metrics.get('n_trading_days', 0):>8d}") print(f" Monthly Periods: {metrics.get('monthly_total', 0):>8d}") print(f" Trades: {metrics.get('n_trades', 0):>8d}") print(f"{'─' * 50}") # ═══════════════════════════════════════════════════════ # CLI # ═══════════════════════════════════════════════════════ def main(): parser = argparse.ArgumentParser( description="Fire Eye V8 — Walk-Forward Backtest Engine" ) # Run mode parser.add_argument('--run', action='store_true', help='Run full backtest and print report') # Data sources parser.add_argument('--local-parquet', type=str, default=None, help='Path to local all_features parquet') parser.add_argument('--local-raw', type=str, default=None, help='Path to local cn_and_us_unified parquet') # Label config parser.add_argument('--label', type=str, default='top20_binary', choices=['median_binary', 'top20_binary', 'top30_binary', '3class'], help='Label definition for training') parser.add_argument('--forward-period', type=int, default=20, help='Forward return period in trading days') # Strategy parameters parser.add_argument('--top-k', type=int, default=30, help='Number of top stocks to long') parser.add_argument('--bottom-k', type=int, default=0, help='Number of bottom stocks to short') parser.add_argument('--rebalance-days', type=int, default=20, help='Rebalance frequency in trading days') parser.add_argument('--score-threshold', type=float, default=0.0, help='Minimum prediction score to enter') parser.add_argument('--stop-loss', type=float, default=0.0, help='Max loss before stop-out (0 = disabled)') parser.add_argument('--trading-cost', type=float, default=0.001, help='Round-trip trading cost fraction') parser.add_argument('--hold-weights', type=str, default='equal', choices=['equal', 'score_weighted'], help='Position weighting scheme') # Model parameters parser.add_argument('--model-params', type=str, default=None, help='JSON file with LightGBM params override') # Output parser.add_argument('--output', type=str, default=None, help='Save backtest report CSV to path') args = parser.parse_args() if not args.run: parser.print_help() return # ── Resolve data paths ── token = resolve_hf_token() if not token: print("ERROR: HF_TOKEN not set. Set env HF_TOKEN or create " "~/.cache/huggingface/token") sys.exit(1) if args.local_parquet and os.path.exists(args.local_parquet): features_path = args.local_parquet else: print("Downloading all_features_2018_2026.parquet ...") features_path = download_hf(token, HF_REPO, HF_FILE) print(f" Features: {features_path}") if args.local_raw and os.path.exists(args.local_raw): raw_path = args.local_raw else: print("Downloading cn_and_us_unified.parquet ...") raw_path = download_hf(token, HF_REPO, HF_RAW) print(f" Raw: {raw_path}") # ── Load model params ── model_params = DEFAULT_LGB_PARAMS.copy() if args.model_params: with open(args.model_params) as f: user_params = json.load(f) model_params.update(user_params) print(f" Model params: {json.dumps(user_params)}") # ── Load & prepare data ── print(f"\n{'=' * 60}") print("DATA PREPARATION") print(f"{'=' * 60}") df, feature_cols = load_and_prepare( features_path=features_path, raw_path=raw_path, label_type=args.label, forward_period=args.forward_period, ) # ── Walk-Forward ── print(f"\n{'=' * 60}") print("WALK-FORWARD TRAINING & PREDICTION") print(f"{'=' * 60}") predictions = walk_forward_predict( df=df, feature_cols=feature_cols, label_col='label', model_params=model_params, ) if predictions.empty: print("ERROR: no predictions generated") sys.exit(1) # ── Backtest ── result = run_backtest( predictions=predictions, daily_ret_data=df[['symbol', 'date', 'daily_ret']], top_k=args.top_k, bottom_k=args.bottom_k, rebalance_days=args.rebalance_days, score_threshold=args.score_threshold, stop_loss=args.stop_loss, trading_cost=args.trading_cost, hold_weights=args.hold_weights, ) # ── Save results ── RESULTS_DIR.mkdir(parents=True, exist_ok=True) report_path = args.output or (RESULTS_DIR / 'backtest_report.csv') # Save equity curve eq_df = pd.DataFrame(result['equity_curve'], columns=['date', 'equity']) eq_df.to_csv(report_path, index=False) print(f"\n Saved equity curve: {report_path}") # Save metrics JSON metrics_path = RESULTS_DIR / 'backtest_metrics.json' with open(metrics_path, 'w') as f: json.dump(result['metrics'], f, indent=2, default=str) print(f" Saved metrics: {metrics_path}") print(f"\n{'=' * 60}") print("DONE") print(f"{'=' * 60}") if __name__ == '__main__': main()