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,9 @@
import numpy as np
import pandas as pd
from strategies.base import Strategy
from strategies.base import StockStrategy, mask_scores
class TrendFollowingStrategy(Strategy):
class TrendFollowingStrategy(StockStrategy):
"""
Per-stock trend following with momentum ranking.
@@ -21,21 +21,22 @@ class TrendFollowingStrategy(Strategy):
self.momentum_period = momentum_period
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:
# Per-stock trend filter: price > MA
ma = data.rolling(self.ma_window).mean()
in_uptrend = data > ma
# Momentum score among trending stocks
momentum = data.pct_change(self.momentum_period)
momentum = data.pct_change(self.momentum_period, fill_method=None)
# Mask out stocks not in uptrend
momentum_filtered = momentum.where(in_uptrend, np.nan)
# Rank and select top_n
momentum_filtered = mask_scores(momentum_filtered, eligible)
n_valid = momentum_filtered.notna().sum(axis=1)
enough = n_valid >= 1
rank = momentum_filtered.rank(axis=1, ascending=False, na_option="bottom")
rank = mask_scores(momentum_filtered, eligible).rank(axis=1, ascending=False, na_option="bottom")
effective_n = n_valid.clip(upper=self.top_n)
top_mask = (rank <= effective_n.values.reshape(-1, 1)) & enough.values.reshape(-1, 1)
# Ensure we only pick stocks that are actually in uptrend