Files
quant-trading/strategies/dual_momentum.py
Gahow Wang 722cade974 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.
2026-10-01 02:24:01 -07:00

58 lines
2.5 KiB
Python

import numpy as np
import pandas as pd
from strategies.base import StockStrategy, mask_scores
class DualMomentumStrategy(StockStrategy):
"""
Dual momentum with multi-timeframe confirmation.
Unlike plain momentum (single 12-1m lookback), this requires agreement
across THREE timeframes — short (1-3m), medium (3-6m), and long (6-12m).
A stock must show positive returns on ALL three to qualify.
This filters out stocks riding a single spike and favors sustained trends.
Position count is variable: when few stocks pass all three filters,
the strategy naturally goes to partial cash.
"""
def __init__(self, top_n: int = 20):
self.top_n = top_n
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, 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 = 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 = 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
raw = top_mask.astype(float)
row_sums = raw.sum(axis=1).replace(0, np.nan)
signals = raw.div(row_sums, axis=0).fillna(0.0)
signals.iloc[:252] = 0.0
return signals.shift(1).fillna(0.0)