Download backtest.py from AcyLa/multi-asset-predictive-model: direct link, hf CLI and curl.
- Browser
- Download file 3.08 kB
-
https://huggingface.co/AcyLa/multi-asset-predictive-model/resolve/main/backtest.py
- Command line
-
hf download hf://AcyLa/multi-asset-predictive-model/backtest.py
-
curl -L -o backtest.py https://huggingface.co/AcyLa/multi-asset-predictive-model/resolve/main/backtest.py
3.08 kB
| """Walk-forward backtest with purging (López de Prado).""" | |
| import numpy as np, pandas as pd | |
| from config import cfg | |
| def walk_forward_splits(n_rows, train_w=None, val_w=None, test_w=None, step=None, purge=None): | |
| tw, vw, tw2 = train_w or cfg.train_window, val_w or cfg.val_window, test_w or cfg.test_window | |
| st, pg = step or cfg.step_size, purge or cfg.purge_gap | |
| splits = [] | |
| start = 0 | |
| while start + tw + vw + pg + tw2 <= n_rows: | |
| tr_s, tr_e = start, start + tw | |
| va_s, va_e = tr_e, tr_e + vw | |
| te_s, te_e = va_e + pg, va_e + pg + tw2 | |
| splits.append((tr_s, tr_e, va_s, va_e, te_s, te_e)) | |
| start += st | |
| return splits | |
| def quick_split(n_rows, val_ratio=0.15, test_ratio=0.15): | |
| """Three-way split: train / validation / test (no overlap, chronological).""" | |
| te_s = int(n_rows * (1 - val_ratio - test_ratio)) | |
| va_s = te_s | |
| va_e = te_s + int(n_rows * val_ratio) | |
| test_s = va_e | |
| test_e = n_rows | |
| return [(0, te_s, va_s, va_e, test_s, test_e)] | |
| def evaluate_predictions(y_true, y_pred): | |
| m = ~np.isnan(y_true) & ~np.isnan(y_pred) | |
| if m.sum() < 2: return {'rmse': np.nan, 'dir_acc': np.nan, 'sharpe': np.nan, 'win_rate': np.nan} | |
| yv, pv = y_true[m], y_pred[m] | |
| rmse = np.sqrt(np.mean((yv - pv) ** 2)) | |
| dir_acc = np.mean(np.sign(yv) == np.sign(pv)) | |
| strategy_ret = np.sign(pv) * yv | |
| sharpe = np.sqrt(252) * np.mean(strategy_ret) / (np.std(strategy_ret) + 1e-9) | |
| win_rate = np.mean((strategy_ret > 0) & (yv != 0)) | |
| return {'rmse': float(rmse), 'dir_acc': float(dir_acc), 'sharpe': float(sharpe), 'win_rate': float(win_rate)} | |
| def run_walk_forward(df, feature_cols, horizons=None, max_splits=None, use_lstm=True): | |
| from models import EnsemblePredictor | |
| horizons = horizons or cfg.horizons | |
| splits = walk_forward_splits(len(df)) | |
| if max_splits: splits = splits[:max_splits] | |
| if not splits: | |
| print("Not enough data for walk-forward. Using quick split.") | |
| splits = quick_split(len(df)) | |
| print(f"Walk-forward: {len(splits)} splits, {len(horizons)} horizons") | |
| results = [] | |
| for si, (tr_s, tr_e, va_s, va_e, te_s, te_e) in enumerate(splits): | |
| tr = df.iloc[tr_s:tr_e]; va = df.iloc[va_s:va_e]; te = df.iloc[te_s:te_e] | |
| for h in horizons: | |
| try: | |
| model = EnsemblePredictor(horizon=h) | |
| model.train(tr, va, feature_cols) | |
| preds = model.predict(te, use_lstm=use_lstm) | |
| tgt = f'Target_Return_{h}' | |
| y_true = te[tgt].values | |
| m = ~np.isnan(y_true) | |
| metrics = evaluate_predictions(y_true[m], preds[m]) | |
| metrics.update({'split': si, 'horizon': h, 'train_start': tr.index[0], | |
| 'test_start': te.index[0], 'test_end': te.index[-1]}) | |
| results.append(metrics) | |
| print(f" Split {si} h={h}: Dir.Acc={metrics['dir_acc']:.1%} Sharpe={metrics['sharpe']:.2f}") | |
| except Exception as e: | |
| print(f" Split {si} h={h}: ERROR {e}") | |
| return pd.DataFrame(results) | |