From e7242f6555b9fabfafa666c3ac63c9ad11b48cbf Mon Sep 17 00:00:00 2001 From: baobao Date: Mon, 26 Oct 2026 14:41:25 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=87=E6=8D=A2=E8=B4=A8=E5=9C=B0=E9=80=89?= =?UTF-8?q?=E8=82=A1=E5=B9=B6=E8=AE=A9=E5=91=BD=E4=BB=A4=E5=8D=87=E4=BB=93?= =?UTF-8?q?=E6=B2=BF=E7=94=A8=E5=80=99=E9=80=89=E9=A1=BA=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DEVLOG.md | 9 +++ app/core/planner.py | 19 +++++- app/services/command_service.py | 10 ++- config/settings.py | 12 ++-- scripts/run_tests.py | 2 + scripts/test_batch46_units.py | 108 ++++++++++++++++++++++++++++++++ 6 files changed, 149 insertions(+), 11 deletions(-) create mode 100644 scripts/test_batch46_units.py diff --git a/DEVLOG.md b/DEVLOG.md index c2cadfc..b002804 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -2158,3 +2158,12 @@ QMT在线、对账无差异。午休任务按原时段跳过,不制造交易 改动文件只有 docs/开发接续_2026-10-12.md 和本记录,补入跨系统未完成事项、实际参数、过滤影响和后续验收条件。另记录命令升仓仍按原始分重排,与自主提议继承 selection_rank 不同。开发机 git diff --check 通过,未改业务代码,未运行业务回归。服务器操作仅为 SELECT、GET 已发布计划及读取指定有效配置,没有写库、改参、重启、发布计划、下单或操作 188。 现状与过滤影响判收为真机见过,新策略上线为未判收。后续需明确两档白名单或完全取消档位的范围,联合验证桥、夜间分析池与 PMS 的排序及准入,不能以单个开关或重新部署替代策略切换验收。 + + +## 2026-10-26(续)· 质地排序统一切换的代码交付 + +用户授权全权完成选股切换。PMS 取消传导档位默认过滤,命令升仓继承候选 selection_rank,旧来源缺名次时保留原分数顺序,用户点名仍优先。补齐已在计划中的白名单票优先级,黑名单和已持仓排除保持。原始分、研判、择时、仓位与下单规则未重定义。 + +变更为 config/settings.py、app/core/planner.py、app/services/command_service.py,新增 scripts/test_batch46_units.py 并登记 scripts/run_tests.py。开发机独立 Python 3.12 经隔离入口完整 50 批、1165 例通过,含新增 11 例及三道页面护栏。桥同步新增冻结输入的排序修订入口,并让研究池消费已发布计划,详见桥台账 083。 + +155 已在临时目录的无配置、禁网容器通过桥 54 组契约测试及真实冻结输入的重排检查,原分数、判决、风险和研究均不变。此时未切服务器配置,未重建运行容器。代码测试通过,策略运行态判收仍为未判收;下一步完成候选镜像回归、备份、无在途与无待入账确认后联合部署,再查真实消费及研究池覆盖。 diff --git a/app/core/planner.py b/app/core/planner.py index 1c9a9aa..1df7ccc 100644 --- a/app/core/planner.py +++ b/app/core/planner.py @@ -83,6 +83,19 @@ def _sortable(p, key, reverse=False): return (-v if reverse else v, p.get("ts_code") or "") +def candidate_order(c): + """用户点名优先;计划票沿用实际筛选次序,旧来源仍按分数排。""" + code = c.get("ts_code") or "" + if c.get("src") == "whitelist" or c.get("user_selected"): + return (0, 0, 0, code) + rank = c.get("selection_rank") + if rank is None: + rank = (c.get("plan_provenance") or {}).get("selection_rank") + if rank is not None: + return (1, 0, float(rank), code) + return (1, 1, -float(c.get("score") or 0), code) + + def _usable(positions, exclude_codes): """可纳入减持方案的持仓: 有数量、**有真实现价**、不在排除名单 (已有在途方案的票)。 @@ -303,7 +316,7 @@ def plan_increase_exposure(*, add_amount: float, positions: list, candidates=Non ctx = _ctx_after(ctx, amt, is_new_name=False, sector=p.get("sector")) # ---- ② 候选池新票建仓 ---- - for execution_rank, c in enumerate(sorted(candidates or [], key=lambda x: _sortable(x, "score", reverse=True)), 1): + for execution_rank, c in enumerate(sorted(candidates or [], key=candidate_order), 1): if acc >= target: break price = float(c.get("price") or 0) @@ -330,8 +343,10 @@ def plan_increase_exposure(*, add_amount: float, positions: list, candidates=Non continue batches = _open_batch_items(c.get("ts_code"), sp, price, reason_prefix="升仓建新仓") for item in batches: + reason = ('用户白名单优先' if c.get('src') == 'whitelist' or c.get('user_selected') + else '沿用候选筛选次序' if candidate_order(c)[1] == 0 else '旧来源按分数排序') item['plan_provenance'] = dict(c.get('plan_provenance') or {}, execution_rank=execution_rank, - priority_reason='用户升仓命令,沿用命令调配次序') + priority_reason=reason) items.extend(batches) intended += want_amt acc += actual diff --git a/app/services/command_service.py b/app/services/command_service.py index 7724582..7291ab0 100644 --- a/app/services/command_service.py +++ b/app/services/command_service.py @@ -759,9 +759,8 @@ def _candidates(view: dict) -> list: 旧表的 target_price 若有则直接用。 2. **上游拿不到不回退旧表** —— 候选池宁可为空。那张表在目标架构下没有明确写入方, 拿它当事实源比没有候选更危险 (沿用「拿不到 ≠ 通过」的纪律)。 - 3. **白名单必须压过计划票** —— planner 只认 score 一把尺子, 而计划的 score 是 200+ - 量级 (旧表的 prob_thresh 是 0~1)。白名单是用户点名的票, 故给 max(池内分)+1, - 写死 1.0 会让点名票沉到池底。 + 3. 白名单必须压过计划票。规划器显式识别用户点名,计划票继承 selection_rank。 + 原始分仍保留供展示及旧来源兼容,不能用它重新覆盖质地排序。 """ from app.services import market, plan_feed held = {x["ts_code"] for x in view["held"]} @@ -789,6 +788,7 @@ def _candidates(view: dict) -> list: # 会让集中度约束跟着漂, 已于 2026-07-31 明确不再灌行业表 (见 UPSTREAM_PLAN_API.md §6)。 out.append({"ts_code": c, "price": px, "price_source": psrc, "score": float(score or 0), "sector": industry.get(c), "theme": theme, "src": tag, + 'selection_rank': (plan_provenance or {}).get('selection_rank'), 'plan_provenance': plan_provenance}) if src in (plan_feed.SRC_PLAN_API, plan_feed.SRC_BOTH): @@ -818,6 +818,10 @@ def _candidates(view: dict) -> list: for c, d in sp.items(): if d.get("white"): _push(c, white_score, "whitelist") + # 已在计划中的点名票也必须提升优先级;保留其研究及消费来源。 + for row in out: + if row['ts_code'] == c: + row.update(user_selected=True, score=white_score) if fallback: logger.info("[候选池] %d 只候选无实时价, 已用昨收定量 (盘前正常): %s", diff --git a/config/settings.py b/config/settings.py index f084b60..6f6eaf2 100644 --- a/config/settings.py +++ b/config/settings.py @@ -161,16 +161,16 @@ class Settings(BaseSettings): PMS_PLAN_OBS_TOP: int = 100 # 上游 obs_top: 观察档要多少条 PMS_PLAN_THEME_CAP: int = 999 # 上游 theme_cap: 让它别裁 (PMS 自己裁) PMS_PLAN_THEME_CAP_LOCAL: int = 5 # PMS 侧同主题限额, 在 TOP_N 截断**之前**生效, 0=不限 - PMS_PLAN_TOP_N: int = 30 # 主榜按 score 降序取前 N 进池 (900+ 只是排序池不是清单) - PMS_PLAN_TIERS: str = "强传导" # 传导档白名单; 留空=不按档过滤 - # **已定纪律 (2026-07-31, 用户): 候选宁缺毋滥, 不因当天强传导少就放宽到弱传导。** - # 上游文档说强传导规模随市场结构波动、无板块传导的日子可能一个都没有 —— 那种日子 - # 候选池就该是空的。只有"热度启动信息经确认"时才考虑放宽, 且要显式改这个参数。 + PMS_PLAN_TOP_N: int = 30 # 按有效排序取前 N 进池,运行参数可覆盖 + PMS_PLAN_TIERS: str = "" # 传导档白名单;留空不按强弱档位过滤 + # 2026-10-26 用户授权完成质地排序切换:传导强弱不再是候选资格门槛。 + # 质地次序由上游提供,判决、风险、黑名单和组合约束继续各自生效。 + # 此参数保留给显式限定场景,不能把旧的“只收强传导”默认为新策略。 PMS_PLAN_INCLUDE_OBSERVE: bool = False # 观察档是否进候选池 (上游把它定位为备选, 无 upside) PMS_PLAN_MIN_SCORE: float = 0.0 # score 下限, 0=不设 PMS_PLAN_MIN_SOURCES: int = 0 # evidence.n_sources 下限, 0=不设 PMS_PLAN_MIN_UPSIDE: float = 0.0 # 预期空间下限 (0.5=+50%), 0=不设。券商目标价 - # 口径, 噪音大 (榜首能到 +212%), 只做下限过滤, **不参与排序** —— 排序始终是 score + # 口径, 噪音大 (榜首能到 +212%), 只做下限过滤,不参与排序。 PMS_PLAN_STALE_TDAYS: int = 1 # 计划日龄超此交易日数即判过期并拒用 (防上游停更) PMS_PLAN_EXCLUDE_ST: bool = True # 剔除 ST/*ST/退市 (上游明确不剔除, 这道闸归 PMS) PMS_PLAN_THEME_SYNC: bool = False # 把 theme 灌进 pms_industry_map。**默认关**: diff --git a/scripts/run_tests.py b/scripts/run_tests.py index a697e45..3222c28 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -5,6 +5,7 @@ 运行: docker compose run --rm pms-web python scripts/run_tests.py 包含 (例数按 2026-10-26 隔离回归实跑校正): + test_batch46_units.py 质地排序切换、档位准入、命令分配与白名单优先 (11 例) test_batch45_units.py 父指令总量:回放延迟、部分成交、跨日预留、故障守成与影子模式 (16 例) test_batch43_units.py 逐票来源核验、实际API至SQL事务、故障回滚与幂等 (14 例) test_batch42_units.py 提议先准备后采纳、模型复用、并发更新与发布审计 (24 例) @@ -198,6 +199,7 @@ SUITES = ["test_core_units.py", "test_batch2_units.py", "test_batch3_units.py", "test_batch37_units.py", "test_batch38_units.py", "test_batch39_units.py", "test_batch40_units.py", "test_batch41_units.py", "test_batch42_units.py", "test_batch43_units.py", "test_batch44_units.py", "test_batch45_units.py", + "test_batch46_units.py", "test_page_copy_guard.py", "test_page_enum_guard.py", "test_page_wiring_guard.py", diff --git a/scripts/test_batch46_units.py b/scripts/test_batch46_units.py new file mode 100644 index 0000000..196df29 --- /dev/null +++ b/scripts/test_batch46_units.py @@ -0,0 +1,108 @@ +"""质地排序切换:资格、命令优先级与实际分配;配置隔离,禁止联网。""" +import unit_test_guard # noqa: F401 +import os +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from app.core import planner +from app.services import plan_feed as pf, command_service as cs, param_store as ps +from config.settings import settings +from test_wiring import install_fakes +from test_batch20_units import caps, params + + +def sample(): + return pf.parse_plan({'date': '2026-10-23', 'rank_axis': 'quality', 'main': [ + {'code': 'SH600001', 'name': '质地好弱传导', 'tier': '弱传导', 'score': 220, + 'rank': 1, 'research_rank': 2, 'verdict': '候选'}, + {'code': 'SH600002', 'name': '质地中强传导', 'tier': '强传导', 'score': 245, + 'rank': 2, 'research_rank': 9, 'verdict': '候选'}, + {'code': 'SH600003', 'name': '已启动无传导', 'tier': '无传导', 'score': 201, + 'rank': 3, 'research_rank': 15, 'verdict': '候选'}]}) + + +class QualityCutoverTest(unittest.TestCase): + def setUp(self): + install_fakes(prices={f'60000{i}.SH': 10 for i in range(1, 5)}, + params={'PMS_CANDIDATE_SOURCE': 'plan_api'}) + + def selected(self, **kw): + return pf.select_candidates(sample(), rank_by_upstream=True, **kw) + + def plan(self, rows): + return planner.plan_increase_exposure(add_amount=10000, positions=[], candidates=rows, + ctx=caps(), params=params(batch_split=(1., 0., 0.))) + + def commands(self, white=None, black=None, held=()): + sp = {c: {'white': True} for c in white or []} + sp.update({c: {'black': True} for c in black or []}) + with patch.object(cs, 'effective_stock_params', return_value=sp), \ + patch.object(pf, 'candidates', return_value=self.selected()): + return cs._candidates({'held': [{'ts_code': c} for c in held]}) + + def test_default_has_no_transmission_tier_gate(self): + self.assertEqual(settings.PMS_PLAN_TIERS, '') + self.assertEqual(ps.get_list('PMS_PLAN_TIERS'), []) + + def test_quality_rank_precedes_stronger_transmission_score(self): + out = self.selected(top_n=1) + self.assertEqual(out['rank_mode'], 'upstream') + self.assertEqual([r['ts_code'] for r in out['items']], ['600001.SH']) + + def test_weak_and_no_transmission_remain_eligible(self): + self.assertEqual(len(self.selected()['items']), 3) + self.assertEqual(self.selected()['dropped']['tier'], 0) + + def test_explicit_tier_override_is_still_honored(self): + self.assertEqual([r['ts_code'] for r in self.selected(tiers=['强传导'])['items']], ['600002.SH']) + + def test_held_black_st_and_display_filters_survive(self): + p = sample() + p['main'] += [dict(p['main'][0], ts_code='600004.SH', name='ST测试'), + dict(p['main'][0], ts_code='600005.SH', verdict='仅展示')] + out = pf.select_candidates(p, rank_by_upstream=True, held=['600001.SH'], + black=['600002.SH'], route_by_verdict=True) + self.assertEqual([r['ts_code'] for r in out['items']], ['600003.SH']) + self.assertEqual([out['dropped'][k] for k in ('held', 'black', 'st', 'display')], [1]*4) + + def test_command_pipeline_keeps_selection_and_research_reference(self): + rows = self.commands() + self.assertEqual(rows[0]['selection_rank'], 1) + self.assertEqual(rows[0]['plan_provenance']['research_rank'], 2) + out = self.plan(rows) + self.assertEqual({r['ts_code'] for r in out['items']}, {'600001.SH'}) + self.assertEqual(out['items'][0]['plan_provenance']['priority_reason'], '沿用候选筛选次序') + + def test_whitelist_outside_plan_precedes_quality_rank(self): + out = self.plan(self.commands(white=['600004.SH'])) + self.assertEqual({r['ts_code'] for r in out['items']}, {'600004.SH'}) + + def test_whitelist_already_in_plan_precedes_quality_rank(self): + rows = self.commands(white=['600002.SH']) + self.assertEqual(len(rows), 3) + out = self.plan(rows) + self.assertEqual({r['ts_code'] for r in out['items']}, {'600002.SH'}) + self.assertEqual(out['items'][0]['plan_provenance']['research_rank'], 9) + self.assertEqual(out['items'][0]['plan_provenance']['priority_reason'], '用户白名单优先') + + def test_whitelist_cannot_override_blacklist_or_existing_holding(self): + rows = self.commands(white=['600002.SH', '600004.SH'], black=['600002.SH'], held=['600004.SH']) + self.assertNotIn('600002.SH', [r['ts_code'] for r in rows]) + self.assertNotIn('600004.SH', [r['ts_code'] for r in rows]) + + def test_legacy_source_without_rank_keeps_score_order(self): + rows = [{'ts_code': '600001.SH', 'score': 1, 'price': 10}, + {'ts_code': '600002.SH', 'score': 2, 'price': 10}] + self.assertEqual({r['ts_code'] for r in self.plan(rows)['items']}, {'600002.SH'}) + + def test_only_legacy_metadata_rank_also_keeps_quality_order(self): + rows = self.commands() + for row in rows: + row.pop('selection_rank') + self.assertEqual({r['ts_code'] for r in self.plan(rows)['items']}, {'600001.SH'}) + + +if __name__ == '__main__': + unittest.main()