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:
2026-10-01 02:24:01 -07:00
parent 761725d2c8
commit 722cade974
45 changed files with 1561 additions and 1021 deletions

View File

@@ -1,9 +1,14 @@
import numpy as np
import pandas as pd
from strategies.base import Strategy
from strategies.base import StockStrategy, mask_scores
class MomentumQualityStrategy(Strategy):
def rolling_max_drawdown(prices: pd.DataFrame, window: int) -> pd.DataFrame:
return prices.rolling(window).apply(
lambda x: np.min(x / np.maximum.accumulate(x) - 1), raw=True)
class MomentumQualityStrategy(StockStrategy):
"""
Momentum + quality factor strategy using price-derived signals only.
@@ -23,44 +28,39 @@ class MomentumQualityStrategy(Strategy):
self.quality_window = quality_window
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:
# --- Momentum factor ---
momentum = data.shift(self.skip).pct_change(self.momentum_period - self.skip)
momentum = data.shift(self.skip).pct_change(self.momentum_period - self.skip, fill_method=None)
# --- Quality factor 1: return consistency ---
# Rolling 21-day (monthly) returns, then count fraction positive over past year
monthly_ret = data.pct_change(21)
monthly_ret = data.pct_change(21, fill_method=None)
consistency = monthly_ret.rolling(self.quality_window).apply(
lambda x: (x > 0).sum() / len(x), raw=True
)
# --- Quality factor 2: inverse max drawdown ---
# Smaller drawdown = higher quality
def rolling_max_dd(prices: pd.DataFrame, window: int) -> pd.DataFrame:
rolling_max = prices.rolling(window).max()
drawdown = prices / rolling_max - 1
# Rolling worst drawdown (most negative)
worst_dd = drawdown.rolling(window).min()
# Invert: less negative = better, so negate
return -worst_dd # higher = smaller drawdown = better
inv_dd = rolling_max_dd(data, self.quality_window)
quality_dd = rolling_max_drawdown(data, self.quality_window)
# --- Cross-sectional ranking ---
# na_option="keep" so NaN stocks stay NaN in the composite. With
# "bottom" + default ascending=True, NaN entries receive pct=1.0 and
# the additive composite ends up maximal for NaN rows, silently
# selecting pre-IPO / delisted names as "top".
mom_rank = momentum.rank(axis=1, pct=True, na_option="keep")
con_rank = consistency.rank(axis=1, pct=True, na_option="keep")
dd_rank = inv_dd.rank(axis=1, pct=True, na_option="keep")
mom_rank = mask_scores(momentum, eligible).rank(axis=1, pct=True, na_option="keep")
con_rank = mask_scores(consistency, eligible).rank(axis=1, pct=True, na_option="keep")
dd_rank = mask_scores(quality_dd, eligible).rank(axis=1, pct=True, na_option="keep")
# Composite: momentum 50%, consistency 25%, drawdown 25%
scores = 0.50 * mom_rank + 0.25 * con_rank + 0.25 * dd_rank
# --- Select top_n ---
scores = scores.where(data.notna())
scores = mask_scores(scores, eligible)
n_valid = scores.notna().sum(axis=1)
enough = n_valid >= self.top_n
score_rank = scores.rank(axis=1, ascending=False, na_option="bottom")
score_rank = mask_scores(scores, eligible).rank(axis=1, ascending=False, na_option="bottom")
top_mask = (score_rank <= self.top_n) & enough.values.reshape(-1, 1)
raw = top_mask.astype(float)