Spaces:
Running
Running
File size: 6,461 Bytes
18d4089 | 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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | """
Comprehensive Walk-Forward Backtest for TFT-ASRO.
Evaluates model performance across multiple time windows with full
metric reporting, comparison against Theta baseline, and ensemble
analysis.
Usage:
python -m deep_learning.validation.backtest --windows 50
Metrics computed per window:
- Directional Accuracy (DA)
- Sharpe Ratio
- Sortino Ratio
- Variance Ratio (VR)
- MAE / RMSE
- Tail Capture Rate
- Prediction Interval Coverage
Results are saved to artifacts/backtest/ for CI comparison.
"""
from __future__ import annotations
import argparse
import json
import logging
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
def run_backtest(
y_actual: np.ndarray,
y_pred_median: np.ndarray,
y_pred_q10: Optional[np.ndarray] = None,
y_pred_q90: Optional[np.ndarray] = None,
window_size: int = 50,
step_size: int = 10,
) -> dict:
"""
Walk-forward backtest across overlapping windows.
Args:
y_actual: Full array of actual returns (test set).
y_pred_median: Full array of median predictions.
y_pred_q10: Optional Q10 predictions.
y_pred_q90: Optional Q90 predictions.
window_size: Evaluation window size.
step_size: Step between consecutive windows.
Returns:
Dict with per-window metrics and aggregate summary.
"""
from deep_learning.training.metrics import (
directional_accuracy,
sharpe_ratio,
sortino_ratio,
tail_capture_rate,
prediction_interval_coverage,
)
n = len(y_actual)
if n < window_size:
window_size = n
step_size = n
windows = []
start = 0
while start + window_size <= n:
end = start + window_size
ya = y_actual[start:end]
yp = y_pred_median[start:end]
strategy_returns = np.sign(yp) * ya
w = {
"start": start,
"end": end,
"da": directional_accuracy(ya, yp),
"sharpe": sharpe_ratio(strategy_returns),
"sortino": sortino_ratio(strategy_returns),
"tail_capture": tail_capture_rate(ya, yp),
"mae": float(np.abs(ya - yp).mean()),
"rmse": float(np.sqrt(((ya - yp) ** 2).mean())),
"pred_std": float(yp.std()),
"actual_std": float(ya.std()),
}
if ya.std() > 1e-9:
w["variance_ratio"] = float(yp.std() / ya.std())
else:
w["variance_ratio"] = 0.0
if y_pred_q10 is not None and y_pred_q90 is not None:
q10 = y_pred_q10[start:end]
q90 = y_pred_q90[start:end]
w["pi80_coverage"] = prediction_interval_coverage(ya, q10, q90)
windows.append(w)
start += step_size
if not windows:
return {"error": "No valid windows"}
df = pd.DataFrame(windows)
summary = {
"n_windows": len(windows),
"window_size": window_size,
"step_size": step_size,
"total_samples": n,
"mean_da": float(df["da"].mean()),
"std_da": float(df["da"].std()),
"min_da": float(df["da"].min()),
"max_da": float(df["da"].max()),
"mean_sharpe": float(df["sharpe"].mean()),
"std_sharpe": float(df["sharpe"].std()),
"mean_vr": float(df["variance_ratio"].mean()),
"mean_mae": float(df["mae"].mean()),
"mean_tail_capture": float(df["tail_capture"].mean()),
"da_above_50pct": float((df["da"] > 0.50).mean()),
"sharpe_positive_pct": float((df["sharpe"] > 0).mean()),
}
if "pi80_coverage" in df.columns:
summary["mean_pi80_coverage"] = float(df["pi80_coverage"].mean())
return {
"summary": summary,
"windows": windows,
}
def compare_with_baseline(
tft_metrics: dict,
theta_metrics: dict,
) -> dict:
"""
Compare TFT-ASRO backtest results against Theta baseline.
Returns:
Dict with comparison metrics and verdict.
"""
tft_s = tft_metrics.get("summary", {})
theta_s = theta_metrics
comparison = {
"tft_da": tft_s.get("mean_da", 0),
"theta_da": theta_s.get("directional_accuracy", 0),
"tft_sharpe": tft_s.get("mean_sharpe", 0),
"theta_sharpe": theta_s.get("sharpe_ratio", 0),
"tft_mae": tft_s.get("mean_mae", 999),
"theta_mae": theta_s.get("mae", 999),
}
tft_wins = 0
if comparison["tft_da"] > comparison["theta_da"]:
tft_wins += 1
if comparison["tft_sharpe"] > comparison["theta_sharpe"]:
tft_wins += 1
if comparison["tft_mae"] < comparison["theta_mae"]:
tft_wins += 1
comparison["tft_wins"] = tft_wins
comparison["theta_wins"] = 3 - tft_wins
comparison["verdict"] = (
"TFT_SUPERIOR" if tft_wins >= 2
else "THETA_SUPERIOR" if tft_wins == 0
else "MIXED"
)
return comparison
def save_backtest_report(
backtest_results: dict,
comparison: Optional[dict] = None,
output_dir: str = "artifacts/backtest",
) -> Path:
"""Save backtest results to a timestamped JSON file."""
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
report = {
"timestamp": timestamp,
"tft_backtest": backtest_results,
}
if comparison:
report["baseline_comparison"] = comparison
path = out / f"backtest_{timestamp}.json"
path.write_text(json.dumps(report, indent=2, default=str))
logger.info("Backtest report saved to %s", path)
return path
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
parser = argparse.ArgumentParser(description="Run TFT-ASRO walk-forward backtest")
parser.add_argument("--windows", type=int, default=50, help="Backtest window size")
parser.add_argument("--step", type=int, default=10, help="Step size between windows")
args = parser.parse_args()
print(f"Backtest configured: window={args.windows}, step={args.step}")
print("Run after training to evaluate model with actual predictions.")
|