fix: unify backtest execution and add forward validation candidates
Share point-in-time signals and a cash-funded order ledger across backtests and trading. Correct eligibility, missing-price fills, quality factors, regime inputs, warmup windows, and cash-injection accounting. Add reproducible registered-strategy comparisons and paired forward candidates with a 20% resize band. Validation: 125 Python tests, 23 web tests, TypeScript/Vite build, 87 strategy causality checks, and real-data target/order/equity parity for 10 strategies.
This commit is contained in:
@@ -14,14 +14,14 @@ Also tests:
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from strategies.base import Strategy
|
||||
from strategies.base import StockStrategy, mask_scores
|
||||
|
||||
|
||||
def _rank(df):
|
||||
return df.rank(axis=1, pct=True, na_option="keep")
|
||||
def _rank(df, eligible=None):
|
||||
return mask_scores(df, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
|
||||
|
||||
class HybridAlphaStrategy(Strategy):
|
||||
class HybridAlphaStrategy(StockStrategy):
|
||||
"""
|
||||
Combines FactorCombo's best signal with risk-parity weighting.
|
||||
"""
|
||||
@@ -40,28 +40,29 @@ class HybridAlphaStrategy(Strategy):
|
||||
self.use_invvol = use_invvol
|
||||
self.regime_dampen = regime_dampen
|
||||
|
||||
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
|
||||
def generate_signals(self, data: pd.DataFrame, eligible: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
p = data
|
||||
|
||||
# --- Signal: rec_mfilt + deep x upvol (from FactorCombo) ---
|
||||
# Recovery momentum-filtered
|
||||
rec = p / p.rolling(126, min_periods=126).min() - 1
|
||||
mom = p.shift(21).pct_change(105)
|
||||
mom = p.shift(21).pct_change(105, fill_method=None)
|
||||
rec_mfilt = rec.where(mom > 0, np.nan)
|
||||
rec_mfilt_r = _rank(rec_mfilt)
|
||||
rec_mfilt_r = _rank(rec_mfilt, eligible)
|
||||
|
||||
# Deep recovery x up-volume
|
||||
rec_126 = p / p.rolling(126, min_periods=126).min() - 1
|
||||
ret = p.pct_change()
|
||||
ret = p.pct_change(fill_method=None)
|
||||
up_vol = ret.where(ret > 0, 0).rolling(20, min_periods=15).sum()
|
||||
deep_upvol = _rank(rec_126) * _rank(up_vol)
|
||||
deep_upvol_r = _rank(deep_upvol)
|
||||
deep_upvol = _rank(rec_126, eligible) * _rank(up_vol, eligible)
|
||||
deep_upvol_r = _rank(deep_upvol, eligible)
|
||||
|
||||
# Combined signal
|
||||
signal = 0.5 * rec_mfilt_r + 0.5 * deep_upvol_r
|
||||
|
||||
# --- Select top_n ---
|
||||
rank = signal.rank(axis=1, ascending=False, na_option="bottom")
|
||||
rank = mask_scores(signal, eligible).rank(axis=1, ascending=False, na_option="bottom")
|
||||
signal = mask_scores(signal, eligible)
|
||||
n_valid = signal.notna().sum(axis=1)
|
||||
enough = n_valid >= self.top_n
|
||||
top_mask = (rank <= self.top_n) & enough.values.reshape(-1, 1)
|
||||
@@ -81,7 +82,7 @@ class HybridAlphaStrategy(Strategy):
|
||||
# --- Light regime dampening ---
|
||||
if self.regime_dampen < 1.0:
|
||||
# Use market-wide vol regime instead of MA200 (more responsive)
|
||||
market_vol = ret.mean(axis=1).rolling(20).std() * np.sqrt(252)
|
||||
market_vol = mask_scores(ret, eligible).mean(axis=1).rolling(20).std() * np.sqrt(252)
|
||||
vol_90th = market_vol.rolling(252, min_periods=126).quantile(0.90)
|
||||
high_vol = market_vol > vol_90th
|
||||
regime_scale = pd.Series(1.0, index=data.index)
|
||||
@@ -101,7 +102,7 @@ class HybridAlphaStrategy(Strategy):
|
||||
return signals.shift(1).fillna(0.0)
|
||||
|
||||
|
||||
class RecoveryQualityBlendStrategy(Strategy):
|
||||
class RecoveryQualityBlendStrategy(StockStrategy):
|
||||
"""
|
||||
Blends recovery, momentum, and quality without strict MA200 filter.
|
||||
Uses intermediate momentum as a soft signal (not hard gate).
|
||||
@@ -125,34 +126,34 @@ class RecoveryQualityBlendStrategy(Strategy):
|
||||
self.rebal_freq = rebal_freq
|
||||
self.top_n = top_n
|
||||
|
||||
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
|
||||
def generate_signals(self, data: pd.DataFrame, eligible: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
p = data
|
||||
|
||||
# Recovery
|
||||
recovery = p / p.rolling(self.recovery_window, min_periods=self.recovery_window).min() - 1
|
||||
|
||||
# 12-1 month momentum
|
||||
momentum = p.shift(self.mom_skip).pct_change(self.mom_lookback - self.mom_skip)
|
||||
momentum = p.shift(self.mom_skip).pct_change(self.mom_lookback - self.mom_skip, fill_method=None)
|
||||
|
||||
# Intermediate momentum (7m)
|
||||
int_mom = p.shift(self.mom_skip).pct_change(147 - self.mom_skip)
|
||||
int_mom = p.shift(self.mom_skip).pct_change(147 - self.mom_skip, fill_method=None)
|
||||
|
||||
# Quality: consistency
|
||||
monthly_ret = p.pct_change(21)
|
||||
monthly_ret = p.pct_change(21, fill_method=None)
|
||||
consistency = (monthly_ret > 0).astype(float).rolling(
|
||||
self.quality_window, min_periods=self.quality_window // 2
|
||||
).mean()
|
||||
|
||||
# Up-volume proxy
|
||||
ret = p.pct_change()
|
||||
ret = p.pct_change(fill_method=None)
|
||||
up_vol = ret.where(ret > 0, 0).rolling(20, min_periods=15).sum()
|
||||
|
||||
# Cross-sectional ranks
|
||||
rec_rank = _rank(recovery)
|
||||
mom_rank = _rank(momentum)
|
||||
int_mom_rank = _rank(int_mom)
|
||||
con_rank = _rank(consistency)
|
||||
upv_rank = _rank(up_vol)
|
||||
rec_rank = _rank(recovery, eligible)
|
||||
mom_rank = _rank(momentum, eligible)
|
||||
int_mom_rank = _rank(int_mom, eligible)
|
||||
con_rank = _rank(consistency, eligible)
|
||||
upv_rank = _rank(up_vol, eligible)
|
||||
|
||||
# Composite: weighted blend of all factors
|
||||
# Recovery 25%, momentum 25%, intermediate momentum 20%, quality 15%, up_vol 15%
|
||||
@@ -160,7 +161,8 @@ class RecoveryQualityBlendStrategy(Strategy):
|
||||
0.15 * con_rank + 0.15 * upv_rank)
|
||||
|
||||
# Select top_n
|
||||
rank = composite.rank(axis=1, ascending=False, na_option="bottom")
|
||||
rank = mask_scores(composite, eligible).rank(axis=1, ascending=False, na_option="bottom")
|
||||
composite = mask_scores(composite, eligible)
|
||||
n_valid = composite.notna().sum(axis=1)
|
||||
enough = n_valid >= self.top_n
|
||||
top_mask = (rank <= self.top_n) & enough.values.reshape(-1, 1)
|
||||
|
||||
Reference in New Issue
Block a user