| |
| """ |
| 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") |
|
|
| |
| 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 |
|
|
| |
| WINDOWS = [ |
| |
| ('2018-01-01', '2022-11-30', '2023-01-01', '2024-06-30'), |
| |
| ('2018-06-01', '2023-06-01', '2023-07-01', '2024-12-31'), |
| |
| ('2019-01-01', '2024-05-31', '2024-07-01', '2025-06-30'), |
| |
| ('2019-06-01', '2024-12-31', '2025-01-01', '2025-12-31'), |
| |
| ('2020-01-01', '2024-12-31', '2025-01-01', '2026-04-10'), |
| ] |
|
|
| EXCLUDE_COLS = {"symbol", "date", "label"} |
|
|
| |
| 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', |
| ] |
|
|
| |
| |
| SELECTED_FEATURE_COLS = [ |
| |
| 'ret_1d', 'ret_20d', |
| |
| 'ma_20', 'ma_200', |
| |
| 'macd_hist', |
| |
| 'kdj_j_14', |
| |
| 'bb_pos_20', 'volatility_20d', |
| |
| 'bi_strength', 'sell2', |
| |
| 'rsi_12', 'vol_ratio_20', 'close_pos_60d', 'atr_14', 'roc_20', |
| ] |
|
|
| |
| 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, |
| } |
|
|
|
|
| |
| |
| |
|
|
| 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, |
| ) |
|
|
|
|
| |
| |
| |
|
|
| 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'") |
|
|
| |
| 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> |
| feature_cols: list of actual feature column names used |
| """ |
| print(" Loading features (PyArrow memory-mapped)...") |
| |
| 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 |
| |
| table = pf.read(columns=select_cols, use_pandas_metadata=True) |
| df = table.to_pandas() |
| del table |
| gc.collect() |
| |
| 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 |
| |
| feat_df, feature_cols = load_features(features_path, feature_cols) |
|
|
| |
| raw_df = load_raw_data(raw_path, forward_period=forward_period) |
|
|
| |
| 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', |
| ) |
| |
| del raw_df, feat_df |
| gc.collect() |
| print(f" Merged: {len(merged):,} rows") |
|
|
| |
| merged = create_labels(merged, label_type, forward_period) |
|
|
| |
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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() |
|
|
| |
| 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) |
|
|
| |
| X_tr = np.nan_to_num(X_tr, nan=0.0) |
| X_te = np.nan_to_num(X_te, nan=0.0) |
|
|
| |
| 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):,}") |
|
|
| |
| |
| 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) |
|
|
| |
| if df_tr[label_col].nunique() <= 2: |
| y_pred = model.predict_proba(X_te)[:, 1] |
| else: |
| |
| 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) |
|
|
| |
| 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']) |
|
|
| |
| result = pd.concat(all_preds, ignore_index=True) |
| result['date'] = pd.to_datetime(result['date']) |
| |
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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 |
| """ |
| |
| 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}" |
| ) |
|
|
| |
| |
| ret_map = {} |
| for _, row in ret_data.iterrows(): |
| ret_map[(row['symbol'], row['date'])] = row['daily_ret'] |
|
|
| |
| 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 = 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()}") |
|
|
| |
| positions = {} |
| |
| 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: |
| |
| |
| equity_curve.append((date, current_equity)) |
| daily_returns_list.append(0.0) |
| continue |
|
|
| is_rebalance = date in rebalance_set |
|
|
| |
| 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 |
|
|
| |
| if is_rebalance: |
| |
| if positions: |
| |
| exit_cost = trading_cost * sum( |
| abs(p['weight']) for p in positions.values() |
| ) |
| current_equity *= (1 - exit_cost) |
| total_exits += len(positions) |
| positions = {} |
|
|
| |
| 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 |
|
|
| |
| 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_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 |
|
|
| |
| 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': |
| |
| 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 |
|
|
| |
| if positions: |
| entry_cost = trading_cost * sum( |
| abs(p['weight']) for p in positions.values() |
| ) |
| current_equity *= (1 - entry_cost) |
|
|
| |
| 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) |
|
|
| |
| 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, |
| }, |
| } |
|
|
|
|
| |
| |
| |
|
|
| 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): |
| |
| 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}") |
|
|
| |
| 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, |
| } |
|
|
|
|
| |
| |
| |
|
|
| 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}" |
| ) |
|
|
| |
| ret_map = {} |
| for _, row in ret_data.iterrows(): |
| ret_map[(row['symbol'], row['date'])] = row['daily_ret'] |
|
|
| |
| 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]) |
|
|
| |
| 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) |
|
|
| |
| if is_rebalance and n_stocks >= n_groups: |
| |
| 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} |
|
|
| |
| 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) |
|
|
| |
| group_rets_arr = [np.array(group_daily_rets[g]) for g in range(n_groups)] |
|
|
| |
| 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 |
| ) |
|
|
| |
| 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 |
|
|
| |
| 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, |
| }, |
| } |
|
|
|
|
| |
| |
| |
|
|
| 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 = equity[-1] / equity[0] - 1 |
|
|
| |
| n_days = len(daily_rets) |
| n_years = n_days / TRADING_DAYS_PER_YEAR |
|
|
| |
| annual_return = (1 + total_return) ** (1 / n_years) - 1 if n_years > 0 else 0.0 |
|
|
| |
| daily_vol = np.std(daily_rets, ddof=1) |
| annual_vol = daily_vol * np.sqrt(TRADING_DAYS_PER_YEAR) |
|
|
| |
| excess_daily = daily_rets |
| sharpe = (np.mean(excess_daily) / daily_vol * np.sqrt(TRADING_DAYS_PER_YEAR) |
| if daily_vol > 0 else 0.0) |
|
|
| |
| 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_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 |
|
|
| |
| 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 = annual_return / abs(max_drawdown) if max_drawdown != 0 else 0.0 |
|
|
| |
| 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}") |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="Fire Eye V8 — Walk-Forward Backtest Engine" |
| ) |
|
|
| |
| parser.add_argument('--run', action='store_true', |
| help='Run full backtest and print report') |
|
|
| |
| 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') |
|
|
| |
| 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') |
|
|
| |
| 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') |
|
|
| |
| parser.add_argument('--model-params', type=str, default=None, |
| help='JSON file with LightGBM params override') |
|
|
| |
| 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 |
|
|
| |
| 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}") |
|
|
| |
| 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)}") |
|
|
| |
| 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, |
| ) |
|
|
| |
| 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) |
|
|
| |
| 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, |
| ) |
|
|
| |
| RESULTS_DIR.mkdir(parents=True, exist_ok=True) |
| report_path = args.output or (RESULTS_DIR / 'backtest_report.csv') |
|
|
| |
| 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}") |
|
|
| |
| 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() |
|
|
|
|