akg-factor-bridge/test_plan_rank_axis.py

237 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""选股计划排序轴换成公司质地(2026-09-17):传导降为雷达门与带内次级键。
离线,不连库不起服务。跑法:python3 test_plan_rank_axis.py,预期最后一行是 ALL OK。
逐字回旧那一例是 case1:四个开关都设旧值时,装配重排输出与 09-14 的 _rerank_by_quality 逐字节相同。
附录丙十例一一对应本文件的十个 test_*。
"""
import os
import sys
import types
# 离线不连库:装不上的驱动打空壳,pandas 本机装得上就用真的(重排要在真 Series 上验)。
for _n in ("pandas", "pymysql", "psycopg", "pymongo"):
if _n not in sys.modules:
try:
__import__(_n)
except Exception: # noqa: BLE001
_m = types.ModuleType(_n)
if _n == "pandas":
_m.DataFrame = type("DataFrame", (), {})
sys.modules[_n] = _m
import pandas as pd # noqa: E402 —— 重排就在 pd.Series 上做,直接用真的 pandas
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import card # noqa: E402
import config # noqa: E402
import plan # noqa: E402
import pool # noqa: E402
import review_targets # noqa: E402
FAILED = []
def t(name, cond, extra=""):
print((" ok " if cond else " FAIL ") + name + ((" " + str(extra)) if not cond else ""))
if not cond:
FAILED.append(name)
def _cr(overall, age_days=None):
if overall is None:
return None
d = {"overall": overall}
if age_days is not None:
d["age_days"] = age_days
return d
def _cards(spec: dict) -> dict:
"""spec:{代码: (质地档, 被指向[, 报告日龄])}。装成 collect 里 cards 的形状(只放本改动要读的两路)。"""
out = {}
for k, v in spec.items():
overall, pointed = v[0], v[1]
age = v[2] if len(v) > 2 else None
out[k] = {"company_review": _cr(overall, age), "gates": {"pointed": pointed}}
return out
def test_1_replay_transmission():
print("[case1 四开关设旧值:逐字回旧到 _rerank_by_quality]")
ranked = pd.Series({"A": 242.0, "B": 238.0, "C": 222.0, "D": 218.0})
cards = _cards({"A": ("差", True), "B": ("好", False), "C": ("好", True), "D": ("差", False)})
old = config.PLAN_RANK_AXIS
try:
config.PLAN_RANK_AXIS = "transmission"
out = plan._rerank(ranked, cards, True)
finally:
config.PLAN_RANK_AXIS = old
ref = plan._rerank_by_quality(ranked, cards, config.PLAN_QUALITY_BONUS)
t("序列顺序逐字相同", list(out.index) == list(ref.index), list(out.index))
t("分值逐字相同", list(out.values) == list(ref.values))
def test_2_bands_order():
print("[case2 质地带:好 > 中 > 无评析 > 差]")
ranked = pd.Series({"g": 210.0, "m": 210.0, "n": 210.0, "b": 210.0})
cards = _cards({"g": ("好", False), "m": ("中", False), "n": (None, False), "b": ("差", False)})
out = plan._rerank_by_axis(ranked, cards, "quality", 120, True)
t("好中无差", list(out.index) == ["g", "m", "n", "b"], list(out.index))
def test_3_within_band():
print("[case3 同带内:被指向优先,再按组内分]")
ranked = pd.Series({"p_lo": 213.0, "p_hi": 217.0, "np_hi": 218.0})
cards = _cards({"p_lo": ("好", True), "p_hi": ("好", True), "np_hi": ("好", False)})
out = plan._rerank_by_axis(ranked, cards, "quality", 120, True)
t("被指向优先且带内按组内分", list(out.index) == ["p_hi", "p_lo", "np_hi"], list(out.index))
def test_4_deterministic():
print("[case4 确定性:两次相同、末位键代码升序]")
ranked = pd.Series({"B": 210.0, "A": 210.0})
cards = _cards({"A": ("好", True), "B": ("好", True)})
o1 = list(plan._rerank_by_axis(ranked, cards, "quality", 120, True).index)
o2 = list(plan._rerank_by_axis(ranked, cards, "quality", 120, True).index)
t("两次装配顺序相同", o1 == o2, o1)
t("末位键代码升序", o1 == ["A", "B"], o1)
def test_5_stale_demotes():
print("[case5 超期一百二十天的好公司落到第一带]")
ranked = pd.Series({"fresh": 210.0, "mid": 210.0, "stale": 210.0})
cards = _cards({"fresh": ("好", False, 10), "mid": ("中", False, 10), "stale": ("好", False, 200)})
out = plan._rerank_by_axis(ranked, cards, "quality", 120, True)
t("超期好票落到无评析带(排到中之后)", list(out.index) == ["fresh", "mid", "stale"], list(out.index))
def test_6_pool_rank_source():
print("[case6 入池 rank:只取被指向的,数量等于 top,按新序]")
main_rows = [
{"code": "a", "pointed": True, "tier": "强传导", "rank_old": 3},
{"code": "b", "pointed": False, "tier": "强传导", "rank_old": 1},
{"code": "c", "pointed": True, "tier": "弱传导", "rank_old": 5},
{"code": "d", "pointed": True, "tier": "无传导", "rank_old": 2},
]
rows = pool.select_plan_rows(main_rows, 2, "rank", set())
t("只取被指向", all(r.get("pointed") for r in rows), [r["code"] for r in rows])
t("数量等于 top", len(rows) == 2, len(rows))
t("按主榜新序取前二", [r["code"] for r in rows] == ["a", "c"], [r["code"] for r in rows])
t("_pool_source 记 rank_top", all(r["_pool_source"] == "rank_top" for r in rows))
def test_7_review_targets_union():
print("[case7 评析名单两路并集:去重、按新序]")
main = [
{"code": "600001.SH", "name": "x1", "score": 300, "rank": 1},
{"code": "600002.SH", "name": "x2", "score": 260, "rank": 2},
{"code": "600003.SH", "name": "x3", "score": 320, "rank": 3},
]
both = review_targets.pick_main_targets(main, "both", 2, 1)
codes = [r["code"] for r in both]
# score 降序前二:x3(320)、x1(300);rank 升序前一:x1(rank1)。并集去重={x1,x3},按 rank 排 → x1,x3
t("并集去重", set(codes) == {"600001.SH", "600003.SH"}, codes)
t("按新序(rank)排", codes == ["600001.SH", "600003.SH"], codes)
only = review_targets.pick_main_targets(main, "score", 2, 1)
t("score 轴逐字回旧(score 降序前二)", [r["code"] for r in only] == ["600003.SH", "600001.SH"],
[r["code"] for r in only])
def test_8_card_sort_toggle():
print("[case8 卡内序开关:开则质地优先,关则回先判决再涨幅]")
rows = [
{"verdict": "候选", "quality_band": 0, "pct0": 5.0},
{"verdict": "候选", "quality_band": 3, "pct0": 1.0},
]
old = config.CARD_SORT_BY_QUALITY
try:
config.CARD_SORT_BY_QUALITY = True
on = sorted(rows, key=card.sort_key)
t("开:质地好在前", on[0]["quality_band"] == 3, on[0])
config.CARD_SORT_BY_QUALITY = False
off = sorted(rows, key=card.sort_key)
t("关:涨幅高在前(逐字回旧)", off[0]["pct0"] == 5.0, off[0])
finally:
config.CARD_SORT_BY_QUALITY = old
def test_9_theme_cap_exemption():
print("[case9 主题限额:质地轴下无传导票免限额,有主题仍每主题五只]")
no_theme = [{"code": f"n{i}", "evidence": None, "rank_axis": "quality"} for i in range(6)]
t("无传导票免五只限额", len(plan.pick_rows(no_theme, 20, 5, uncapped_no_theme=True)) == 6)
t("旧轴无主题同样不合桶", len(plan.pick_rows(no_theme, 20, 5, uncapped_no_theme=False)) == 6)
themed = [{"code": f"t{i}", "evidence": {"theme": "锂电"}, "rank_axis": "quality"} for i in range(6)]
t("有主题仍受每主题五只", len(plan.pick_rows(themed, 20, 5, uncapped_no_theme=True)) == 5)
def test_10_pool_keep_old():
print("[case10 备用开关 keep_old:并进旧序强传导前 top,去重,受 POOL_MAX 兜底]")
main_rows = [
{"code": "a", "pointed": True, "tier": "强传导", "rank_old": 3},
{"code": "b", "pointed": False, "tier": "强传导", "rank_old": 1},
{"code": "e", "pointed": False, "tier": "强传导", "rank_old": 2},
]
rows = pool.select_plan_rows(main_rows, 2, "rank", {"强传导"}, keep_old=True)
codes = [r["code"] for r in rows]
t("被指向的 a 在", "a" in codes, codes)
t("旧序强传导前二并进(b、e)", "b" in codes and "e" in codes, codes)
t("同票不重复", len(codes) == len(set(codes)), codes)
old_max = config.POOL_MAX
try:
config.POOL_MAX = 2
rows2 = pool.select_plan_rows(main_rows, 2, "rank", {"强传导"}, keep_old=True)
t("POOL_MAX 兜底", len(rows2) <= 2, len(rows2))
finally:
config.POOL_MAX = old_max
def test_11_started_member_counts_theme():
print("[case11 必改一:已启动成员两条路都算进所在主题、受限额]")
# 六条同主题"锂电",前五条走传导视图证据行,第六条无证据行、由候选卡 moved_view 补主题
ev = {f"c{i}": ("锂电", 2, 0.3) for i in range(5)}
cards = {"c5": {"started_source": "moved_view", "theme": "锂电"}}
def _theme_of(kv): # 与 collect 里 _theme_of 同源:先传导视图证据行,再已动成员视图补充
k = kv[0]
e = ev.get(k)
if e:
return e[0]
c = cards.get(k) or {}
if c.get("started_source") == "moved_view" and c.get("theme"):
return c["theme"]
return None
items = [(f"c{i}", 200.0 - i) for i in range(6)]
picked = plan.take_by_theme(items, 20, 5, _theme_of, uncapped_no_theme=True)
t("装配路:同主题只放五条(含 moved_view 补主题那条算进主题)", len(picked) == 5, len(picked))
rows = [{"code": f"c{i}", "evidence": {"theme": "锂电"}, "rank_axis": "quality"} for i in range(6)]
t("快照路:同样六条只放五条", len(plan.pick_rows(rows, 20, 5)) == 5, len(plan.pick_rows(rows, 20, 5)))
def test_12_no_theme_by_axis():
print("[case12 必改一:无主题行两轴各归各——质地轴免限额,旧轴归无传导桶计数]")
items = [(f"n{i}", 200.0 - i) for i in range(6)]
none_theme = lambda kv: None # noqa: E731 —— 六条都无主题
t("质地轴(uncapped 真)放六条", len(plan.take_by_theme(items, 20, 5, none_theme, True)) == 6)
t("旧轴(uncapped 假)无主题同样免限额", len(plan.take_by_theme(items, 20, 5, none_theme, False)) == 6)
def main():
for fn in (test_1_replay_transmission, test_2_bands_order, test_3_within_band,
test_4_deterministic, test_5_stale_demotes, test_6_pool_rank_source,
test_7_review_targets_union, test_8_card_sort_toggle, test_9_theme_cap_exemption,
test_10_pool_keep_old, test_11_started_member_counts_theme, test_12_no_theme_by_axis):
fn()
print("-" * 70)
if FAILED:
print("FAILED %d: %s" % (len(FAILED), "; ".join(FAILED)))
return 1
print("ALL OK — 排序轴换质地:逐字回旧 / 四带序 / 带内次级键 / 确定性 / 超期守卫 / "
"入池 rank / 评析并集 / 卡内序 / 主题限额例外 / 备用开关")
return 0
if __name__ == "__main__":
sys.exit(main())