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:
@@ -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 AdaptiveMomentumStrategy(Strategy):
|
||||
class AdaptiveMomentumStrategy(StockStrategy):
|
||||
"""
|
||||
Momentum with dynamic position sizing via inverse-volatility weighting.
|
||||
|
||||
@@ -25,18 +25,19 @@ class AdaptiveMomentumStrategy(Strategy):
|
||||
self.vol_window = vol_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 ranking
|
||||
momentum = data.shift(self.skip).pct_change(self.lookback - self.skip)
|
||||
momentum = data.shift(self.skip).pct_change(self.lookback - self.skip, fill_method=None)
|
||||
|
||||
momentum = mask_scores(momentum, eligible)
|
||||
n_valid = momentum.notna().sum(axis=1)
|
||||
enough = n_valid >= self.top_n
|
||||
|
||||
score_rank = momentum.rank(axis=1, ascending=False, na_option="bottom")
|
||||
score_rank = mask_scores(momentum, eligible).rank(axis=1, ascending=False, na_option="bottom")
|
||||
top_mask = (score_rank <= self.top_n) & enough.values.reshape(-1, 1)
|
||||
|
||||
# Inverse-vol weighting among selected stocks
|
||||
returns = data.pct_change()
|
||||
returns = data.pct_change(fill_method=None)
|
||||
vol = returns.rolling(self.vol_window).std().replace(0, np.nan)
|
||||
inv_vol = (1.0 / vol).where(top_mask, 0.0)
|
||||
|
||||
@@ -44,7 +45,7 @@ class AdaptiveMomentumStrategy(Strategy):
|
||||
signals = inv_vol.div(row_sums, axis=0).fillna(0.0)
|
||||
|
||||
# Regime scaling: compare current market vol to its 1-year median
|
||||
market_vol = vol.mean(axis=1)
|
||||
market_vol = mask_scores(vol, eligible).mean(axis=1)
|
||||
vol_median = market_vol.rolling(252).median()
|
||||
vol_scale = (vol_median / market_vol).clip(0.3, 1.5)
|
||||
signals = signals.mul(vol_scale, axis=0)
|
||||
|
||||
@@ -121,6 +121,7 @@ class AgentReviewStrategy(BarStrategy):
|
||||
eligible = close.notna()
|
||||
if "eligible" in bars:
|
||||
eligible &= bars["eligible"].reindex_like(close).fillna(False).astype(bool)
|
||||
panel["eligible"] = eligible
|
||||
return self._score(panel).where(eligible)
|
||||
|
||||
def generate_weights(self, bars: dict[str, pd.DataFrame]) -> pd.DataFrame:
|
||||
|
||||
@@ -20,6 +20,14 @@ class Strategy(ABC):
|
||||
pass
|
||||
|
||||
|
||||
def mask_scores(scores: pd.DataFrame, eligible: pd.DataFrame | None) -> pd.DataFrame:
|
||||
return scores if eligible is None else scores.where(eligible.reindex_like(scores).fillna(False))
|
||||
|
||||
|
||||
class StockStrategy(Strategy):
|
||||
accepts_eligibility = True
|
||||
|
||||
|
||||
class BarStrategy(Strategy):
|
||||
"""Strategy on completed daily bars with several fields.
|
||||
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
import pandas as pd
|
||||
from strategies.base import Strategy
|
||||
from strategies.base import StockStrategy, mask_scores
|
||||
|
||||
class BuyAndHoldStrategy(Strategy):
|
||||
"""
|
||||
A simple buy and hold strategy.
|
||||
"""
|
||||
|
||||
def generate_signals(self, data):
|
||||
"""
|
||||
Generates equal weights for all assets.
|
||||
"""
|
||||
tickers = data.columns
|
||||
weights = pd.DataFrame(1 / len(tickers), index=data.index, columns=tickers)
|
||||
class BuyAndHoldStrategy(StockStrategy):
|
||||
def __init__(self, asset: str | None = None):
|
||||
self.asset = asset
|
||||
|
||||
def generate_signals(self, data, eligible=None):
|
||||
if self.asset is not None:
|
||||
if self.asset not in data:
|
||||
raise ValueError(f"Missing buy-and-hold benchmark: {self.asset}")
|
||||
weights = pd.DataFrame(0.0, index=data.index, columns=data.columns)
|
||||
weights[self.asset] = data[self.asset].notna().astype(float)
|
||||
else:
|
||||
# A fixed initial basket; new listings never enter retrospectively.
|
||||
first = data.iloc[0]
|
||||
values = data.ffill().div(first).where(first.notna(), 0.0).fillna(0.0)
|
||||
weights = values.div(values.sum(axis=1).replace(0, float('nan')), axis=0).fillna(0.0)
|
||||
return weights.shift(1).fillna(0.0)
|
||||
|
||||
@@ -15,10 +15,10 @@ With:
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from strategies.base import Strategy
|
||||
from strategies.base import StockStrategy, mask_scores
|
||||
|
||||
|
||||
class CompositeAlphaStrategy(Strategy):
|
||||
class CompositeAlphaStrategy(StockStrategy):
|
||||
"""
|
||||
Multi-factor alpha composite with regime gating.
|
||||
"""
|
||||
@@ -49,7 +49,9 @@ class CompositeAlphaStrategy(Strategy):
|
||||
self.regime_gate = regime_gate
|
||||
self.regime_ma = regime_ma
|
||||
|
||||
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
|
||||
def generate_signals(self, data: pd.DataFrame, eligible: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
if self.regime_gate and self.benchmark not in data.columns:
|
||||
raise ValueError(f"Missing regime benchmark: {self.benchmark}")
|
||||
# Separate benchmark from stocks if needed
|
||||
if self.tickers is not None:
|
||||
stock_data = data[[t for t in self.tickers if t in data.columns]]
|
||||
@@ -63,17 +65,17 @@ class CompositeAlphaStrategy(Strategy):
|
||||
).min() - 1
|
||||
|
||||
# --- Factor 2: Intermediate momentum (7-month, skip 1 month) ---
|
||||
int_mom = stock_data.shift(self.skip).pct_change(self.intermediate_period - self.skip)
|
||||
int_mom = stock_data.shift(self.skip).pct_change(self.intermediate_period - self.skip, fill_method=None)
|
||||
|
||||
# --- Factor 3: Quality composite ---
|
||||
# Consistency: fraction of positive 21-day returns
|
||||
monthly_ret = stock_data.pct_change(21)
|
||||
monthly_ret = stock_data.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: sum of positive daily returns over 20 days
|
||||
daily_ret = stock_data.pct_change()
|
||||
daily_ret = stock_data.pct_change(fill_method=None)
|
||||
up_vol_proxy = daily_ret.where(daily_ret > 0, 0).rolling(20, min_periods=15).sum()
|
||||
|
||||
# --- Factor 4: Above MA200 (per-stock trend filter) ---
|
||||
@@ -81,10 +83,10 @@ class CompositeAlphaStrategy(Strategy):
|
||||
above_ma = (stock_data > ma200)
|
||||
|
||||
# --- Cross-sectional ranks ---
|
||||
rec_rank = recovery.rank(axis=1, pct=True, na_option="keep")
|
||||
mom_rank = int_mom.rank(axis=1, pct=True, na_option="keep")
|
||||
con_rank = consistency.rank(axis=1, pct=True, na_option="keep")
|
||||
upv_rank = up_vol_proxy.rank(axis=1, pct=True, na_option="keep")
|
||||
rec_rank = mask_scores(recovery, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
mom_rank = mask_scores(int_mom, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
con_rank = mask_scores(consistency, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
upv_rank = mask_scores(up_vol_proxy, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
|
||||
# Composite: recovery 30%, int_momentum 30%, consistency 20%, up_volume 20%
|
||||
composite = (0.30 * rec_rank + 0.30 * mom_rank +
|
||||
@@ -94,7 +96,8 @@ class CompositeAlphaStrategy(Strategy):
|
||||
composite = composite.where(above_ma, np.nan)
|
||||
|
||||
# --- 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 >= min(self.top_n, 5)
|
||||
top_mask = (rank <= self.top_n) & enough.values.reshape(-1, 1)
|
||||
|
||||
@@ -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 DualMomentumStrategy(Strategy):
|
||||
class DualMomentumStrategy(StockStrategy):
|
||||
"""
|
||||
Dual momentum with multi-timeframe confirmation.
|
||||
|
||||
@@ -19,29 +19,31 @@ class DualMomentumStrategy(Strategy):
|
||||
def __init__(self, top_n: int = 20):
|
||||
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:
|
||||
# Three timeframe returns (each skipping most recent 5 days)
|
||||
skip = 5
|
||||
short_mom = data.shift(skip).pct_change(63 - skip) # ~3 month
|
||||
med_mom = data.shift(skip).pct_change(126 - skip) # ~6 month
|
||||
long_mom = data.shift(skip).pct_change(252 - skip) # ~12 month
|
||||
short_mom = data.shift(skip).pct_change(63 - skip, fill_method=None) # ~3 month
|
||||
med_mom = data.shift(skip).pct_change(126 - skip, fill_method=None) # ~6 month
|
||||
long_mom = data.shift(skip).pct_change(252 - skip, fill_method=None) # ~12 month
|
||||
|
||||
# All three must be positive (absolute momentum across timeframes)
|
||||
all_positive = (short_mom > 0) & (med_mom > 0) & (long_mom > 0)
|
||||
|
||||
# Composite score: average percentile rank across timeframes
|
||||
short_rank = short_mom.rank(axis=1, pct=True, na_option="keep")
|
||||
med_rank = med_mom.rank(axis=1, pct=True, na_option="keep")
|
||||
long_rank = long_mom.rank(axis=1, pct=True, na_option="keep")
|
||||
short_rank = mask_scores(short_mom, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
med_rank = mask_scores(med_mom, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
long_rank = mask_scores(long_mom, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
composite = (short_rank + med_rank + long_rank) / 3
|
||||
|
||||
# Only consider stocks passing absolute filter
|
||||
composite_filtered = composite.where(all_positive, np.nan)
|
||||
|
||||
composite_filtered = composite_filtered.where(data.notna())
|
||||
composite_filtered = mask_scores(composite_filtered, eligible)
|
||||
n_valid = composite_filtered.notna().sum(axis=1)
|
||||
enough = n_valid >= 1
|
||||
|
||||
rank = composite_filtered.rank(axis=1, ascending=False, na_option="bottom")
|
||||
rank = mask_scores(composite_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)
|
||||
top_mask = top_mask & all_positive
|
||||
|
||||
@@ -11,10 +11,10 @@ Improvements over base RecoveryMomentumStrategy:
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from strategies.base import Strategy
|
||||
from strategies.base import StockStrategy, mask_scores
|
||||
|
||||
|
||||
class EnhancedRecoveryMomentumStrategy(Strategy):
|
||||
class EnhancedRecoveryMomentumStrategy(StockStrategy):
|
||||
"""
|
||||
Recovery + momentum with inverse-vol weighting and regime awareness.
|
||||
"""
|
||||
@@ -39,34 +39,35 @@ class EnhancedRecoveryMomentumStrategy(Strategy):
|
||||
self.top_n = top_n
|
||||
self.regime_scale = regime_scale
|
||||
|
||||
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
|
||||
def generate_signals(self, data: pd.DataFrame, eligible: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
# Factor 1: Recovery — price / rolling min
|
||||
recovery = data / data.rolling(self.recovery_window, min_periods=self.recovery_window).min() - 1
|
||||
|
||||
# Factor 2: 12-1 month momentum
|
||||
momentum = data.shift(self.mom_skip).pct_change(self.mom_lookback - self.mom_skip)
|
||||
momentum = data.shift(self.mom_skip).pct_change(self.mom_lookback - self.mom_skip, fill_method=None)
|
||||
|
||||
# Factor 3: Intermediate momentum (6m) as a filter gate
|
||||
# Only consider stocks with positive intermediate trend
|
||||
intermediate = data.shift(self.mom_skip).pct_change(self.intermediate_mom - self.mom_skip)
|
||||
intermediate = data.shift(self.mom_skip).pct_change(self.intermediate_mom - self.mom_skip, fill_method=None)
|
||||
trend_gate = intermediate > 0
|
||||
|
||||
# Cross-sectional percentile ranks
|
||||
rec_rank = recovery.rank(axis=1, pct=True, na_option="keep")
|
||||
mom_rank = momentum.rank(axis=1, pct=True, na_option="keep")
|
||||
rec_rank = mask_scores(recovery, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
mom_rank = mask_scores(momentum, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
|
||||
# Composite score (50/50), gated by intermediate trend
|
||||
composite = 0.5 * rec_rank + 0.5 * mom_rank
|
||||
composite = composite.where(trend_gate, np.nan)
|
||||
|
||||
# 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)
|
||||
|
||||
# Inverse-vol weighting among selected stocks
|
||||
returns = data.pct_change()
|
||||
returns = data.pct_change(fill_method=None)
|
||||
vol = returns.rolling(self.vol_window, min_periods=30).std().replace(0, np.nan)
|
||||
inv_vol = (1.0 / vol).where(top_mask, 0.0)
|
||||
|
||||
@@ -75,7 +76,7 @@ class EnhancedRecoveryMomentumStrategy(Strategy):
|
||||
|
||||
# Regime scaling: reduce exposure when market vol is high
|
||||
if self.regime_scale:
|
||||
market_vol = vol.mean(axis=1)
|
||||
market_vol = mask_scores(vol, eligible).mean(axis=1)
|
||||
vol_median = market_vol.rolling(252, min_periods=126).median()
|
||||
vol_ratio = (vol_median / market_vol).clip(0.5, 1.2)
|
||||
signals = signals.mul(vol_ratio, axis=0)
|
||||
|
||||
@@ -19,14 +19,14 @@ New approach:
|
||||
|
||||
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 EnsembleAlphaStrategy(Strategy):
|
||||
class EnsembleAlphaStrategy(StockStrategy):
|
||||
"""
|
||||
Ensemble of the two strongest signals with tail-risk protection.
|
||||
"""
|
||||
@@ -45,28 +45,28 @@ class EnsembleAlphaStrategy(Strategy):
|
||||
self.tail_threshold = tail_threshold
|
||||
self.tail_scale = tail_scale
|
||||
|
||||
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 A: rec_mfilt + deep_upvol (from FactorCombo) ===
|
||||
rec_126 = p / p.rolling(126, min_periods=126).min() - 1
|
||||
mom_filter = p.shift(21).pct_change(105)
|
||||
mom_filter = p.shift(21).pct_change(105, fill_method=None)
|
||||
rec_mfilt = rec_126.where(mom_filter > 0, np.nan)
|
||||
rec_mfilt_r = _rank(rec_mfilt)
|
||||
rec_mfilt_r = _rank(rec_mfilt, eligible)
|
||||
|
||||
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)
|
||||
|
||||
signal_a = 0.5 * rec_mfilt_r + 0.5 * deep_upvol_r
|
||||
|
||||
# === Signal B: Recovery 63d + 12-1 momentum (from RecoveryMom) ===
|
||||
rec_63 = p / p.rolling(63, min_periods=63).min() - 1
|
||||
mom_12_1 = p.shift(21).pct_change(231)
|
||||
mom_12_1 = p.shift(21).pct_change(231, fill_method=None)
|
||||
|
||||
rec_63_r = _rank(rec_63)
|
||||
mom_r = _rank(mom_12_1)
|
||||
rec_63_r = _rank(rec_63, eligible)
|
||||
mom_r = _rank(mom_12_1, eligible)
|
||||
|
||||
signal_b = 0.5 * rec_63_r + 0.5 * mom_r
|
||||
|
||||
@@ -74,7 +74,9 @@ class EnsembleAlphaStrategy(Strategy):
|
||||
ensemble = 0.5 * signal_a + 0.5 * signal_b
|
||||
|
||||
# === Select top_n ===
|
||||
rank = ensemble.rank(axis=1, ascending=False, na_option="bottom")
|
||||
ensemble = ensemble.where(data.notna())
|
||||
rank = mask_scores(ensemble, eligible).rank(axis=1, ascending=False, na_option="bottom")
|
||||
ensemble = mask_scores(ensemble, eligible)
|
||||
n_valid = ensemble.notna().sum(axis=1)
|
||||
enough = n_valid >= self.top_n
|
||||
top_mask = (rank <= self.top_n) & enough.values.reshape(-1, 1)
|
||||
@@ -99,7 +101,7 @@ class EnsembleAlphaStrategy(Strategy):
|
||||
# otherwise daily flips force half-out/half-in trades that burn
|
||||
# the account through fixed per-trade fees.
|
||||
if self.tail_protection:
|
||||
mkt_ret = ret.mean(axis=1, skipna=True)
|
||||
mkt_ret = mask_scores(ret, eligible).mean(axis=1, skipna=True)
|
||||
mkt_eq = (1 + mkt_ret.fillna(0.0)).cumprod()
|
||||
mkt_dd = mkt_eq / mkt_eq.cummax() - 1
|
||||
in_tail = mkt_dd < self.tail_threshold
|
||||
@@ -111,7 +113,7 @@ class EnsembleAlphaStrategy(Strategy):
|
||||
return signals.shift(1).fillna(0.0)
|
||||
|
||||
|
||||
class EnhancedFactorComboStrategy(Strategy):
|
||||
class EnhancedFactorComboStrategy(StockStrategy):
|
||||
"""
|
||||
FactorCombo signal enhanced with:
|
||||
1. Additional momentum confirmation (12-1 momentum rank as tiebreaker)
|
||||
@@ -131,31 +133,33 @@ class EnhancedFactorComboStrategy(Strategy):
|
||||
self.mom_boost = mom_boost
|
||||
self.tail_protection = tail_protection
|
||||
|
||||
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
|
||||
|
||||
# Core signal: rec_mfilt + deep_upvol
|
||||
rec_126 = p / p.rolling(126, min_periods=126).min() - 1
|
||||
mom_filter = p.shift(21).pct_change(105)
|
||||
mom_filter = p.shift(21).pct_change(105, fill_method=None)
|
||||
rec_mfilt = rec_126.where(mom_filter > 0, np.nan)
|
||||
rec_mfilt_r = _rank(rec_mfilt)
|
||||
rec_mfilt_r = _rank(rec_mfilt, eligible)
|
||||
|
||||
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)
|
||||
|
||||
base_signal = 0.5 * rec_mfilt_r + 0.5 * deep_upvol_r
|
||||
|
||||
# Momentum boost: 12-1 month return rank
|
||||
mom_12_1 = p.shift(21).pct_change(231)
|
||||
mom_r = _rank(mom_12_1)
|
||||
mom_12_1 = p.shift(21).pct_change(231, fill_method=None)
|
||||
mom_r = _rank(mom_12_1, eligible)
|
||||
|
||||
# Combined: base + momentum tiebreaker
|
||||
signal = (1 - self.mom_boost) * base_signal + self.mom_boost * mom_r
|
||||
|
||||
# Select top_n
|
||||
rank = signal.rank(axis=1, ascending=False, na_option="bottom")
|
||||
signal = signal.where(data.notna())
|
||||
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)
|
||||
@@ -177,7 +181,7 @@ class EnhancedFactorComboStrategy(Strategy):
|
||||
|
||||
# Tail protection (rebal-gated to avoid daily-flip turnover)
|
||||
if self.tail_protection:
|
||||
mkt_ret = ret.mean(axis=1, skipna=True)
|
||||
mkt_ret = mask_scores(ret, eligible).mean(axis=1, skipna=True)
|
||||
mkt_eq = (1 + mkt_ret.fillna(0.0)).cumprod()
|
||||
mkt_dd = mkt_eq / mkt_eq.cummax() - 1
|
||||
in_tail = mkt_dd < -0.15
|
||||
@@ -189,7 +193,7 @@ class EnhancedFactorComboStrategy(Strategy):
|
||||
return signals.shift(1).fillna(0.0)
|
||||
|
||||
|
||||
class RiskManagedEnsembleStrategy(Strategy):
|
||||
class RiskManagedEnsembleStrategy(StockStrategy):
|
||||
"""
|
||||
EnsembleAlpha with market-aware drawdown risk management.
|
||||
|
||||
@@ -230,15 +234,15 @@ class RiskManagedEnsembleStrategy(Strategy):
|
||||
self.vol_spike_lookback = vol_spike_lookback
|
||||
self.vol_spike_floor = vol_spike_floor
|
||||
|
||||
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
|
||||
def generate_signals(self, data: pd.DataFrame, eligible: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
# Step 1: Get raw signals from the ensemble (already shifted by 1)
|
||||
raw = self.ensemble.generate_signals(data)
|
||||
raw = self.ensemble.generate_signals(data, eligible=eligible)
|
||||
|
||||
# Step 2: Compute MARKET returns over valid (non-masked) columns.
|
||||
# `daily_rets` keeps NaN for PIT-masked tickers so they don't dilute
|
||||
# the cross-sectional mean to ~0.
|
||||
daily_rets = data.pct_change()
|
||||
mkt_rets = daily_rets.mean(axis=1, skipna=True)
|
||||
daily_rets = data.pct_change(fill_method=None)
|
||||
mkt_rets = mask_scores(daily_rets, eligible).mean(axis=1, skipna=True)
|
||||
|
||||
# Step 3: Market drawdown dampener
|
||||
mkt_eq = (1 + mkt_rets.fillna(0.0)).cumprod()
|
||||
@@ -272,7 +276,7 @@ class RiskManagedEnsembleStrategy(Strategy):
|
||||
return raw.mul(final_scale, axis=0)
|
||||
|
||||
|
||||
class SharpeBoostedEnsembleStrategy(Strategy):
|
||||
class SharpeBoostedEnsembleStrategy(StockStrategy):
|
||||
"""
|
||||
Optimized ensemble targeting Sharpe >1.5 while maintaining high CAGR.
|
||||
|
||||
@@ -310,33 +314,35 @@ class SharpeBoostedEnsembleStrategy(Strategy):
|
||||
self.dd_floor = dd_floor
|
||||
self.dd_denom = dd_denom
|
||||
|
||||
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
|
||||
ret = p.pct_change()
|
||||
ret = p.pct_change(fill_method=None)
|
||||
|
||||
# === Signal A: rec_mfilt + deep_upvol ===
|
||||
rec_126 = p / p.rolling(126, min_periods=126).min() - 1
|
||||
mom_filter = p.shift(21).pct_change(105)
|
||||
mom_filter = p.shift(21).pct_change(105, fill_method=None)
|
||||
rec_mfilt = rec_126.where(mom_filter > 0, np.nan)
|
||||
rec_mfilt_r = _rank(rec_mfilt)
|
||||
rec_mfilt_r = _rank(rec_mfilt, eligible)
|
||||
|
||||
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)
|
||||
signal_a = 0.5 * rec_mfilt_r + 0.5 * deep_upvol_r
|
||||
|
||||
# === Signal B: Recovery 63d + 12-1 momentum ===
|
||||
rec_63 = p / p.rolling(63, min_periods=63).min() - 1
|
||||
mom_12_1 = p.shift(21).pct_change(231)
|
||||
rec_63_r = _rank(rec_63)
|
||||
mom_r = _rank(mom_12_1)
|
||||
mom_12_1 = p.shift(21).pct_change(231, fill_method=None)
|
||||
rec_63_r = _rank(rec_63, eligible)
|
||||
mom_r = _rank(mom_12_1, eligible)
|
||||
signal_b = 0.5 * rec_63_r + 0.5 * mom_r
|
||||
|
||||
# === Ensemble: equal-weight average of both signals ===
|
||||
ensemble = 0.5 * signal_a + 0.5 * signal_b
|
||||
|
||||
# === Select top_n ===
|
||||
rank = ensemble.rank(axis=1, ascending=False, na_option="bottom")
|
||||
ensemble = ensemble.where(data.notna())
|
||||
rank = mask_scores(ensemble, eligible).rank(axis=1, ascending=False, na_option="bottom")
|
||||
ensemble = mask_scores(ensemble, eligible)
|
||||
n_valid = ensemble.notna().sum(axis=1)
|
||||
enough = n_valid >= self.top_n
|
||||
top_mask = (rank <= self.top_n) & enough.values.reshape(-1, 1)
|
||||
@@ -361,7 +367,7 @@ class SharpeBoostedEnsembleStrategy(Strategy):
|
||||
# burning the account through fixed per-trade fees ($2 US / $5 CN).
|
||||
# Use cross-sectional mean of non-masked returns so PIT-masked
|
||||
# NaN→0 fills don't dilute the market signal.
|
||||
daily_rets = data.pct_change()
|
||||
daily_rets = data.pct_change(fill_method=None)
|
||||
port_rets = (signals * daily_rets).sum(axis=1, min_count=1).fillna(0.0)
|
||||
short_vol = port_rets.rolling(20, min_periods=10).std() * np.sqrt(252)
|
||||
vol_median = short_vol.rolling(252, min_periods=126).median()
|
||||
@@ -371,7 +377,7 @@ class SharpeBoostedEnsembleStrategy(Strategy):
|
||||
asym_scale_raw[high_vol_neg] = self.asym_vol_floor
|
||||
|
||||
# === Market-DD dampener (rebal-gated, NaN-aware market mean) ===
|
||||
mkt_rets = daily_rets.mean(axis=1, skipna=True)
|
||||
mkt_rets = mask_scores(daily_rets, eligible).mean(axis=1, skipna=True)
|
||||
mkt_eq = (1 + mkt_rets.fillna(0.0)).cumprod()
|
||||
mkt_dd = mkt_eq / mkt_eq.cummax() - 1
|
||||
dd_scale_raw = (1.0 + mkt_dd / self.dd_denom).clip(
|
||||
|
||||
@@ -18,7 +18,7 @@ Each can run at daily/weekly/biweekly/monthly rebalancing frequency.
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from strategies.base import Strategy
|
||||
from strategies.base import StockStrategy, mask_scores
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -26,11 +26,11 @@ from strategies.base import Strategy
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _mom_12_1(p):
|
||||
return p.shift(21).pct_change(231)
|
||||
return p.shift(21).pct_change(231, fill_method=None)
|
||||
|
||||
|
||||
def _mom_intermediate(p):
|
||||
return p.shift(21).pct_change(147)
|
||||
return p.shift(21).pct_change(147, fill_method=None)
|
||||
|
||||
|
||||
def _rec_63(p):
|
||||
@@ -46,29 +46,29 @@ def _above_ma200(p):
|
||||
|
||||
|
||||
def _up_volume_proxy(p):
|
||||
ret = p.pct_change()
|
||||
ret = p.pct_change(fill_method=None)
|
||||
return ret.where(ret > 0, 0).rolling(20, min_periods=15).sum()
|
||||
|
||||
|
||||
def _gap_up_freq(p):
|
||||
ret = p.pct_change()
|
||||
ret = p.pct_change(fill_method=None)
|
||||
return (ret > 0.01).astype(float).rolling(60, min_periods=40).mean()
|
||||
|
||||
|
||||
def _consistent_returns(p):
|
||||
ret = p.pct_change()
|
||||
ret = p.pct_change(fill_method=None)
|
||||
return (ret > 0).astype(float).rolling(252, min_periods=126).mean()
|
||||
|
||||
|
||||
def _rec_mom_filtered(p):
|
||||
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)
|
||||
return rec.where(mom > 0, np.nan)
|
||||
|
||||
|
||||
def _up_capture(p):
|
||||
ret = p.pct_change()
|
||||
mkt = ret.mean(axis=1)
|
||||
def _up_capture(p, eligible=None):
|
||||
ret = p.pct_change(fill_method=None)
|
||||
mkt = mask_scores(ret, eligible).mean(axis=1)
|
||||
up_mkt = mkt > 0
|
||||
arr = ret.values.copy()
|
||||
arr[~up_mkt.values, :] = np.nan
|
||||
@@ -79,9 +79,9 @@ def _up_capture(p):
|
||||
return stock_avg.div(mkt_avg, axis=0)
|
||||
|
||||
|
||||
def _down_resilience(p):
|
||||
ret = p.pct_change()
|
||||
mkt = ret.mean(axis=1)
|
||||
def _down_resilience(p, eligible=None):
|
||||
ret = p.pct_change(fill_method=None)
|
||||
mkt = mask_scores(ret, eligible).mean(axis=1)
|
||||
down_mkt = mkt < 0
|
||||
arr = ret.values.copy()
|
||||
arr[~down_mkt.values, :] = np.nan
|
||||
@@ -89,16 +89,16 @@ def _down_resilience(p):
|
||||
return -down_ret.rolling(120, min_periods=30).mean()
|
||||
|
||||
|
||||
def _quality_mom(p):
|
||||
mom_r = _mom_12_1(p).rank(axis=1, pct=True, na_option="keep")
|
||||
con_r = _consistent_returns(p).rank(axis=1, pct=True, na_option="keep")
|
||||
up_r = _up_volume_proxy(p).rank(axis=1, pct=True, na_option="keep")
|
||||
def _quality_mom(p, eligible=None):
|
||||
mom_r = _rank(_mom_12_1(p), eligible)
|
||||
con_r = _rank(_consistent_returns(p), eligible)
|
||||
up_r = _rank(_up_volume_proxy(p), eligible)
|
||||
return 0.4 * mom_r + 0.3 * con_r + 0.3 * up_r
|
||||
|
||||
|
||||
def _mom_x_gap(p):
|
||||
mom_r = _mom_12_1(p).rank(axis=1, pct=True, na_option="keep")
|
||||
gap_r = _gap_up_freq(p).rank(axis=1, pct=True, na_option="keep")
|
||||
def _mom_x_gap(p, eligible=None):
|
||||
mom_r = _rank(_mom_12_1(p), eligible)
|
||||
gap_r = _rank(_gap_up_freq(p), eligible)
|
||||
return mom_r * gap_r
|
||||
|
||||
|
||||
@@ -106,47 +106,47 @@ def _mom_x_gap(p):
|
||||
# Combo signal constructors (weighted rank sums)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
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")
|
||||
|
||||
|
||||
# US combos
|
||||
def signal_rec_mfilt_deep_upvol(p):
|
||||
rec_mfilt_r = _rank(_rec_mom_filtered(p))
|
||||
deep_upvol_r = _rank(_rec_126(p)) * _rank(_up_volume_proxy(p))
|
||||
deep_upvol_rr = _rank(deep_upvol_r)
|
||||
def signal_rec_mfilt_deep_upvol(p, eligible=None):
|
||||
rec_mfilt_r = _rank(_rec_mom_filtered(p), eligible)
|
||||
deep_upvol_r = _rank(_rec_126(p), eligible) * _rank(_up_volume_proxy(p), eligible)
|
||||
deep_upvol_rr = _rank(deep_upvol_r, eligible)
|
||||
return 0.5 * rec_mfilt_r + 0.5 * deep_upvol_rr
|
||||
|
||||
|
||||
def signal_ma200_mom7m_rec126(p):
|
||||
return (0.33 * _rank(_above_ma200(p))
|
||||
+ 0.33 * _rank(_mom_intermediate(p))
|
||||
+ 0.34 * _rank(_rec_126(p)))
|
||||
def signal_ma200_mom7m_rec126(p, eligible=None):
|
||||
return (0.33 * _rank(_above_ma200(p), eligible)
|
||||
+ 0.33 * _rank(_mom_intermediate(p), eligible)
|
||||
+ 0.34 * _rank(_rec_126(p), eligible))
|
||||
|
||||
|
||||
def signal_rec_mfilt_ma200(p):
|
||||
return 0.5 * _rank(_rec_mom_filtered(p)) + 0.5 * _rank(_above_ma200(p))
|
||||
def signal_rec_mfilt_ma200(p, eligible=None):
|
||||
return 0.5 * _rank(_rec_mom_filtered(p), eligible) + 0.5 * _rank(_above_ma200(p), eligible)
|
||||
|
||||
|
||||
def signal_mom7m_rec126(p):
|
||||
return 0.5 * _rank(_mom_intermediate(p)) + 0.5 * _rank(_rec_126(p))
|
||||
def signal_mom7m_rec126(p, eligible=None):
|
||||
return 0.5 * _rank(_mom_intermediate(p), eligible) + 0.5 * _rank(_rec_126(p), eligible)
|
||||
|
||||
|
||||
# CN combos
|
||||
def signal_up_cap_quality_mom(p):
|
||||
return 0.5 * _rank(_up_capture(p)) + 0.5 * _rank(_quality_mom(p))
|
||||
def signal_up_cap_quality_mom(p, eligible=None):
|
||||
return 0.5 * _rank(_up_capture(p, eligible), eligible) + 0.5 * _rank(_quality_mom(p, eligible), eligible)
|
||||
|
||||
|
||||
def signal_down_resil_qual_mom(p):
|
||||
return 0.5 * _rank(_down_resilience(p)) + 0.5 * _rank(_quality_mom(p))
|
||||
def signal_down_resil_qual_mom(p, eligible=None):
|
||||
return 0.5 * _rank(_down_resilience(p, eligible), eligible) + 0.5 * _rank(_quality_mom(p, eligible), eligible)
|
||||
|
||||
|
||||
def signal_rec63_mom_gap(p):
|
||||
return 0.5 * _rank(_rec_63(p)) + 0.5 * _rank(_mom_x_gap(p))
|
||||
def signal_rec63_mom_gap(p, eligible=None):
|
||||
return 0.5 * _rank(_rec_63(p), eligible) + 0.5 * _rank(_mom_x_gap(p, eligible), eligible)
|
||||
|
||||
|
||||
def signal_up_cap_mom_gap(p):
|
||||
return 0.5 * _rank(_up_capture(p)) + 0.5 * _rank(_mom_x_gap(p))
|
||||
def signal_up_cap_mom_gap(p, eligible=None):
|
||||
return 0.5 * _rank(_up_capture(p, eligible), eligible) + 0.5 * _rank(_mom_x_gap(p, eligible), eligible)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -171,7 +171,7 @@ SIGNAL_REGISTRY = {
|
||||
# Strategy class
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class FactorComboStrategy(Strategy):
|
||||
class FactorComboStrategy(StockStrategy):
|
||||
"""
|
||||
Generic factor-combination strategy with configurable rebalancing frequency.
|
||||
|
||||
@@ -192,11 +192,12 @@ class FactorComboStrategy(Strategy):
|
||||
self.rebal_freq = rebal_freq
|
||||
self.top_n = top_n
|
||||
|
||||
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
|
||||
sig = self.signal_func(data)
|
||||
def generate_signals(self, data: pd.DataFrame, eligible: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
sig = self.signal_func(data, eligible=eligible).where(data.notna())
|
||||
|
||||
# Select top_n by signal rank
|
||||
rank = sig.rank(axis=1, ascending=False, na_option="bottom")
|
||||
rank = mask_scores(sig, eligible).rank(axis=1, ascending=False, na_option="bottom")
|
||||
sig = mask_scores(sig, eligible)
|
||||
n_valid = sig.notna().sum(axis=1)
|
||||
enough = n_valid >= self.top_n
|
||||
top_mask = (rank <= self.top_n) & enough.values.reshape(-1, 1)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -11,10 +11,11 @@ Improvements over base MomentumQualityStrategy:
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from strategies.base import Strategy
|
||||
from strategies.base import StockStrategy, mask_scores
|
||||
from strategies.momentum_quality import rolling_max_drawdown
|
||||
|
||||
|
||||
class ImprovedMomentumQualityStrategy(Strategy):
|
||||
class ImprovedMomentumQualityStrategy(StockStrategy):
|
||||
"""
|
||||
Momentum + quality + recovery with monthly rebal and inv-vol weighting.
|
||||
"""
|
||||
@@ -37,45 +38,44 @@ class ImprovedMomentumQualityStrategy(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:
|
||||
# --- 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: return consistency (vectorized) ---
|
||||
# Fraction of positive 21-day returns over rolling window
|
||||
monthly_ret = data.pct_change(21)
|
||||
monthly_ret = data.pct_change(21, fill_method=None)
|
||||
positive_indicator = (monthly_ret > 0).astype(float)
|
||||
consistency = positive_indicator.rolling(
|
||||
self.quality_window, min_periods=self.quality_window // 2
|
||||
).mean()
|
||||
|
||||
# --- Quality: inverse max drawdown ---
|
||||
rolling_max = data.rolling(self.quality_window, min_periods=self.quality_window // 2).max()
|
||||
drawdown = data / rolling_max - 1
|
||||
worst_dd = drawdown.rolling(self.quality_window, min_periods=self.quality_window // 2).min()
|
||||
inv_dd = -worst_dd # higher = smaller drawdown = better
|
||||
quality_dd = rolling_max_drawdown(data, self.quality_window)
|
||||
|
||||
# --- Recovery factor ---
|
||||
recovery = data / data.rolling(self.recovery_window, min_periods=self.recovery_window).min() - 1
|
||||
|
||||
# --- Cross-sectional ranking ---
|
||||
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")
|
||||
rec_rank = recovery.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")
|
||||
rec_rank = mask_scores(recovery, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
|
||||
# Composite: momentum 35%, recovery 25%, consistency 20%, drawdown 20%
|
||||
scores = (0.35 * mom_rank + 0.25 * rec_rank +
|
||||
0.20 * con_rank + 0.20 * 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)
|
||||
|
||||
# --- Inverse-vol weighting ---
|
||||
returns = data.pct_change()
|
||||
returns = data.pct_change(fill_method=None)
|
||||
vol = returns.rolling(self.vol_window, min_periods=30).std().replace(0, np.nan)
|
||||
inv_vol = (1.0 / vol).where(top_mask, 0.0)
|
||||
row_sums = inv_vol.sum(axis=1).replace(0, np.nan)
|
||||
|
||||
@@ -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 InverseVolatilityStrategy(Strategy):
|
||||
class InverseVolatilityStrategy(StockStrategy):
|
||||
"""
|
||||
Risk parity via inverse-volatility weighting.
|
||||
|
||||
@@ -17,13 +17,13 @@ class InverseVolatilityStrategy(Strategy):
|
||||
def __init__(self, vol_window: int = 20):
|
||||
self.vol_window = vol_window
|
||||
|
||||
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
|
||||
returns = data.pct_change()
|
||||
def generate_signals(self, data: pd.DataFrame, eligible: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
returns = data.pct_change(fill_method=None)
|
||||
vol = returns.rolling(self.vol_window).std()
|
||||
|
||||
# Replace zero vol with NaN to avoid division by zero
|
||||
vol = vol.replace(0, np.nan)
|
||||
inv_vol = 1.0 / vol
|
||||
inv_vol = mask_scores((1.0 / vol).where(data.notna()), eligible)
|
||||
|
||||
row_sums = inv_vol.sum(axis=1).replace(0, np.nan)
|
||||
signals = inv_vol.div(row_sums, axis=0).fillna(0.0)
|
||||
|
||||
@@ -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 MeanReversionStrategy(Strategy):
|
||||
class MeanReversionStrategy(StockStrategy):
|
||||
"""
|
||||
Monthly "buy the dip" with momentum confirmation.
|
||||
|
||||
@@ -20,17 +20,18 @@ class MeanReversionStrategy(Strategy):
|
||||
self.rebal_freq = rebal_freq
|
||||
self.top_n = top_n
|
||||
|
||||
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
|
||||
long_mom = data.pct_change(self.mom_lookback)
|
||||
def generate_signals(self, data: pd.DataFrame, eligible: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
long_mom = data.pct_change(self.mom_lookback, fill_method=None)
|
||||
has_momentum = long_mom > 0
|
||||
|
||||
short_ret = data.pct_change(self.dip_window)
|
||||
short_ret = data.pct_change(self.dip_window, fill_method=None)
|
||||
|
||||
# Among positive-momentum stocks, rank by biggest dip
|
||||
scores = short_ret.where(has_momentum, np.nan)
|
||||
|
||||
# Rank: most negative = rank 1 (biggest dip)
|
||||
rank = scores.rank(axis=1, ascending=True, na_option="bottom")
|
||||
rank = mask_scores(scores, eligible).rank(axis=1, ascending=True, na_option="bottom")
|
||||
scores = mask_scores(scores, eligible)
|
||||
n_valid = scores.notna().sum(axis=1)
|
||||
effective_n = n_valid.clip(upper=self.top_n)
|
||||
|
||||
|
||||
@@ -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 MomentumStrategy(Strategy):
|
||||
class MomentumStrategy(StockStrategy):
|
||||
"""
|
||||
Classic cross-sectional momentum strategy (Jegadeesh & Titman, 1993).
|
||||
|
||||
@@ -19,14 +19,16 @@ class MomentumStrategy(Strategy):
|
||||
self.skip = skip # ~1 month — skip to avoid reversal
|
||||
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: return from T-(lookback) to T-skip
|
||||
momentum = data.shift(self.skip).pct_change(self.lookback - self.skip)
|
||||
momentum = data.shift(self.skip).pct_change(self.lookback - self.skip, fill_method=None)
|
||||
|
||||
momentum = momentum.where(data.notna())
|
||||
momentum = mask_scores(momentum, eligible)
|
||||
n_valid = momentum.notna().sum(axis=1)
|
||||
enough_data = n_valid >= self.top_n
|
||||
|
||||
score_rank = momentum.rank(axis=1, ascending=False, na_option="bottom")
|
||||
score_rank = mask_scores(momentum, eligible).rank(axis=1, ascending=False, na_option="bottom")
|
||||
top_mask = (score_rank <= self.top_n) & enough_data.values.reshape(-1, 1)
|
||||
|
||||
raw = top_mask.astype(float)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 MultiFactorStrategy(Strategy):
|
||||
class MultiFactorStrategy(StockStrategy):
|
||||
"""
|
||||
Multi-factor strategy combining momentum and value signals with a market-timing filter.
|
||||
|
||||
@@ -33,7 +33,7 @@ class MultiFactorStrategy(Strategy):
|
||||
self.value_period = value_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:
|
||||
stock = data[self.tickers]
|
||||
|
||||
# --- Market timing filter ---
|
||||
@@ -42,7 +42,7 @@ class MultiFactorStrategy(Strategy):
|
||||
|
||||
# --- Momentum factor ---
|
||||
# Return from T-(momentum_period+skip) to T-skip, avoiding the last month
|
||||
momentum = stock.shift(self.momentum_skip).pct_change(self.momentum_period)
|
||||
momentum = stock.shift(self.momentum_skip).pct_change(self.momentum_period, fill_method=None)
|
||||
|
||||
# --- Value factor ---
|
||||
# min_price_over_period / current_price (higher = more "undervalued" vs recent range)
|
||||
@@ -51,16 +51,17 @@ class MultiFactorStrategy(Strategy):
|
||||
# --- Cross-sectional ranking (each row ranked across assets) ---
|
||||
# na_option="keep" so NaN stocks (pre-IPO / delisted / masked) stay
|
||||
# NaN in the composite score instead of being assigned pct=1.0.
|
||||
mom_rank = momentum.rank(axis=1, pct=True, na_option="keep")
|
||||
val_rank = value.rank(axis=1, pct=True, na_option="keep")
|
||||
mom_rank = mask_scores(momentum, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
val_rank = mask_scores(value, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
scores = mom_rank + val_rank # combined score, higher = better
|
||||
|
||||
# --- Select top_n assets per row ---
|
||||
# Only allocate rows that have enough valid scores
|
||||
scores = mask_scores(scores, eligible)
|
||||
n_valid = scores.notna().sum(axis=1)
|
||||
enough_data = 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_data.values.reshape(-1, 1)
|
||||
|
||||
# Equal-weight allocation among selected assets
|
||||
|
||||
@@ -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 RecoveryMomentumStrategy(Strategy):
|
||||
class RecoveryMomentumStrategy(StockStrategy):
|
||||
"""
|
||||
Recovery + momentum composite factor strategy.
|
||||
|
||||
@@ -29,26 +29,27 @@ class RecoveryMomentumStrategy(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:
|
||||
# Factor 1: Recovery — price / rolling min
|
||||
recovery = data / data.rolling(self.recovery_window).min() - 1
|
||||
|
||||
# Factor 2: 12-1 month momentum
|
||||
momentum = data.shift(self.mom_skip).pct_change(self.mom_lookback - self.mom_skip)
|
||||
momentum = data.shift(self.mom_skip).pct_change(self.mom_lookback - self.mom_skip, fill_method=None)
|
||||
|
||||
# Cross-sectional percentile ranks. na_option="keep" is critical:
|
||||
# with "bottom" + ascending=True default, NaN stocks get pct=1.0, so
|
||||
# non-member / delisted / pre-IPO names leak into the composite as
|
||||
# "top" candidates. "keep" propagates NaN and the final ascending=False
|
||||
# + "bottom" rank pushes them to the end where they are not selected.
|
||||
rec_rank = recovery.rank(axis=1, pct=True, na_option="keep")
|
||||
mom_rank = momentum.rank(axis=1, pct=True, na_option="keep")
|
||||
rec_rank = mask_scores(recovery, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
mom_rank = mask_scores(momentum, eligible).rank(axis=1, pct=True, na_option="keep")
|
||||
|
||||
# Composite score (50/50)
|
||||
composite = 0.5 * rec_rank + 0.5 * mom_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)
|
||||
|
||||
@@ -27,7 +27,7 @@ import numpy as np
|
||||
import pandas as pd
|
||||
from numpy.lib.stride_tricks import sliding_window_view
|
||||
|
||||
from strategies.base import BarStrategy
|
||||
from strategies.base import BarStrategy, mask_scores
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -60,10 +60,10 @@ def sharpe_momentum(close: pd.DataFrame) -> pd.DataFrame:
|
||||
return momentum_12_1(close) / _returns(close).rolling(252, min_periods=180).std()
|
||||
|
||||
|
||||
def low_beta(close: pd.DataFrame, window: int = 252) -> pd.DataFrame:
|
||||
def low_beta(close: pd.DataFrame, window: int = 252, eligible=None) -> pd.DataFrame:
|
||||
"""Negative rolling beta to the equal-weight average of the panel."""
|
||||
r = _returns(close)
|
||||
m = r.mean(axis=1).fillna(0.0)
|
||||
m = mask_scores(r, eligible).mean(axis=1).fillna(0.0)
|
||||
minp = window * 180 // 252
|
||||
e_xy = r.mul(m, axis=0).rolling(window, min_periods=minp).mean()
|
||||
e_x = r.rolling(window, min_periods=minp).mean()
|
||||
@@ -73,12 +73,12 @@ def low_beta(close: pd.DataFrame, window: int = 252) -> pd.DataFrame:
|
||||
|
||||
|
||||
def idiosyncratic_vol(close: pd.DataFrame, beta_window: int = 252,
|
||||
vol_window: int = 63) -> pd.DataFrame:
|
||||
vol_window: int = 63, eligible=None) -> pd.DataFrame:
|
||||
"""Negative 63-day volatility of returns net of the equal-weight market
|
||||
times a trailing (lagged) 252-day beta; Ang, Hodrick, Xing & Zhang (2006)."""
|
||||
r = _returns(close)
|
||||
m = r.mean(axis=1).fillna(0.0)
|
||||
beta = -low_beta(close, beta_window).shift(1)
|
||||
m = mask_scores(r, eligible).mean(axis=1).fillna(0.0)
|
||||
beta = -low_beta(close, beta_window, eligible).shift(1)
|
||||
resid = r - beta.mul(m, axis=0)
|
||||
return -resid.rolling(vol_window, min_periods=40).std()
|
||||
|
||||
@@ -111,28 +111,29 @@ def _rank(df: pd.DataFrame) -> pd.DataFrame:
|
||||
return df.rank(axis=1, pct=True)
|
||||
|
||||
|
||||
def _composite(*factors: pd.DataFrame) -> pd.DataFrame:
|
||||
return sum(_rank(f) for f in factors) / len(factors)
|
||||
def _composite(*factors: pd.DataFrame, eligible=None) -> pd.DataFrame:
|
||||
return sum(_rank(mask_scores(f, eligible)) for f in factors) / len(factors)
|
||||
|
||||
|
||||
def signal_overnight_recovery(bars):
|
||||
return _composite(overnight_momentum(bars["open"], bars["close"]), recovery(bars["close"]))
|
||||
return _composite(overnight_momentum(bars["open"], bars["close"]), recovery(bars["close"]), eligible=bars.get("eligible"))
|
||||
|
||||
|
||||
def signal_lowrisk_momentum(bars):
|
||||
c = bars["close"]
|
||||
return _composite(amplitude_cut_momentum(bars["high"], bars["low"], c), low_beta(c),
|
||||
price_volume_corr(c, bars["volume"]), sharpe_momentum(c))
|
||||
return _composite(amplitude_cut_momentum(bars["high"], bars["low"], c), low_beta(c, eligible=bars.get("eligible")),
|
||||
price_volume_corr(c, bars["volume"]), sharpe_momentum(c), eligible=bars.get("eligible"))
|
||||
|
||||
|
||||
def signal_lowbeta_sharpe_mom(bars):
|
||||
c = bars["close"]
|
||||
return _composite(low_beta(c), sharpe_momentum(c))
|
||||
return _composite(low_beta(c, eligible=bars.get("eligible")), sharpe_momentum(c), eligible=bars.get("eligible"))
|
||||
|
||||
|
||||
def signal_low_risk(bars):
|
||||
c = bars["close"]
|
||||
return _composite(idiosyncratic_vol(c), low_beta(c))
|
||||
return _composite(idiosyncratic_vol(c, eligible=bars.get("eligible")),
|
||||
low_beta(c, eligible=bars.get("eligible")), eligible=bars.get("eligible"))
|
||||
|
||||
|
||||
# name -> (bar fields, score function)
|
||||
@@ -202,6 +203,8 @@ class RobustMomentumStrategy(BarStrategy):
|
||||
def generate_weights(self, bars: dict[str, pd.DataFrame]) -> pd.DataFrame:
|
||||
close = bars["close"]
|
||||
panel = {f: bars[f].reindex(index=close.index, columns=close.columns) for f in self.fields}
|
||||
if "eligible" in bars:
|
||||
panel["eligible"] = bars["eligible"]
|
||||
score = self._score(panel)
|
||||
# names without a price are not eligible; a backtest also passes
|
||||
# "eligible" (point-in-time index membership) so signals can use a
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -46,6 +46,8 @@ from strategies.factor_combo import SIGNAL_REGISTRY
|
||||
class TrendRiderV6(TrendRiderV5):
|
||||
"""Stock-sleeve TrendRider with V5 regime engine."""
|
||||
|
||||
accepts_eligibility = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*args,
|
||||
@@ -98,10 +100,10 @@ class TrendRiderV6(TrendRiderV5):
|
||||
self.leverage_overlay_symbol, *self.risk_off_basket})
|
||||
return [c for c in prices.columns if c not in non_stock]
|
||||
|
||||
def _stock_top_n_weights(self, prices: pd.DataFrame, universe: list[str]) -> pd.DataFrame:
|
||||
def _stock_top_n_weights(self, prices: pd.DataFrame, universe: list[str], eligible=None) -> pd.DataFrame:
|
||||
"""Top-N selection by signal, inv-vol weighted within selection."""
|
||||
stock_panel = prices[universe]
|
||||
sig = self.signal_func(stock_panel)
|
||||
sig = self.signal_func(stock_panel, eligible=eligible)
|
||||
# Top-N by signal rank (highest score = top)
|
||||
rank = sig.rank(axis=1, ascending=False, na_option="bottom")
|
||||
n_valid = sig.notna().sum(axis=1)
|
||||
@@ -154,7 +156,7 @@ class TrendRiderV6(TrendRiderV5):
|
||||
return {best: 1.0}
|
||||
|
||||
# ---- Override generate_signals ----
|
||||
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
|
||||
def generate_signals(self, data: pd.DataFrame, eligible=None) -> pd.DataFrame:
|
||||
if self.signal not in data.columns:
|
||||
raise ValueError(f"Required regime signal {self.signal!r} not in data.")
|
||||
universe = self._resolve_universe(data)
|
||||
@@ -163,7 +165,7 @@ class TrendRiderV6(TrendRiderV5):
|
||||
|
||||
# 1) Build sleeve weights — stock sleeve, anchor sleeve
|
||||
# (defensive sleeve is single-pick, computed per-bar inside the loop)
|
||||
stock_w = self._stock_top_n_weights(data, universe)
|
||||
stock_w = self._stock_top_n_weights(data, universe, eligible)
|
||||
anchor_w = pd.DataFrame(0.0, index=data.index, columns=[self.moderate_anchor])
|
||||
if self.moderate_anchor in data.columns:
|
||||
anchor_w[self.moderate_anchor] = 1.0
|
||||
|
||||
@@ -18,21 +18,15 @@ Three sequential layers, each PIT-safe:
|
||||
Restore when gain drops below 20% (hysteresis band = 10%).
|
||||
Entry price = yesterday's close at symbol change (PIT-safe).
|
||||
|
||||
Why profit-take works on leveraged ETFs
|
||||
---------------------------------------
|
||||
3x ETFs (TQQQ, UPRO) suffer from volatility drag: daily rebalancing
|
||||
erodes multi-day compound returns proportional to variance. After a
|
||||
+30% gain, the position sits on a large base where subsequent
|
||||
volatility causes disproportionate drag. Clearing the position:
|
||||
|
||||
1. Locks in geometric gains before vol drag erodes them.
|
||||
2. Reduces the base on which the drag operates.
|
||||
3. Forces rebalancing from an asset that has become "overweight."
|
||||
|
||||
This is not alpha from prediction — it is alpha from mechanical
|
||||
rebalancing of a negatively-convex instrument, a structural effect
|
||||
documented in the leveraged ETF literature.
|
||||
Research boundary
|
||||
-----------------
|
||||
Profit-taking is an empirical timing rule. Daily leverage compounding alone
|
||||
neither proves that the 30% threshold earns alpha nor makes it independent
|
||||
of the development window. Compare against no profit-taking and a simple
|
||||
trend rule using the shared cash ledger and out-of-period stress scenarios.
|
||||
|
||||
The following legacy figures used the earlier execution model and are not
|
||||
comparable to cash-ledger-pit-v2 results:
|
||||
Empirical 10y (2016-05-16 to 2026-05-13, 10bps one-way cost):
|
||||
Ann 54.7%, Vol 24.2%, Sharpe(rf=5%) 1.72, MaxDD -25.7%,
|
||||
Sortino 2.23, Calmar 2.13.
|
||||
|
||||
Reference in New Issue
Block a user