File size: 3,079 Bytes
3b6e773
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""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)