Spaces:
Configuration error
Configuration error
Niranjan-Murugarasu024
feat: TradeSense AI Chairman Edition production release ready for Hugging Face Spaces
0125724 Download quant/evaluation/overfitting_diagnostics.py from BlueMen/tradesenseAi: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/spaces/BlueMen/tradesenseAi/resolve/main/quant/evaluation/overfitting_diagnostics.py
- Command line
-
hf download hf://spaces/BlueMen/tradesenseAi/quant/evaluation/overfitting_diagnostics.py
-
curl -L -o overfitting_diagnostics.py https://huggingface.co/spaces/BlueMen/tradesenseAi/resolve/main/quant/evaluation/overfitting_diagnostics.py
10.7 kB
| """ | |
| TradeSense AI — Institutional Overfitting Diagnostics & Deflated Sharpe Ratio | |
| Implements: | |
| 1. Bailey & López de Prado (2014) Deflated Sharpe Ratio (DSR) | |
| 2. Combinatorial Symmetric Cross-Validation (CSCV) Probability of Backtest Overfitting (PBO) | |
| 3. Stationary Block Bootstrap White's Reality Check & Superior Predictive Ability (SPA) | |
| 4. Comprehensive Research Provenance Manifest for cryptographic reproducibility | |
| """ | |
| import math | |
| from typing import List, Dict, Any, Optional, Tuple | |
| from datetime import date, datetime, timezone | |
| import numpy as np | |
| import pandas as pd | |
| from scipy.stats import norm, skew, kurtosis | |
| from pydantic import BaseModel, Field | |
| class ResearchProvenanceManifest(BaseModel): | |
| """Cryptographically verifiable provenance manifest for an empirical quantitative experiment.""" | |
| experiment_id: str | |
| created_at: str | |
| data_provider: str | |
| dataset_sha256: str | |
| universe_tickers: List[str] | |
| benchmark_ticker: str | |
| feature_specification: str | |
| model_specification: str | |
| horizon_sessions: int | |
| lookback_sessions: int | |
| transaction_cost_bps: float | |
| train_period: str | |
| cal_period: str | |
| oos_period: str | |
| n_candidate_configurations_tested: int | |
| random_seed: int | |
| software_environment: str = Field("TradeSense AI v7.5.1 / Python 3.12 / Scikit-Learn / XGBoost") | |
| class DSRResult(BaseModel): | |
| """Result of Bailey & López de Prado Deflated Sharpe Ratio analysis.""" | |
| observed_annualized_sharpe: float | |
| expected_maximum_sharpe_benchmark: float | |
| deflated_sharpe_stat: float | |
| deflated_sharpe_p_value: float | |
| is_statistically_significant: bool | |
| sample_length_sessions: int | |
| skewness: float | |
| excess_kurtosis: float | |
| n_trials_corrected: int | |
| class PBOResult(BaseModel): | |
| """Result of Combinatorial Symmetric Cross-Validation Probability of Backtest Overfitting.""" | |
| pbo_value: float = Field(..., description="Probability of Backtest Overfitting in [0.0, 1.0]") | |
| n_partitions: int | |
| n_combinations: int | |
| performance_degradation_pct: float | |
| is_overfit_risk_high: bool | |
| class OverfittingDiagnosticsEngine: | |
| """ | |
| Mathematical reality checks and multiple-testing deflations for quantitative strategies. | |
| """ | |
| EULER_MASCHERONI: float = 0.57721566490153286 | |
| def compute_expected_max_sharpe(cls, n_trials: int, var_sharpe: float = 1.0) -> float: | |
| """ | |
| Computes expected maximum Sharpe ratio under the null hypothesis of zero true skill across N trials: | |
| E[max(SR_N)] = sqrt(var_sharpe) * [ (1 - gamma)*Z^-1(1 - 1/N) + gamma*Z^-1(1 - 1/(N*e)) ] | |
| """ | |
| N = max(2, n_trials) | |
| z1 = norm.ppf(1.0 - (1.0 / N)) | |
| z2 = norm.ppf(1.0 - (1.0 / (N * math.e))) | |
| em = cls.EULER_MASCHERONI | |
| sr_star = math.sqrt(var_sharpe) * (((1.0 - em) * z1) + (em * z2)) | |
| return float(sr_star) | |
| def compute_deflated_sharpe_ratio( | |
| cls, | |
| daily_returns: np.ndarray, | |
| n_candidate_trials: int = 14, | |
| annualization_factor: float = 252.0, | |
| benchmark_sr_override: Optional[float] = None, | |
| ) -> DSRResult: | |
| """ | |
| Calculates the Deflated Sharpe Ratio (DSR) adjusting for non-normality, sample length, | |
| and multiple testing across N candidate configurations. | |
| """ | |
| rets = np.asarray(daily_returns, dtype=float).ravel() | |
| T = len(rets) | |
| if T < 10: | |
| return DSRResult( | |
| observed_annualized_sharpe=0.0, | |
| expected_maximum_sharpe_benchmark=0.0, | |
| deflated_sharpe_stat=0.0, | |
| deflated_sharpe_p_value=1.0, | |
| is_statistically_significant=False, | |
| sample_length_sessions=T, | |
| skewness=0.0, | |
| excess_kurtosis=0.0, | |
| n_trials_corrected=n_candidate_trials, | |
| ) | |
| mean_r = float(np.mean(rets)) | |
| std_r = float(np.std(rets)) | |
| if std_r <= 1e-9: | |
| return DSRResult( | |
| observed_annualized_sharpe=0.0, | |
| expected_maximum_sharpe_benchmark=0.0, | |
| deflated_sharpe_stat=0.0, | |
| deflated_sharpe_p_value=1.0, | |
| is_statistically_significant=False, | |
| sample_length_sessions=T, | |
| skewness=0.0, | |
| excess_kurtosis=0.0, | |
| n_trials_corrected=n_candidate_trials, | |
| ) | |
| sr_daily = mean_r / std_r | |
| sr_annual = sr_daily * math.sqrt(annualization_factor) | |
| # Higher statistical moments | |
| sk = float(skew(rets)) | |
| kurt = float(kurtosis(rets)) # Fisher kurtosis (normal == 0) | |
| # Expected maximum Sharpe across N trials | |
| sr_star_daily = (benchmark_sr_override / math.sqrt(annualization_factor)) if benchmark_sr_override is not None else (cls.compute_expected_max_sharpe(n_candidate_trials) / math.sqrt(annualization_factor)) | |
| # Standard error of Sharpe ratio under non-normality (Mertens, 2002) | |
| # Var(SR) = (1 - gamma3*SR + (gamma4 - 1)/4 * SR^2) / (T - 1) | |
| var_sr = (1.0 - (sk * sr_daily) + (((kurt + 2.0) / 4.0) * (sr_daily ** 2))) / (T - 1.0) | |
| se_sr = math.sqrt(max(1e-8, var_sr)) | |
| dsr_stat = (sr_daily - sr_star_daily) / se_sr | |
| dsr_p_val = 1.0 - float(norm.cdf(dsr_stat)) | |
| return DSRResult( | |
| observed_annualized_sharpe=round(sr_annual, 2), | |
| expected_maximum_sharpe_benchmark=round(sr_star_daily * math.sqrt(annualization_factor), 2), | |
| deflated_sharpe_stat=round(dsr_stat, 4), | |
| deflated_sharpe_p_value=round(dsr_p_val, 4), | |
| is_statistically_significant=(dsr_p_val <= 0.05), | |
| sample_length_sessions=T, | |
| skewness=round(sk, 3), | |
| excess_kurtosis=round(kurt, 3), | |
| n_trials_corrected=n_candidate_trials, | |
| ) | |
| def compute_pbo_cscv( | |
| cls, | |
| strategy_returns_matrix: np.ndarray, | |
| n_splits: int = 6, | |
| ) -> PBOResult: | |
| """ | |
| Evaluates Probability of Backtest Overfitting (PBO) via Combinatorial Symmetric Cross-Validation. | |
| strategy_returns_matrix: Shape (T, M) where T is sessions, M is candidate strategy configurations. | |
| """ | |
| T, M = strategy_returns_matrix.shape | |
| if T < 30 or M < 2 or n_splits < 4 or n_splits % 2 != 0: | |
| return PBOResult( | |
| pbo_value=0.5, | |
| n_partitions=n_splits, | |
| n_combinations=1, | |
| performance_degradation_pct=0.0, | |
| is_overfit_risk_high=False, | |
| ) | |
| # Split into S sub-matrices | |
| split_size = T // n_splits | |
| blocks = [strategy_returns_matrix[i * split_size : (i + 1) * split_size] for i in range(n_splits)] | |
| # Generate combinatorial combinations of N/2 train blocks vs N/2 test blocks | |
| from itertools import combinations | |
| k = n_splits // 2 | |
| all_combs = list(combinations(range(n_splits), k)) | |
| n_combs = len(all_combs) | |
| overfit_count = 0 | |
| perf_degradations = [] | |
| for train_indices in all_combs: | |
| test_indices = [idx for idx in range(n_splits) if idx not in train_indices] | |
| train_data = np.vstack([blocks[i] for i in train_indices]) | |
| test_data = np.vstack([blocks[i] for i in test_indices]) | |
| # In-sample Sharpe per candidate | |
| is_means = np.mean(train_data, axis=0) | |
| is_stds = np.std(train_data, axis=0) + 1e-8 | |
| is_sharpes = is_means / is_stds | |
| # Out-of-sample Sharpe per candidate | |
| oos_means = np.mean(test_data, axis=0) | |
| oos_stds = np.std(test_data, axis=0) + 1e-8 | |
| oos_sharpes = oos_means / oos_stds | |
| best_is_idx = int(np.argmax(is_sharpes)) | |
| oos_rank = np.argsort(np.argsort(oos_sharpes))[best_is_idx] | |
| oos_percentile = oos_rank / float(M - 1) | |
| # PBO counts instances where best IS strategy falls below median OOS | |
| if oos_percentile < 0.50: | |
| overfit_count += 1 | |
| degradation = is_sharpes[best_is_idx] - oos_sharpes[best_is_idx] | |
| perf_degradations.append(degradation) | |
| pbo = float(overfit_count / max(1, n_combs)) | |
| mean_deg = float(np.mean(perf_degradations)) if perf_degradations else 0.0 | |
| return PBOResult( | |
| pbo_value=round(pbo, 4), | |
| n_partitions=n_splits, | |
| n_combinations=n_combs, | |
| performance_degradation_pct=round(mean_deg * 100.0, 2), | |
| is_overfit_risk_high=(pbo > 0.50), | |
| ) | |
| def stationary_block_bootstrap_spa( | |
| cls, | |
| candidate_loss: np.ndarray, | |
| benchmark_losses_matrix: np.ndarray, | |
| block_length: int = 10, | |
| n_bootstraps: int = 500, | |
| ) -> float: | |
| """ | |
| Implements Hansen Superior Predictive Ability (SPA) bootstrap p-value | |
| preserving serial correlation through stationary block resampling. | |
| candidate_loss: Shape (T,) - Loss of candidate strategy | |
| benchmark_losses_matrix: Shape (T, K) - Losses of K benchmark strategies | |
| """ | |
| T = len(candidate_loss) | |
| K = benchmark_losses_matrix.shape[1] if benchmark_losses_matrix.ndim > 1 else 1 | |
| if T < 20: | |
| return 1.0 | |
| # Loss differentials: d_k,t = L_k,t - L_candidate,t (positive means candidate is better) | |
| if benchmark_losses_matrix.ndim == 1: | |
| diffs = (benchmark_losses_matrix - candidate_loss).reshape(-1, 1) | |
| else: | |
| diffs = benchmark_losses_matrix - candidate_loss[:, None] | |
| mean_diffs = np.mean(diffs, axis=0) | |
| max_t_stat = np.max(mean_diffs / (np.std(diffs, axis=0) / math.sqrt(T) + 1e-8)) | |
| # Stationary Block Bootstrap | |
| p_geom = 1.0 / max(1, block_length) | |
| boot_max_stats = [] | |
| np.random.seed(42) | |
| for _ in range(n_bootstraps): | |
| # Generate resampled time indices | |
| indices = [] | |
| cur_idx = np.random.randint(0, T) | |
| for _ in range(T): | |
| indices.append(cur_idx) | |
| if np.random.rand() < p_geom: | |
| cur_idx = np.random.randint(0, T) | |
| else: | |
| cur_idx = (cur_idx + 1) % T | |
| boot_diffs = diffs[indices] | |
| boot_means = np.mean(boot_diffs, axis=0) - mean_diffs # Centered under null | |
| boot_stds = np.std(boot_diffs, axis=0) / math.sqrt(T) + 1e-8 | |
| boot_max_stats.append(np.max(boot_means / boot_stds)) | |
| boot_arr = np.array(boot_max_stats) | |
| spa_p_val = float(np.mean(boot_arr >= max_t_stat)) | |
| return round(spa_p_val, 4) | |