Files
Auto-Trader/agent/tests/test_bench_multiple_testing.py
T
shadowinlife ee03474268 feat(factors): industry-neutralized CN value alphas + PIT SW2021 sector tag (csi300) (#1802)
* feat(bench): add horizon parameter for monthly-frequency IC revalidation

h-bar forward returns (close[t+h]/close[t]-1, no ffill — a NaN close never
bridges) sampled non-overlapping end-anchored, so the naive-iid t-stat and
the alive/dead thresholds stay honest without new statistics. Threaded
through run_bench / run_bench_strict / the alpha_bench tool + MCP wrapper /
CLI --horizon (argparse type + handler guard, exit 2 on bad input).
horizon=1 is byte-identical to the previous next-bar formula.

Follow-up #1 of issue #1789 (monthly-horizon revalidation of the 13
fundamental factors — the conventional reading for fundamental factors).

* fix(bench): exclude SEC-fundamental alphas off sp500 instead of failing the bench

--zoo fundamental --universe csi300 (the repro command printed in issue
#1789) hard-failed with 'Choose the S&P 500 universe' because the
validator rejects fund:* inputs on any non-sp500 universe, while the
mirror case (CN val:* alphas on sp500) skips cleanly per alpha. The
runners now split the selection up front, disclose the excluded ids in
the result envelope, and error only when nothing is left to bench; the
validator stays as the backstop for direct callers.

The CLI/tool JSON envelopes also state their own horizon,
forward_return_sampling and universe_excluded — a saved summary must
show the configuration its numbers came from.

* fix(bench): close review findings on horizon/exclusion disclosure

- multi-zoo CLI aggregation threads horizon / forward_return_sampling /
  universe_excluded from the sub-runs into the aggregate envelope (a saved
  all-zoos JSON now states its own horizon and reconciles its exclusions)
- alpha compare surfaces universe-excluded shortlist members as skipped
  entries with the exclusion reason instead of silently dropping them
- horizon upper bound (1.._MAX_HORIZON) enforced consistently at the CLI
  parser, the handler, and both runner entries BEFORE any panel load —
  previously only the tool/MCP capped it and an unbounded CLI run fetched
  the full panel before failing late
- non-int horizon can no longer TypeError in the entry schema construction
- categorise docstring notes the daily calibration of the |IC|>0.02 floor
  at h>1; the sampling comment no longer overclaims (residual
  autocorrelation from persistent factor exposures is not modeled)
- MCP wrapper uses _MAX_HORIZON instead of a hardcoded duplicate

Pinned by new tests: parser/handler/runner cap rejection (fetch not
called), multi-zoo disclosure aggregation, compare exclusion disclosure.

* feat(factors): industry-neutralized CN value alphas + PIT SW2021 sector tag

Three within-industry z-scored variants of the CN value factors
(fund_pb/fund_ps_ttm/fund_dividend_yield -> *_ind_neutral, zoo 475 -> 478):
raw A-share PB/PS/dy are heavily industry-confounded, so each name is
z-scored against its Shenwan L1 peers instead of the whole cross-section.

- industry_loader.py: tushare index_member_all (SW2021) membership with
  in_date/out_date -> point-in-time labels per trading day; deterministic
  overlap resolution; 2000-row truncation guard refetches per L1; degrades
  to an unmapped frame on provider failure, never invents a label.
- csi300 bench attaches panel['sector'] outside the pickled price cache,
  masked to the PIT membership cross-section, behind the same 0.9 coverage
  gate the sp500 GICS tag uses; meta discloses sector_source/coverage.
- base.zscore_by_group: the z-scoring sibling of alpha101's _ind_neutralize
  demean - no global fallback (an unlabelled cell stays NaN rather than
  wearing an industry-neutral label it did not earn).
- README x7 + SKILL.md counts (incl. the stale 462 prose sites), i18n zh/en.

Follow-up #2 of issue #1789.

* fix(loaders): index_member_all takes no src param; fetch PIT history via is_new Y+N

Live-verified endpoint contract (pinned by test): index_member_all accepts
only the documented l1/l2/l3_code, ts_code and is_new filters — an
undocumented src param silently returns an empty frame (HTTP 200, 0 rows),
which degraded the first csi300 sector attach to coverage 0.0. src now goes
to index_classify (truncation fallback) only.

The server also defaults is_new to 'Y' (current members, no out_date rows),
so the historical half ('N', ~2000 rows with out_date back to the 1990s) is
fetched separately and concatenated — without it every label would be
today's classification and the loader's PIT claim false.

Live smoke: 350/350 csi300 PIT constituents covered (100%), 0.9 gate passes.

* docs(factors): surface the SW2021 taxonomy-retroactivity caveat; pin cache immutability

Review follow-ups: the loader docstring disclosed that SW2021
classifications are applied retroactively, but no user-facing surface
did — one sentence added to each ind-neutral alpha's notes, the i18n
en/zh entries and SKILL.md (membership is point-in-time; the taxonomy
version itself is not). The sector-attach test now pins that the
original pickled panel dict is never mutated by the attach, and the
sector_coverage meta semantics (labelled-somewhere fraction, not
per-date) are documented at the attach site.

* fix(factors): align ind-neutral PB/PS with the upstream nonpositive-multiple guard

The maintenance batch (d3c76819) added a guard to fund_pb/fund_ps_ttm:
nonpositive multiples are excluded rather than ranked as cheap. The
industry-neutral variants follow suit — the within-group z-score sees
the same values.where(values > 0) pre-filter, the guard sentence leads
the notes/i18n entries, and the upstream parametrized test is mirrored
for the neutral stems.
2026-10-12 19:22:41 +08:00

127 lines
5.1 KiB
Python

"""Tests for the multiple-testing block wired into run_bench.
`n_alphas_tested` has been carried in the bench result since it was written and
has only ever been displayed. These tests pin the correction that now uses it,
and pin that adding it changed nothing else about the result.
"""
from __future__ import annotations
from unittest.mock import MagicMock
import numpy as np
import pandas as pd
import pytest
from src.factors.bench_runner import run_bench
from src.quantlib.multipletesting import MIN_OBSERVATIONS, expected_maximum_sharpe
def _make_panel(n_symbols: int = 10, n_days: int = 120):
rng = np.random.default_rng(42)
dates = pd.date_range("2020-01-01", periods=n_days, freq="B")
symbols = [f"SYM{i:03d}" for i in range(n_symbols)]
close = pd.DataFrame(
np.cumsum(rng.standard_normal((n_days, n_symbols)), axis=0) + 100,
index=dates,
columns=symbols,
)
return {"close": close, "open": close, "high": close, "low": close, "volume": close}
def _setup(monkeypatch, n_alphas=8, n_days=120):
panel = _make_panel(n_days=n_days)
return_df = panel["close"].pct_change().shift(-1).iloc[:-1]
rng = np.random.default_rng(7)
reg = MagicMock()
reg.list.return_value = [f"alpha_{i}" for i in range(n_alphas)]
reg.get.return_value = MagicMock(meta={"theme": ["test"], "formula_latex": ""})
reg.compute.side_effect = lambda aid, p: pd.DataFrame(
rng.standard_normal(p["close"].shape), index=p["close"].index, columns=p["close"].columns
)
monkeypatch.setattr("src.factors.bench_runner._load_universe_panel", lambda u, p: panel)
monkeypatch.setattr("src.factors.bench_runner._compute_forward_returns", lambda p, horizon=1: return_df)
monkeypatch.setattr("src.factors.bench_runner.get_default_registry", lambda: reg)
return reg
def test_bench_reports_a_multiple_testing_block(monkeypatch):
reg = _setup(monkeypatch, n_alphas=8)
result = run_bench("test_zoo", "mock", "2020-2021", registry=reg)
assert result["status"] == "ok"
block = result["multiple_testing"]
assert block["applicable"] is True
assert block["n_trials"] == result["n_alphas_tested"]
assert block["statistic"] == "ic_information_ratio"
def test_the_haircut_is_exactly_the_expected_maximum_under_the_null(monkeypatch):
reg = _setup(monkeypatch, n_alphas=10)
result = run_bench("test_zoo", "mock", "2020-2021", registry=reg)
block = result["multiple_testing"]
irs = np.array([float(r["ir"]) for r in result["rows"]])
expected = expected_maximum_sharpe(len(irs), float(irs.std(ddof=1)))
assert block["expected_max_ir_under_null"] == pytest.approx(expected, abs=1e-6)
assert block["ir_haircut"] == pytest.approx(block["best_ir"] - expected, abs=1e-6)
def test_the_best_alpha_named_by_the_block_is_the_best_alpha_in_the_rows(monkeypatch):
reg = _setup(monkeypatch, n_alphas=12)
result = run_bench("test_zoo", "mock", "2020-2021", registry=reg)
block = result["multiple_testing"]
best_by_ir = max(result["rows"], key=lambda r: r["ir"])
assert block["best_id"] == best_by_ir["id"]
assert block["best_ir"] == pytest.approx(best_by_ir["ir"])
def test_pure_noise_alphas_do_not_survive_deflation(monkeypatch):
# Every alpha here is random noise against the returns, so the best IR of
# the batch is the maximum of N draws and nothing more. The correction is
# supposed to say so.
reg = _setup(monkeypatch, n_alphas=16)
result = run_bench("test_zoo", "mock", "2020-2021", registry=reg)
block = result["multiple_testing"]
assert block["deflated_probability"] is not None
assert block["survives_deflation"] is False
def test_a_single_alpha_has_no_search_to_correct_for(monkeypatch):
reg = _setup(monkeypatch, n_alphas=1)
result = run_bench("test_zoo", "mock", "2020-2021", registry=reg)
assert result["multiple_testing"]["applicable"] is False
def test_a_short_ic_sample_reports_no_deflated_statistic_rather_than_a_bad_one(monkeypatch):
# Too few IC observations for the moments behind the statistic to mean
# anything: the block must say so instead of returning a number.
reg = _setup(monkeypatch, n_alphas=6, n_days=MIN_OBSERVATIONS + 2)
result = run_bench("test_zoo", "mock", "2020-2021", registry=reg)
block = result["multiple_testing"]
if block["applicable"] and block["ic_observations"] < MIN_OBSERVATIONS:
assert block["deflated_probability"] is None
assert block["survives_deflation"] is None
assert "note" in block
def test_wiring_the_block_in_did_not_change_any_existing_key(monkeypatch):
reg = _setup(monkeypatch, n_alphas=5)
result = run_bench("test_zoo", "mock", "2020-2021", registry=reg)
# The keys the bench has always returned are all still present, and
# `n_alphas_tested` still means what it always meant.
for key in (
"status", "n_alphas_tested", "n_skipped", "alive", "reversed", "dead",
"by_theme", "top5_by_ir", "dead_examples", "rows", "skipped", "meta",
"wall_seconds",
):
assert key in result, f"existing key {key} disappeared"
assert result["n_alphas_tested"] == len(result["rows"])