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.
74 lines
3.2 KiB
Python
74 lines
3.2 KiB
Python
import numpy as np
|
|
import pandas as pd
|
|
from strategies.base import StockStrategy, mask_scores
|
|
|
|
|
|
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.
|
|
|
|
Quality proxy (from price data):
|
|
- Return consistency: fraction of positive monthly returns over past year
|
|
(stocks that grind up steadily are higher "quality" than volatile jumpers)
|
|
- Low max drawdown: smaller peak-to-trough drop = more stable
|
|
|
|
Combined with momentum, this favors stocks with strong AND stable uptrends,
|
|
filtering out lottery-ticket stocks that spike then crash.
|
|
"""
|
|
|
|
def __init__(self, momentum_period: int = 252, skip: int = 21,
|
|
quality_window: int = 252, top_n: int = 20):
|
|
self.momentum_period = momentum_period
|
|
self.skip = skip
|
|
self.quality_window = quality_window
|
|
self.top_n = top_n
|
|
|
|
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, 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, 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
|
|
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 = 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 = 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)
|
|
row_sums = raw.sum(axis=1).replace(0, np.nan)
|
|
signals = raw.div(row_sums, axis=0).fillna(0.0)
|
|
|
|
warmup = max(self.momentum_period, self.quality_window) + 21
|
|
signals.iloc[:warmup] = 0.0
|
|
|
|
return signals.shift(1).fillna(0.0)
|