"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(factors): add 4 canonical academic alphas (#277)
卫斯李33527a7f7716
diff --git a/agent/src/factors/zoo/academic/high52w.py b/agent/src/factors/zoo/academic/high52w.pynew file mode 100644index 000000000..043a4024a--- /dev/null+++ b/agent/src/factors/zoo/academic/high52w.py@@ -0,0 +1,59 @@++# ============================================================+# 中文名称: 52周高点因子 (HIGH52W)+# 简要说明: 当前价格越接近过去52周(252日)最高价,未来收益越高。George & Hwang(2004)的52周高点动量。+# 典型用途: 捕获基于52周高点锚定的动量效应,用于动量投资策略。+# ============================================================+"""academic 52-week-high momentum: closeness of price to its 252-day high.++Reference:+ George, T. J., & Hwang, C.-Y. (2004). "The 52-Week High and Momentum+ Investing." The Journal of Finance, 59(5), 2145-2176.++Stocks trading near their 52-week high tend to earn higher future returns —+the ratio of current price to the trailing 252-day high predicts momentum+better than past returns alone. Computed as close / ts_max(close, 252), then+cross-sectional z-scored per date. Higher z-scores = closer to the 52-week+high (the long leg).+"""+from __future__ import annotations++import numpy as np+import pandas as pd++from src.factors.base import safe_div, ts_max++__alpha_meta__ = {+ 'id': 'academic_high52w',+ 'nickname': 'George-Hwang 2004 52-week-high momentum',+ 'theme': ['momentum'],+ 'formula_latex': r'\mathrm{zscore}_{x}\bigl(\mathrm{close}_t / \mathrm{ts\_max}(\mathrm{close},\,252)\bigr)',+ 'columns_required': ['close'],+ 'universe': ['equity_us', 'equity_cn', 'equity_hk'],+ 'frequency': ['1d'],+ 'decay_horizon': 60,+ 'min_warmup_bars': 252,+ 'notes': (+ 'George & Hwang (2004) 52-week-high momentum. Ratio of current close to the '+ 'trailing 252-day maximum close, cross-sectional z-score per date for '+ 'long-short ranking. Top z-scores = names trading nearest their 52-week high. '+ 'Canonical 252d window; declared decay_horizon=60 due to registry schema cap '+ '(le=60); real signal horizon spans months.'+ ),+}+++def _cross_sectional_zscore(df: pd.DataFrame) -> pd.DataFrame:+ """Per-row z-score: (x - row_mean) / row_std; zero/NaN std rows -> NaN."""+ mean = df.mean(axis=1, skipna=True)+ std = df.std(axis=1, ddof=1, skipna=True)+ centered = df.sub(mean, axis=0)+ result = centered.div(std.where(std > 0), axis=0)+ return result.replace([np.inf, -np.inf], np.nan)+++def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:+ """Return close-to-252d-high ratio cross-sectional z-score per stock."""+ close = panel['close']+ ratio = safe_div(close, ts_max(close, 252))+ return _cross_sectional_zscore(ratio)diff --git a/agent/src/factors/zoo/academic/illiq.py b/agent/src/factors/zoo/academic/illiq.pynew file mode 100644index 000000000..46463e868--- /dev/null+++ b/agent/src/factors/zoo/academic/illiq.py@@ -0,0 +1,62 @@++# ============================================================+# 中文名称: Amihud非流动性因子 (ILLIQ)+# 简要说明: 单位成交额带来的价格冲击越大,流动性越差,预期收益越高(流动性溢价)。Amihud(2002)。+# 典型用途: 捕获非流动性溢价,做多流动性差的股票,用于流动性风格分析。+# ============================================================+"""academic Amihud illiquidity: average absolute return per dollar of volume.++Reference:+ Amihud, Y. (2002). "Illiquidity and stock returns: cross-section and+ time-series effects." Journal of Financial Markets, 5(1), 31-56.++The Amihud (2002) ILLIQ measure: the daily ratio of absolute return to dollar+volume, averaged over a trailing window, captures the price impact of trading.+Illiquid stocks (high ILLIQ) command a return premium. Computed over a 21-day+window then cross-sectional z-scored per date. Higher z-scores = less liquid+names (the long leg of the illiquidity premium).+"""+from __future__ import annotations++import numpy as np+import pandas as pd++from src.factors.base import safe_div, ts_mean++__alpha_meta__ = {+ 'id': 'academic_illiq',+ 'nickname': 'Amihud 2002 illiquidity — |return| per dollar volume',+ 'theme': ['liquidity'],+ 'formula_latex': r'\mathrm{zscore}_{x}\bigl(\mathrm{ts\_mean}(|r_t| / (\mathrm{close}_t \cdot \mathrm{volume}_t),\,21)\bigr)',+ 'columns_required': ['close', 'volume'],+ 'universe': ['equity_us', 'equity_cn', 'equity_hk'],+ 'frequency': ['1d'],+ 'decay_horizon': 21,+ 'min_warmup_bars': 22,+ 'notes': (+ 'Amihud (2002) ILLIQ. Daily |simple return| divided by dollar volume '+ '(close * volume), averaged over a trailing 21-day window, then '+ 'cross-sectional z-score per date for long-short ranking. Top z-scores = '+ 'least liquid names, which carry the illiquidity premium. Uses a 1-day '+ 'return (one extra warmup bar over the 21-day average window).'+ ),+}+++def _cross_sectional_zscore(df: pd.DataFrame) -> pd.DataFrame:+ """Per-row z-score: (x - row_mean) / row_std; zero/NaN std rows -> NaN."""+ mean = df.mean(axis=1, skipna=True)+ std = df.std(axis=1, ddof=1, skipna=True)+ centered = df.sub(mean, axis=0)+ result = centered.div(std.where(std > 0), axis=0)+ return result.replace([np.inf, -np.inf], np.nan)+++def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:+ """Return 21-day Amihud illiquidity cross-sectional z-score per stock."""+ close = panel['close']+ volume = panel['volume']+ daily_ret = safe_div(close - close.shift(1), close.shift(1))+ dollar_volume = close * volume+ illiq = safe_div(daily_ret.abs(), dollar_volume)+ return _cross_sectional_zscore(ts_mean(illiq, 21))diff --git a/agent/src/factors/zoo/academic/retskew.py b/agent/src/factors/zoo/academic/retskew.pynew file mode 100644index 000000000..cb8a25b47--- /dev/null+++ b/agent/src/factors/zoo/academic/retskew.py@@ -0,0 +1,60 @@++# ============================================================+# 中文名称: 收益偏度因子 (RETSKEW)+# 简要说明: 过去一段时间日收益分布偏度越低(越负偏),预期收益越高。Harvey & Siddique(2000)的偏度溢价。+# 典型用途: 捕获特质偏度溢价,做多负偏(类彩票反向)的股票,用于偏度风格分析。+# ============================================================+"""academic return skewness: inverse trailing skewness of daily returns.++Reference:+ Harvey, C. R., & Siddique, A. (2000). "Conditional Skewness in Asset+ Pricing Tests." The Journal of Finance, 55(3), 1263-1295.++Investors pay a premium for positively-skewed (lottery-like) payoffs, so+positively-skewed stocks earn lower subsequent returns and negatively-skewed+stocks earn higher ones. Computed as the negative of the trailing 60-day+skewness of daily returns, then cross-sectional z-scored per date. Higher+z-scores = more negatively-skewed names (the long leg of the skewness premium).+"""+from __future__ import annotations++import numpy as np+import pandas as pd++from src.factors.base import safe_div++__alpha_meta__ = {+ 'id': 'academic_retskew',+ 'nickname': 'Harvey-Siddique 2000 return skewness — inverse 60d skew',+ 'theme': ['volatility'],+ 'formula_latex': r'\mathrm{zscore}_{x}\bigl(-\mathrm{skew}_{60}(r_t)\bigr)',+ 'columns_required': ['close'],+ 'universe': ['equity_us', 'equity_cn', 'equity_hk'],+ 'frequency': ['1d'],+ 'decay_horizon': 60,+ 'min_warmup_bars': 61,+ 'notes': (+ 'Harvey & Siddique (2000) skewness premium. Negative of the trailing '+ '60-day sample skewness of daily simple returns, cross-sectional z-score '+ 'per date for long-short ranking. Top z-scores = most negatively-skewed '+ 'names, which command a return premium over lottery-like positively-skewed '+ 'names. Uses a 1-day return (one extra warmup bar over the 60-day window).'+ ),+}+++def _cross_sectional_zscore(df: pd.DataFrame) -> pd.DataFrame:+ """Per-row z-score: (x - row_mean) / row_std; zero/NaN std rows -> NaN."""+ mean = df.mean(axis=1, skipna=True)+ std = df.std(axis=1, ddof=1, skipna=True)+ centered = df.sub(mean, axis=0)+ result = centered.div(std.where(std > 0), axis=0)+ return result.replace([np.inf, -np.inf], np.nan)+++def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:+ """Return inverse 60-day return-skewness cross-sectional z-score per stock."""+ close = panel['close']+ daily_ret = safe_div(close - close.shift(1), close.shift(1))+ skew = daily_ret.rolling(window=60, min_periods=60).skew()+ return _cross_sectional_zscore(-skew)diff --git a/agent/src/factors/zoo/academic/strev.py b/agent/src/factors/zoo/academic/strev.pynew file mode 100644index 000000000..1ed6cccde--- /dev/null+++ b/agent/src/factors/zoo/academic/strev.py@@ -0,0 +1,58 @@++# ============================================================+# 中文名称: 短期反转因子 (STREV)+# 简要说明: 做多过去一个月输家、做空过去一个月赢家的收益。短期(月度)价格存在反转效应。+# 典型用途: 捕获一个月尺度的均值回复,用于短期反转策略。+# ============================================================+"""academic short-term reversal: inverse trailing 21-day return.++Reference:+ Jegadeesh, N. (1990). "Evidence of predictable behavior of security+ returns." The Journal of Finance, 45(3), 881-898.++The canonical one-month reversal factor: stocks with low past-month returns+tend to outperform stocks with high past-month returns over the following+month. Computed directly from prices as the negative of the trailing 21-day+return, then cross-sectional z-scored per date. Higher z-scores = larger+recent losers (the long leg).+"""+from __future__ import annotations++import numpy as np+import pandas as pd++from src.factors.base import delta, safe_div++__alpha_meta__ = {+ 'id': 'academic_strev',+ 'nickname': 'Jegadeesh 1990 short-term reversal — inverse 21d return',+ 'theme': ['reversal'],+ 'formula_latex': r'\mathrm{zscore}_{x}\bigl(-(\mathrm{close}_t - \mathrm{close}_{t-21}) / \mathrm{close}_{t-21}\bigr)',+ 'columns_required': ['close'],+ 'universe': ['equity_us', 'equity_cn', 'equity_hk'],+ 'frequency': ['1d'],+ 'decay_horizon': 21,+ 'min_warmup_bars': 21,+ 'notes': (+ 'Jegadeesh (1990) one-month reversal. Negative trailing 21-day return, '+ 'cross-sectional z-score per date for long-short ranking. Top z-scores = '+ 'recent one-month losers, which tend to rebound. Constructed directly from '+ 'prices, matching the original definition modulo the z-score wrapper.'+ ),+}+++def _cross_sectional_zscore(df: pd.DataFrame) -> pd.DataFrame:+ """Per-row z-score: (x - row_mean) / row_std; zero/NaN std rows -> NaN."""+ mean = df.mean(axis=1, skipna=True)+ std = df.std(axis=1, ddof=1, skipna=True)+ centered = df.sub(mean, axis=0)+ result = centered.div(std.where(std > 0), axis=0)+ return result.replace([np.inf, -np.inf], np.nan)+++def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:+ """Return inverse 21-day return cross-sectional z-score per stock."""+ close = panel['close']+ ret = safe_div(delta(close, 21), close.shift(21))+ return _cross_sectional_zscore(-ret)