Niranjan-Murugarasu024
feat: TradeSense AI Chairman Edition production release ready for Hugging Face Spaces
0125724
Raw History Blame Contribute Delete
7.25 kB
"""
TradeSense AI — Multi-Baseline Benchmark Suite
Implements 5 core quantitative baselines that all candidate alpha models must beat:
1. Naive Persistence (Random Walk: P_{t+h} = P_t)
2. Buy & Hold (Passive Asset Exposure)
3. SPY Relative Drift (Broad Market Beta Benchmark)
4. Simple Momentum (Dual Moving Average 20/50 Crossover + ROC)
5. Mean Reversion (Bollinger Band & RSI Oversold Rebound)
"""
from abc import ABC, abstractmethod
from typing import Tuple, List, Dict, Any, Optional
import numpy as np
import pandas as pd
from pydantic import BaseModel, Field
class BaselineMetrics(BaseModel):
"""Out-of-sample performance metrics for a single baseline benchmark."""
model_id: str = Field(..., description="Unique baseline identifier")
name: str = Field(..., description="Human-readable baseline name")
rmse: float = Field(..., description="Root Mean Squared Error vs realized future prices")
mae: float = Field(..., description="Mean Absolute Error vs realized future prices")
directional_accuracy_pct: float = Field(..., description="Directional forecast hit rate (%)")
gross_return_pct: float = Field(..., description="Gross strategy return over test period (%)")
net_return_pct: float = Field(..., description="Net strategy return after transaction frictions (%)")
net_sharpe: float = Field(..., description="Annualized net Sharpe ratio")
max_drawdown_pct: float = Field(..., description="Maximum net drawdown (%)")
class BaselineComparisonSuite(BaseModel):
"""Comprehensive benchmark comparison suite results."""
naive_persistence: BaselineMetrics
buy_and_hold: BaselineMetrics
spy_relative: Optional[BaselineMetrics] = None
momentum: BaselineMetrics
mean_reversion: BaselineMetrics
best_baseline_name: str
best_baseline_rmse: float
candidate_outperforms_all_baselines: bool
class BaseQuantBaseline(ABC):
"""Abstract interface for benchmark models."""
name: str = "BaseBaseline"
model_id: str = "base_baseline"
@abstractmethod
def predict_prices(self, current_prices: np.ndarray, horizon_sessions: int = 21, **kwargs) -> np.ndarray:
"""Generates future price point forecasts for each sample."""
pass
@abstractmethod
def generate_position_signals(self, price_history: np.ndarray, **kwargs) -> np.ndarray:
"""Generates position targets in [-1, 0, +1] for backtesting."""
pass
class NaivePersistenceBaseline(BaseQuantBaseline):
"""
Naive Random Walk: Forecasts future price equals current cutoff price.
P_{t+h} = P_t (Zero expected price change).
"""
name: str = "Naive Persistence"
model_id: str = "baseline_naive_persistence"
def predict_prices(self, current_prices: np.ndarray, horizon_sessions: int = 21, **kwargs) -> np.ndarray:
return np.asarray(current_prices, dtype=float).copy()
def generate_position_signals(self, price_history: np.ndarray, **kwargs) -> np.ndarray:
# Zero active directional positions (flat)
return np.zeros(len(price_history), dtype=float)
class BuyAndHoldBaseline(BaseQuantBaseline):
"""
Passive Buy & Hold: Constant 100% long exposure to underlying equity.
Forecasts future price based on historical drift.
"""
name: str = "Buy & Hold"
model_id: str = "baseline_buy_and_hold"
def predict_prices(self, current_prices: np.ndarray, horizon_sessions: int = 21, **kwargs) -> np.ndarray:
# Extrapolates standard equity risk premium (~8% annualized drift)
daily_drift = 0.08 / 252.0
h_drift = (1.0 + daily_drift) ** horizon_sessions
return np.asarray(current_prices, dtype=float) * h_drift
def generate_position_signals(self, price_history: np.ndarray, **kwargs) -> np.ndarray:
return np.ones(len(price_history), dtype=float)
class SPYRelativeBaseline(BaseQuantBaseline):
"""
SPY Broad Market Drift Benchmark: Evaluates returns relative to SPY ETF.
"""
name: str = "SPY Relative Benchmark"
model_id: str = "baseline_spy_relative"
def predict_prices(self, current_prices: np.ndarray, horizon_sessions: int = 21, **kwargs) -> np.ndarray:
spy_prices = kwargs.get("spy_prices")
if spy_prices is not None and len(spy_prices) == len(current_prices):
# Track SPY return
spy_pct = (spy_prices[-1] - spy_prices[0]) / spy_prices[0] if spy_prices[0] > 0 else 0.0
return np.asarray(current_prices, dtype=float) * (1.0 + spy_pct)
# Fallback to standard market drift
daily_drift = 0.09 / 252.0
h_drift = (1.0 + daily_drift) ** horizon_sessions
return np.asarray(current_prices, dtype=float) * h_drift
def generate_position_signals(self, price_history: np.ndarray, **kwargs) -> np.ndarray:
return np.ones(len(price_history), dtype=float)
class SimpleMomentumBaseline(BaseQuantBaseline):
"""
Dual Moving Average (SMA 20 vs SMA 50) + 21-Day Rate of Change (ROC).
Position = +1 if SMA20 > SMA50 and ROC > 0, else 0 or -1.
"""
name: str = "Simple Momentum"
model_id: str = "baseline_simple_momentum"
def predict_prices(self, current_prices: np.ndarray, horizon_sessions: int = 21, **kwargs) -> np.ndarray:
# Forecast based on 21-day momentum persistence
prices = np.asarray(current_prices, dtype=float)
return prices * 1.01 # Modest momentum drift
def generate_position_signals(self, price_history: np.ndarray, **kwargs) -> np.ndarray:
s = pd.Series(price_history)
sma20 = s.rolling(20, min_periods=1).mean()
sma50 = s.rolling(50, min_periods=1).mean()
roc21 = s.pct_change(21).fillna(0.0)
signals = np.where((sma20 > sma50) & (roc21 > 0), 1.0, np.where((sma20 < sma50) & (roc21 < 0), -1.0, 0.0))
return signals
class MeanReversionBaseline(BaseQuantBaseline):
"""
Bollinger Band & 14-day RSI Mean Reversion.
Goes long when price <= lower band (2 std) and RSI < 30.
Goes short / flat when price >= upper band (2 std) and RSI > 70.
"""
name: str = "Mean Reversion"
model_id: str = "baseline_mean_reversion"
def predict_prices(self, current_prices: np.ndarray, horizon_sessions: int = 21, **kwargs) -> np.ndarray:
prices = np.asarray(current_prices, dtype=float)
return prices # Mean reversion expects convergence
def generate_position_signals(self, price_history: np.ndarray, **kwargs) -> np.ndarray:
s = pd.Series(price_history)
sma20 = s.rolling(20, min_periods=1).mean()
std20 = s.rolling(20, min_periods=1).std().fillna(1.0)
lower_band = sma20 - 2.0 * std20
upper_band = sma20 + 2.0 * std20
# Approximate RSI
delta = s.diff().fillna(0.0)
gain = np.where(delta > 0, delta, 0.0)
loss = np.where(delta < 0, -delta, 0.0)
avg_gain = pd.Series(gain).rolling(14, min_periods=1).mean()
avg_loss = pd.Series(loss).rolling(14, min_periods=1).mean().replace(0, 1e-6)
rs = avg_gain / avg_loss
rsi = 100.0 - (100.0 / (1.0 + rs))
signals = np.where((s <= lower_band) | (rsi < 30), 1.0, np.where((s >= upper_band) | (rsi > 70), -1.0, 0.0))
return signals