File size: 6,839 Bytes
a36a0c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""
Walk-Forward Backtesting Engine — purged, rolling walk-forward CV.
[=== TRAIN ===][== VAL ==][-- PURGE --][== TEST ==]
Gold standard for financial ML evaluation (López de Prado).
"""
import pandas as pd
import numpy as np
from config import cfg
from models import EnsemblePredictor
from labels import get_label_columns
import warnings
warnings.filterwarnings('ignore')

def walk_forward_splits(df):
    n = len(df)
    splits = []
    start = 0
    while start + cfg.train_window + cfg.val_window + cfg.purge_gap + cfg.test_window <= n:
        train_end = start + cfg.train_window
        val_start = train_end; val_end = val_start + cfg.val_window
        test_start = val_end + cfg.purge_gap; test_end = test_start + cfg.test_window
        if test_end > n: break
        train_df = df.iloc[start:train_end].copy()
        val_df = df.iloc[val_start:val_end].copy()
        test_df = df.iloc[test_start:test_end].copy()
        info = {'split': len(splits), 'train_start': df.index[start], 'train_end': df.index[train_end - 1],
                'val_start': df.index[val_start], 'val_end': df.index[val_end - 1],
                'test_start': df.index[test_start], 'test_end': df.index[test_end - 1]}
        splits.append((train_df, val_df, test_df, info))
        start += cfg.step_size
    return splits

def evaluate_predictions(y_true, y_pred):
    valid = ~np.isnan(y_true) & ~np.isnan(y_pred)
    y_t, y_p = y_true[valid], y_pred[valid]
    if len(y_t) < 10:
        return {'rmse': np.nan, 'mae': np.nan, 'r2': np.nan, 'directional_accuracy': np.nan, 'n': len(y_t)}
    rmse = np.sqrt(np.mean((y_t - y_p) ** 2))
    mae = np.mean(np.abs(y_t - y_p))
    ss_res = np.sum((y_t - y_p) ** 2); ss_tot = np.sum((y_t - np.mean(y_t)) ** 2)
    r2 = 1 - ss_res / ss_tot if ss_tot > 0 else np.nan
    actual_dir = np.sign(y_t); pred_dir = np.sign(y_p)
    non_flat = actual_dir != 0
    dir_acc = np.mean(actual_dir[non_flat] == pred_dir[non_flat]) if non_flat.sum() > 0 else np.nan
    return {'rmse': float(rmse), 'mae': float(mae), 'r2': float(r2),
            'directional_accuracy': float(dir_acc), 'n': int(len(y_t))}

def simulate_strategy(test_df, predictions, horizon, cost_bps=10):
    target = f'Target_Return_{horizon}d'
    y = test_df[target].values; close = test_df['Close'].values
    valid = ~np.isnan(y) & ~np.isnan(predictions)
    y_v, pred_v, close_v = y[valid], predictions[valid], close[valid]
    n = len(y_v)
    pred_std = np.std(pred_v)
    threshold = max(pred_std * 0.25, 0.001)
    raw_positions = np.where(pred_v > threshold, 1, np.where(pred_v < -threshold, -1, 0))
    # Non-overlapping holding
    positions = np.zeros(n, dtype=float)
    i = 0
    while i < n:
        pos = raw_positions[i]; end = min(i + horizon, n)
        positions[i:end] = pos; i = end
    daily_returns = np.zeros(n, dtype=float)
    if n > 1: daily_returns[1:] = close_v[1:] / close_v[:-1] - 1
    strategy_returns = positions * daily_returns
    trade_flags = np.zeros(n, dtype=bool)
    trade_flags[0] = positions[0] != 0
    if n > 1: trade_flags[1:] = positions[1:] != positions[:-1]
    costs = trade_flags * (cost_bps / 10000)
    strategy_returns -= costs
    buyhold_returns = daily_returns.copy()
    cum_strategy = np.cumprod(1 + strategy_returns) - 1
    cum_buyhold = np.cumprod(1 + buyhold_returns) - 1
    n_trades = int(trade_flags.sum())
    # Win rate per trade
    trade_pnl = []; i = 0
    while i < n:
        if positions[i] != 0:
            end = min(i + horizon, n)
            trade_pnl.append(positions[i] * np.sum(strategy_returns[i:end])); i = end
        else: i += 1
    win_rate = np.mean([p > 0 for p in trade_pnl]) if trade_pnl else 0.0
    sharpe = np.mean(strategy_returns) / np.std(strategy_returns) * np.sqrt(365) if np.std(strategy_returns) > 0 else 0.0
    cum_curve = np.cumprod(1 + strategy_returns)
    running_max = np.maximum.accumulate(cum_curve)
    drawdown = (cum_curve - running_max) / running_max
    max_dd = np.min(drawdown) if len(drawdown) > 0 else 0.0
    return {
        'cum_return_strategy': float(cum_strategy[-1]) if len(cum_strategy) > 0 else 0.0,
        'cum_return_buyhold': float(cum_buyhold[-1]) if len(cum_buyhold) > 0 else 0.0,
        'alpha': float(cum_strategy[-1] - cum_buyhold[-1]) if len(cum_strategy) > 0 else 0.0,
        'sharpe': float(sharpe), 'max_drawdown': float(max_dd),
        'n_trades': n_trades, 'win_rate': float(win_rate)}

def run_walk_forward(df, feature_cols, horizons=None, verbose=True):
    horizons = horizons or cfg.horizons
    splits = walk_forward_splits(df)
    if verbose:
        print(f"\n{'='*70}\nWALK-FORWARD BACKTEST\n  Splits: {len(splits)} | Horizons: {horizons}")
        print(f"  Train: {cfg.train_window}d | Val: {cfg.val_window}d | Test: {cfg.test_window}d | Purge: {cfg.purge_gap}d | Step: {cfg.step_size}d\n{'='*70}\n")
    all_results = {}
    for h in horizons:
        if verbose: print(f"\n{'─'*50}\nHorizon: {h}d\n{'─'*50}")
        metrics_list = []; strategy_list = []; final_model = None
        for i, (train_df, val_df, test_df, info) in enumerate(splits):
            if verbose: print(f"\n  Split {i+1}/{len(splits)}: train={info['train_start']:%Y-%m-%d}..{info['train_end']:%Y-%m-%d} test={info['test_start']:%Y-%m-%d}..{info['test_end']:%Y-%m-%d}")
            model = EnsemblePredictor(horizon=h)
            model.train(train_df, val_df, feature_cols)
            preds = model.predict(test_df, use_lstm=True)
            y_test = test_df[f'Target_Return_{h}d'].values
            metrics = evaluate_predictions(y_test, preds)
            strategy = simulate_strategy(test_df, preds, h)
            metrics_list.append(metrics); strategy_list.append(strategy); final_model = model
            if verbose: print(f"    RMSE={metrics['rmse']:.6f} | Dir.Acc={metrics['directional_accuracy']:.1%} | R²={metrics['r2']:.4f} | α={strategy['alpha']:+.2%} | Sharpe={strategy['sharpe']:.2f} | Trades={strategy['n_trades']}")
        avg_m = {k: np.nanmean([m[k] for m in metrics_list]) for k in metrics_list[0]}
        avg_s = {k: np.nanmean([s[k] for s in strategy_list]) for k in strategy_list[0]}
        if verbose:
            print(f"\n  {'─'*40}\n  AVERAGE ACROSS {len(splits)} SPLITS:")
            print(f"    RMSE: {avg_m['rmse']:.6f} | MAE: {avg_m['mae']:.6f} | R²: {avg_m['r2']:.4f} | Dir.Acc: {avg_m['directional_accuracy']:.1%}")
            print(f"    Strategy: {avg_s['cum_return_strategy']:+.2%} | BuyHold: {avg_s['cum_return_buyhold']:+.2%} | Alpha: {avg_s['alpha']:+.2%} | Sharpe: {avg_s['sharpe']:.2f} | MaxDD: {avg_s['max_drawdown']:.2%} | WinRate: {avg_s['win_rate']:.1%}")
        all_results[h] = {'metrics': avg_m, 'strategy': avg_s,
            'per_split_metrics': metrics_list, 'per_split_strategy': strategy_list, 'model': final_model}
    return all_results