AcyLa's picture
Upload backtest.py with huggingface_hub
777df07 verified
Raw History Blame Contribute Delete
1.62 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)}