Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(factors): use OLS for Qlib BETA and RESI (#2062)

Yufeng Hef92c723564a9
diff --git a/agent/src/factors/base.py b/agent/src/factors/base.py
index 0ac7709a2..ebfcde567 100644
--- a/agent/src/factors/base.py
+++ b/agent/src/factors/base.py
@@ -276,6 +276,31 @@ def ts_std(df: pd.DataFrame, n: int) -> pd.DataFrame:
return df.rolling(window=n, min_periods=n).std(ddof=1)
+def ts_slope(df: pd.DataFrame, n: int) -> pd.DataFrame:
+ """Rolling OLS slope against ``0, ..., n - 1``, requiring a full window."""
+ if n < 2:
+ raise ValueError(f"ts_slope window must be >= 2, got {n}")
+ arr = _as_float(df).to_numpy(dtype=np.float64, na_value=np.nan)
+ T, C = arr.shape
+ result = np.full((T, C), np.nan)
+ if T < n:
+ return pd.DataFrame(result, index=df.index, columns=df.columns)
+
+ x = np.arange(n, dtype=np.float64)
+ x -= x.mean()
+ windows = sliding_window_view(arr, window_shape=n, axis=0)
+ slopes = np.einsum("ijk,k->ij", windows, x) / np.dot(x, x)
+ result[n - 1 :] = slopes
+ return pd.DataFrame(result, index=df.index, columns=df.columns)
+
+
+def ts_resi(df: pd.DataFrame, n: int) -> pd.DataFrame:
+ """Latest observation's residual from the same trailing OLS fit."""
+ slope = ts_slope(df, n)
+ fitted_at_last = ts_mean(df, n) + slope * ((n - 1) / 2.0)
+ return df - fitted_at_last
+
+
def ts_max(df: pd.DataFrame, n: int) -> pd.DataFrame:
"""Rolling max per column, warmup → NaN."""
if n < 1:
diff --git a/agent/src/factors/zoo/qlib158/beta10.py b/agent/src/factors/zoo/qlib158/beta10.py
index eee7817b0..5ca40ea6b 100644
--- a/agent/src/factors/zoo/qlib158/beta10.py
+++ b/agent/src/factors/zoo/qlib158/beta10.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: Beta系数 10日
-# 简要说明: ts_cov(close, ts_mean(close, 10), 10) / ts_var(close, 10),个股相对于自身的10日Beta。
-# 典型用途: 衡量个股在10日窗口内的弹性/风险,高Beta意味着高波动和高弹性。
+# 简要说明: Slope(close, 10) / close,收盘价对时间的10日线性回归斜率,按最新收盘价归一化。
+# 典型用途: 衡量10日价格趋势的速度和方向,正值表示上涨趋势。
# ============================================================
-"""qlib158 BETA10: formula = (\\mathrm{close}_t - \\mathrm{close}_{{t-10}}) / (10\\,\\mathrm{close})."""
+"""qlib158 BETA10: formula = \\mathrm{Slope}(\\mathrm{close}, 10) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, delta
+from src.factors.base import safe_div, ts_slope
__alpha_meta__ = {
'id': 'qlib158_beta10',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close}_t - \\\\mathrm{close}_{{t-10}}) / (10\\\\,\\\\mathrm{close})',
+ 'formula_latex': '\\\\mathrm{Slope}(\\\\mathrm{close}, 10) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 BETA10 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(delta(c, 10), c) / float(10)
+ return safe_div(ts_slope(c, 10), c)
diff --git a/agent/src/factors/zoo/qlib158/beta20.py b/agent/src/factors/zoo/qlib158/beta20.py
index ccdcbc476..d73454d54 100644
--- a/agent/src/factors/zoo/qlib158/beta20.py
+++ b/agent/src/factors/zoo/qlib158/beta20.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: Beta系数 20日
-# 简要说明: ts_cov(close, ts_mean(close, 20), 20) / ts_var(close, 20),个股相对于自身的20日Beta。
-# 典型用途: 衡量个股在20日窗口内的弹性/风险,高Beta意味着高波动和高弹性。
+# 简要说明: Slope(close, 20) / close,收盘价对时间的20日线性回归斜率,按最新收盘价归一化。
+# 典型用途: 衡量20日价格趋势的速度和方向,正值表示上涨趋势。
# ============================================================
-"""qlib158 BETA20: formula = (\\mathrm{close}_t - \\mathrm{close}_{{t-20}}) / (20\\,\\mathrm{close})."""
+"""qlib158 BETA20: formula = \\mathrm{Slope}(\\mathrm{close}, 20) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, delta
+from src.factors.base import safe_div, ts_slope
__alpha_meta__ = {
'id': 'qlib158_beta20',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close}_t - \\\\mathrm{close}_{{t-20}}) / (20\\\\,\\\\mathrm{close})',
+ 'formula_latex': '\\\\mathrm{Slope}(\\\\mathrm{close}, 20) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 BETA20 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(delta(c, 20), c) / float(20)
+ return safe_div(ts_slope(c, 20), c)
diff --git a/agent/src/factors/zoo/qlib158/beta30.py b/agent/src/factors/zoo/qlib158/beta30.py
index c7636c793..60a9e3535 100644
--- a/agent/src/factors/zoo/qlib158/beta30.py
+++ b/agent/src/factors/zoo/qlib158/beta30.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: Beta系数 30日
-# 简要说明: ts_cov(close, ts_mean(close, 30), 30) / ts_var(close, 30),个股相对于自身的30日Beta。
-# 典型用途: 衡量个股在30日窗口内的弹性/风险,高Beta意味着高波动和高弹性。
+# 简要说明: Slope(close, 30) / close,收盘价对时间的30日线性回归斜率,按最新收盘价归一化。
+# 典型用途: 衡量30日价格趋势的速度和方向,正值表示上涨趋势。
# ============================================================
-"""qlib158 BETA30: formula = (\\mathrm{close}_t - \\mathrm{close}_{{t-30}}) / (30\\,\\mathrm{close})."""
+"""qlib158 BETA30: formula = \\mathrm{Slope}(\\mathrm{close}, 30) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, delta
+from src.factors.base import safe_div, ts_slope
__alpha_meta__ = {
'id': 'qlib158_beta30',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close}_t - \\\\mathrm{close}_{{t-30}}) / (30\\\\,\\\\mathrm{close})',
+ 'formula_latex': '\\\\mathrm{Slope}(\\\\mathrm{close}, 30) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 BETA30 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(delta(c, 30), c) / float(30)
+ return safe_div(ts_slope(c, 30), c)
diff --git a/agent/src/factors/zoo/qlib158/beta5.py b/agent/src/factors/zoo/qlib158/beta5.py
index d9e2dbbf7..fb8804296 100644
--- a/agent/src/factors/zoo/qlib158/beta5.py
+++ b/agent/src/factors/zoo/qlib158/beta5.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: Beta系数 5日
-# 简要说明: ts_cov(close, ts_mean(close, 5), 5) / ts_var(close, 5),个股相对于自身的5日Beta。
-# 典型用途: 衡量个股在5日窗口内的弹性/风险,高Beta意味着高波动和高弹性。
+# 简要说明: Slope(close, 5) / close,收盘价对时间的5日线性回归斜率,按最新收盘价归一化。
+# 典型用途: 衡量5日价格趋势的速度和方向,正值表示上涨趋势。
# ============================================================
-"""qlib158 BETA5: formula = (\\mathrm{close}_t - \\mathrm{close}_{{t-5}}) / (5\\,\\mathrm{close})."""
+"""qlib158 BETA5: formula = \\mathrm{Slope}(\\mathrm{close}, 5) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, delta
+from src.factors.base import safe_div, ts_slope
__alpha_meta__ = {
'id': 'qlib158_beta5',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close}_t - \\\\mathrm{close}_{{t-5}}) / (5\\\\,\\\\mathrm{close})',
+ 'formula_latex': '\\\\mathrm{Slope}(\\\\mathrm{close}, 5) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 BETA5 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(delta(c, 5), c) / float(5)
+ return safe_div(ts_slope(c, 5), c)
diff --git a/agent/src/factors/zoo/qlib158/beta60.py b/agent/src/factors/zoo/qlib158/beta60.py
index 0ee970eb0..a8cb0864b 100644
--- a/agent/src/factors/zoo/qlib158/beta60.py
+++ b/agent/src/factors/zoo/qlib158/beta60.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: Beta系数 60日
-# 简要说明: ts_cov(close, ts_mean(close, 60), 60) / ts_var(close, 60),个股相对于自身的60日Beta。
-# 典型用途: 衡量个股在60日窗口内的弹性/风险,高Beta意味着高波动和高弹性。
+# 简要说明: Slope(close, 60) / close,收盘价对时间的60日线性回归斜率,按最新收盘价归一化。
+# 典型用途: 衡量60日价格趋势的速度和方向,正值表示上涨趋势。
# ============================================================
-"""qlib158 BETA60: formula = (\\mathrm{close}_t - \\mathrm{close}_{{t-60}}) / (60\\,\\mathrm{close})."""
+"""qlib158 BETA60: formula = \\mathrm{Slope}(\\mathrm{close}, 60) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, delta
+from src.factors.base import safe_div, ts_slope
__alpha_meta__ = {
'id': 'qlib158_beta60',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close}_t - \\\\mathrm{close}_{{t-60}}) / (60\\\\,\\\\mathrm{close})',
+ 'formula_latex': '\\\\mathrm{Slope}(\\\\mathrm{close}, 60) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 BETA60 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(delta(c, 60), c) / float(60)
+ return safe_div(ts_slope(c, 60), c)
diff --git a/agent/src/factors/zoo/qlib158/resi10.py b/agent/src/factors/zoo/qlib158/resi10.py
index 9e90d7bd1..c2efbdefc 100644
--- a/agent/src/factors/zoo/qlib158/resi10.py
+++ b/agent/src/factors/zoo/qlib158/resi10.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: 残差 10日
-# 简要说明: (close - ts_mean(close, 10)) / close,价格相对10日均线的偏离度。
-# 典型用途: 衡量价格偏离均线的程度,用于均值回复策略。
+# 简要说明: Resi(close, 10) / close,最新收盘价相对10日线性回归拟合值的残差。
+# 典型用途: 衡量价格偏离趋势线的程度,用于均值回复策略。
# ============================================================
-"""qlib158 RESI10: formula = (\\mathrm{close} - \\mathrm{ts\\_mean}(\\mathrm{close}, 10)) / \\mathrm{close}."""
+"""qlib158 RESI10: formula = \\mathrm{Resi}(\\mathrm{close}, 10) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, ts_mean
+from src.factors.base import safe_div, ts_resi
__alpha_meta__ = {
'id': 'qlib158_resi10',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close} - \\\\mathrm{ts\\\\_mean}(\\\\mathrm{close}, 10)) / \\\\mathrm{close}',
+ 'formula_latex': '\\\\mathrm{Resi}(\\\\mathrm{close}, 10) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 RESI10 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(c - ts_mean(c, 10), c)
+ return safe_div(ts_resi(c, 10), c)
diff --git a/agent/src/factors/zoo/qlib158/resi20.py b/agent/src/factors/zoo/qlib158/resi20.py
index f587b2bd8..a4e4b9093 100644
--- a/agent/src/factors/zoo/qlib158/resi20.py
+++ b/agent/src/factors/zoo/qlib158/resi20.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: 残差 20日
-# 简要说明: (close - ts_mean(close, 20)) / close,价格相对20日均线的偏离度。
-# 典型用途: 衡量价格偏离均线的程度,用于均值回复策略。
+# 简要说明: Resi(close, 20) / close,最新收盘价相对20日线性回归拟合值的残差。
+# 典型用途: 衡量价格偏离趋势线的程度,用于均值回复策略。
# ============================================================
-"""qlib158 RESI20: formula = (\\mathrm{close} - \\mathrm{ts\\_mean}(\\mathrm{close}, 20)) / \\mathrm{close}."""
+"""qlib158 RESI20: formula = \\mathrm{Resi}(\\mathrm{close}, 20) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, ts_mean
+from src.factors.base import safe_div, ts_resi
__alpha_meta__ = {
'id': 'qlib158_resi20',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close} - \\\\mathrm{ts\\\\_mean}(\\\\mathrm{close}, 20)) / \\\\mathrm{close}',
+ 'formula_latex': '\\\\mathrm{Resi}(\\\\mathrm{close}, 20) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 RESI20 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(c - ts_mean(c, 20), c)
+ return safe_div(ts_resi(c, 20), c)
diff --git a/agent/src/factors/zoo/qlib158/resi30.py b/agent/src/factors/zoo/qlib158/resi30.py
index 9ca4724f5..5700244dd 100644
--- a/agent/src/factors/zoo/qlib158/resi30.py
+++ b/agent/src/factors/zoo/qlib158/resi30.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: 残差 30日
-# 简要说明: (close - ts_mean(close, 30)) / close,价格相对30日均线的偏离度。
-# 典型用途: 衡量价格偏离均线的程度,用于均值回复策略。
+# 简要说明: Resi(close, 30) / close,最新收盘价相对30日线性回归拟合值的残差。
+# 典型用途: 衡量价格偏离趋势线的程度,用于均值回复策略。
# ============================================================
-"""qlib158 RESI30: formula = (\\mathrm{close} - \\mathrm{ts\\_mean}(\\mathrm{close}, 30)) / \\mathrm{close}."""
+"""qlib158 RESI30: formula = \\mathrm{Resi}(\\mathrm{close}, 30) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, ts_mean
+from src.factors.base import safe_div, ts_resi
__alpha_meta__ = {
'id': 'qlib158_resi30',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close} - \\\\mathrm{ts\\\\_mean}(\\\\mathrm{close}, 30)) / \\\\mathrm{close}',
+ 'formula_latex': '\\\\mathrm{Resi}(\\\\mathrm{close}, 30) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 RESI30 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(c - ts_mean(c, 30), c)
+ return safe_div(ts_resi(c, 30), c)
diff --git a/agent/src/factors/zoo/qlib158/resi5.py b/agent/src/factors/zoo/qlib158/resi5.py
index 5daf577ab..58ea05ca4 100644
--- a/agent/src/factors/zoo/qlib158/resi5.py
+++ b/agent/src/factors/zoo/qlib158/resi5.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: 残差 5日
-# 简要说明: (close - ts_mean(close, 5)) / close,价格相对5日均线的偏离度。
-# 典型用途: 衡量价格偏离均线的程度,用于均值回复策略。
+# 简要说明: Resi(close, 5) / close,最新收盘价相对5日线性回归拟合值的残差。
+# 典型用途: 衡量价格偏离趋势线的程度,用于均值回复策略。
# ============================================================
-"""qlib158 RESI5: formula = (\\mathrm{close} - \\mathrm{ts\\_mean}(\\mathrm{close}, 5)) / \\mathrm{close}."""
+"""qlib158 RESI5: formula = \\mathrm{Resi}(\\mathrm{close}, 5) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, ts_mean
+from src.factors.base import safe_div, ts_resi
__alpha_meta__ = {
'id': 'qlib158_resi5',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close} - \\\\mathrm{ts\\\\_mean}(\\\\mathrm{close}, 5)) / \\\\mathrm{close}',
+ 'formula_latex': '\\\\mathrm{Resi}(\\\\mathrm{close}, 5) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 RESI5 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(c - ts_mean(c, 5), c)
+ return safe_div(ts_resi(c, 5), c)
diff --git a/agent/src/factors/zoo/qlib158/resi60.py b/agent/src/factors/zoo/qlib158/resi60.py
index e57a9b66f..83f73faa8 100644
--- a/agent/src/factors/zoo/qlib158/resi60.py
+++ b/agent/src/factors/zoo/qlib158/resi60.py
@@ -2,19 +2,19 @@
# (Apache-2.0). Copyright (c) Microsoft Corporation.
# ============================================================
# 中文名称: 残差 60日
-# 简要说明: (close - ts_mean(close, 60)) / close,价格相对60日均线的偏离度。
-# 典型用途: 衡量价格偏离均线的程度,用于均值回复策略。
+# 简要说明: Resi(close, 60) / close,最新收盘价相对60日线性回归拟合值的残差。
+# 典型用途: 衡量价格偏离趋势线的程度,用于均值回复策略。
# ============================================================
-"""qlib158 RESI60: formula = (\\mathrm{close} - \\mathrm{ts\\_mean}(\\mathrm{close}, 60)) / \\mathrm{close}."""
+"""qlib158 RESI60: formula = \\mathrm{Resi}(\\mathrm{close}, 60) / \\mathrm{close}."""
from __future__ import annotations
import pandas as pd
-from src.factors.base import safe_div, ts_mean
+from src.factors.base import safe_div, ts_resi
__alpha_meta__ = {
'id': 'qlib158_resi60',
'theme': ['momentum'],
- 'formula_latex': '(\\\\mathrm{close} - \\\\mathrm{ts\\\\_mean}(\\\\mathrm{close}, 60)) / \\\\mathrm{close}',
+ 'formula_latex': '\\\\mathrm{Resi}(\\\\mathrm{close}, 60) / \\\\mathrm{close}',
'columns_required': ['close'],
'universe': ['equity_us', 'equity_cn', 'equity_hk', 'equity_in', 'equity_kr'],
'frequency': ['1d'],
@@ -26,4 +26,4 @@ __alpha_meta__ = {
def compute(panel: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""Return qlib158 RESI60 on the supplied OHLCV panel."""
c = panel['close']
- return safe_div(c - ts_mean(c, 60), c)
+ return safe_div(ts_resi(c, 60), c)
diff --git a/agent/tests/factors/test_qlib158_regression.py b/agent/tests/factors/test_qlib158_regression.py
new file mode 100644
index 000000000..8fdc4bdba
--- /dev/null
+++ b/agent/tests/factors/test_qlib158_regression.py
@@ -0,0 +1,65 @@
+"""Qlib's BETA and RESI features share one trailing OLS fit."""
+
+from __future__ import annotations
+
+import importlib
+
+import numpy as np
+import pandas as pd
+import pytest
+
+_WINDOWS = (5, 10, 20, 30, 60)
+
+
+def _close_through(window: int) -> pd.DataFrame:
+ steps = np.arange(window + 1, dtype=np.float64)
+ values = 30.0 + 0.7 * steps + 0.11 * steps**2 + np.sin(steps * 0.8)
+ return pd.DataFrame(values, columns=["A"])
+
+
+def _fit(window: np.ndarray) -> tuple[float, float]:
+ slope, intercept = np.polyfit(np.arange(window.size, dtype=np.float64), window, 1)
+ return float(slope), float(intercept)
+
+
[email protected]("window", _WINDOWS)
+def test_beta_is_the_ols_slope_over_latest_close(window: int) -> None:
+ close = _close_through(window)
+ module = importlib.import_module(f"src.factors.zoo.qlib158.beta{window}")
+
+ actual = module.compute({"close": close})["A"]
+
+ for end in (window - 1, window):
+ values = close["A"].iloc[end - window + 1 : end + 1].to_numpy()
+ slope, _ = _fit(values)
+ assert actual.iloc[end] == pytest.approx(slope / values[-1], abs=1e-12)
+
+
[email protected]("window", _WINDOWS)
+def test_resi_is_the_latest_point_residual_over_latest_close(window: int) -> None:
+ close = _close_through(window)
+ module = importlib.import_module(f"src.factors.zoo.qlib158.resi{window}")
+
+ actual = module.compute({"close": close})["A"]
+
+ for end in (window - 1, window):
+ values = close["A"].iloc[end - window + 1 : end + 1].to_numpy()
+ slope, intercept = _fit(values)
+ fitted = intercept + slope * (window - 1)
+ assert actual.iloc[end] == pytest.approx(
+ (values[-1] - fitted) / values[-1], abs=1e-12
+ )
+
+
[email protected]("stem", ("beta", "resi"))
+def test_regression_features_require_a_complete_gap_free_window(stem: str) -> None:
+ close = pd.DataFrame(
+ {"A": [20.0, 21.0, 23.0, 24.0, 27.0, 28.0, 32.0, 33.0, 37.0, 39.0, 42.0, 46.0]}
+ )
+ close.iloc[3, 0] = np.nan
+ module = importlib.import_module(f"src.factors.zoo.qlib158.{stem}5")
+
+ actual = module.compute({"close": close})["A"]
+
+ assert actual.iloc[3:8].isna().all()
+ assert actual.iloc[8:].notna().all()
diff --git a/agent/tests/test_factor_operators.py b/agent/tests/test_factor_operators.py
index 23497be00..1c69a25ad 100644
--- a/agent/tests/test_factor_operators.py
+++ b/agent/tests/test_factor_operators.py
@@ -278,6 +278,58 @@ class TestDecayLinear:
base.decay_linear(pd.DataFrame(), 0)
+# ── Rolling OLS tests ──
+
+
+class TestRollingRegression:
+ @pytest.mark.parametrize("n", [2, 5, 20])
+ def test_matches_polyfit(self, random_df, n):
+ base = _reload_base_with_bottleneck(True)
+ df = random_df.iloc[:30, :3]
+ slope = base.ts_slope(df, n)
+ resi = base.ts_resi(df, n)
+ expected_slope = np.full(df.shape, np.nan)
+ expected_resi = np.full(df.shape, np.nan)
+ x = np.arange(n, dtype=np.float64)
+
+ for end in range(n - 1, len(df)):
+ for column in range(df.shape[1]):
+ values = df.iloc[end - n + 1 : end + 1, column].to_numpy()
+ fit = np.polyfit(x, values, 1)
+ expected_slope[end, column] = fit[0]
+ expected_resi[end, column] = values[-1] - np.polyval(fit, x[-1])
+
+ np.testing.assert_allclose(
+ slope.to_numpy(), expected_slope, rtol=1e-12, atol=1e-12
+ )
+ np.testing.assert_allclose(
+ resi.to_numpy(), expected_resi, rtol=1e-12, atol=1e-12
+ )
+
+ def test_gap_invalidates_only_overlapping_windows(self, random_df):
+ base = _reload_base_with_bottleneck(True)
+ df = random_df.iloc[:20, :2].copy()
+ df.iloc[6, 0] = np.nan
+
+ slope = base.ts_slope(df, 5)
+ resi = base.ts_resi(df, 5)
+
+ for result in (slope, resi):
+ assert result.iloc[6:11, 0].isna().all()
+ assert result.iloc[11:, 0].notna().all()
+ assert result.iloc[4:, 1].notna().all()
+
+ def test_short_input_and_invalid_window(self, random_df):
+ base = _reload_base_with_bottleneck(True)
+ short = random_df.iloc[:3, :2]
+ assert base.ts_slope(short, 5).isna().all().all()
+ assert base.ts_resi(short, 5).isna().all().all()
+ with pytest.raises(ValueError, match="window must be >= 2"):
+ base.ts_slope(short, 1)
+ with pytest.raises(ValueError, match="window must be >= 2"):
+ base.ts_resi(short, 1)
+
+
# ── Backend detection tests ──