选股计划:同质地档按评级升降调整三十日优先级(台账 085)
This commit is contained in:
parent
3d513a2e4f
commit
1278c07421
|
|
@ -120,3 +120,5 @@ MONGO_DB=stock_predictions
|
||||||
# 当晚 22:30 全量扫兜底)。key 填决策系统 .env 的 XXL_TRIGGER_KEY ---
|
# 当晚 22:30 全量扫兜底)。key 填决策系统 .env 的 XXL_TRIGGER_KEY ---
|
||||||
# BIONIC_SCAN_URL=http://192.168.16.188:38000/api/v1/xxl/daily-scan
|
# BIONIC_SCAN_URL=http://192.168.16.188:38000/api/v1/xxl/daily-scan
|
||||||
# BIONIC_SCAN_KEY=
|
# BIONIC_SCAN_KEY=
|
||||||
|
|
||||||
|
# PLAN_RATING_PRIORITY_ENABLED=0 # 基座历史就绪后开启,同质地带内升优降后,30自然日
|
||||||
|
|
|
||||||
5
card.py
5
card.py
|
|
@ -290,7 +290,7 @@ def logic_lines(claims, limit: int = 3) -> list[str]:
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def sort_key(row: dict[str, Any], sort_by_quality=None) -> tuple:
|
def sort_key(row: dict[str, Any], sort_by_quality=None, rating_enabled=False) -> tuple:
|
||||||
"""卡内序:先判决(候选 < 关注 < 仅展示),2026-09-17 起在判决与涨幅之间插入质地带降序
|
"""卡内序:先判决(候选 < 关注 < 仅展示),2026-09-17 起在判决与涨幅之间插入质地带降序
|
||||||
(开关 CARD_SORT_BY_QUALITY,默认开),最后按数据日涨幅降序。开关关掉时元组与旧实现
|
(开关 CARD_SORT_BY_QUALITY,默认开),最后按数据日涨幅降序。开关关掉时元组与旧实现
|
||||||
(先判决再涨幅)逐字相同,逐字回旧。不算总分。"""
|
(先判决再涨幅)逐字相同,逐字回旧。不算总分。"""
|
||||||
|
|
@ -299,6 +299,9 @@ def sort_key(row: dict[str, Any], sort_by_quality=None) -> tuple:
|
||||||
pct0 = _num(row.get("pct0"))
|
pct0 = _num(row.get("pct0"))
|
||||||
pct_key = -(pct0 if pct0 is not None else -1e9)
|
pct_key = -(pct0 if pct0 is not None else -1e9)
|
||||||
if config.CARD_SORT_BY_QUALITY if sort_by_quality is None else sort_by_quality:
|
if config.CARD_SORT_BY_QUALITY if sort_by_quality is None else sort_by_quality:
|
||||||
|
if rating_enabled:
|
||||||
|
import rating_priority
|
||||||
|
return (v, -int(row.get("quality_band") or 0), -rating_priority.key(row.get('company_review')), pct_key)
|
||||||
return (v, -int(row.get("quality_band") or 0), pct_key)
|
return (v, -int(row.get("quality_band") or 0), pct_key)
|
||||||
return (v, pct_key)
|
return (v, pct_key)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -334,3 +334,7 @@ LOGIC_SETTLE_EXIT_DAYS = int(os.environ.get("LOGIC_SETTLE_EXIT_DAYS", "3"))
|
||||||
# 读上一次落定态与近几日原始态时往前看几个自然日。要盖住国庆这种连休八天再加两个周末的空档;
|
# 读上一次落定态与近几日原始态时往前看几个自然日。要盖住国庆这种连休八天再加两个周末的空档;
|
||||||
# 超过这个窗口没记过行的票按第一次见到处理,落定态等于原始态。
|
# 超过这个窗口没记过行的票按第一次见到处理,落定态等于原始态。
|
||||||
LOGIC_STATE_LOOKBACK_DAYS = int(os.environ.get("LOGIC_STATE_LOOKBACK_DAYS", "30"))
|
LOGIC_STATE_LOOKBACK_DAYS = int(os.environ.get("LOGIC_STATE_LOOKBACK_DAYS", "30"))
|
||||||
|
|
||||||
|
# 基座评级历史就绪后开启;保留候选,只在同质地带内改变优先级。
|
||||||
|
PLAN_RATING_PRIORITY_ENABLED = os.environ.get("PLAN_RATING_PRIORITY_ENABLED", "0") == "1"
|
||||||
|
PLAN_RATING_PRIORITY_DAYS = 30
|
||||||
|
|
|
||||||
|
|
@ -892,3 +892,12 @@ PMS 155 镜像 50 批、1165 例通过;桥 54 组契约及池、构建就绪
|
||||||
- **完成与时间口径。** 完成要求真实固定报告引用、成功的买方评议、论点及有效生成时间。七天复核窗口使用真实运行或核对时刻,避免指纹命中后只有核对时间更新而永远无法完成;报告日期仍取原生成时间的北京时间日期。缺引用、材料不全、评议失败或来源不可用均不伪造完成。财报期与原评析重试规则继续由基座负责。
|
- **完成与时间口径。** 完成要求真实固定报告引用、成功的买方评议、论点及有效生成时间。七天复核窗口使用真实运行或核对时刻,避免指纹命中后只有核对时间更新而永远无法完成;报告日期仍取原生成时间的北京时间日期。缺引用、材料不全、评议失败或来源不可用均不伪造完成。财报期与原评析重试规则继续由基座负责。
|
||||||
- **版本与预期。** 规则切换即使输入不变也追加新的完整修订,记录真实截止时刻、参数指纹和变更原因。旧晨版、历史计划及固定版本查询不变。人工关注的研究覆盖与交易资格分开,移除或到期后停止新增关注研究;评析完成不等于可以自动建仓。预期自然回执能分别说明登记、受理、报告完成、日研究和盘中观察状态。
|
- **版本与预期。** 规则切换即使输入不变也追加新的完整修订,记录真实截止时刻、参数指纹和变更原因。旧晨版、历史计划及固定版本查询不变。人工关注的研究覆盖与交易资格分开,移除或到期后停止新增关注研究;评析完成不等于可以自动建仓。预期自然回执能分别说明登记、受理、报告完成、日研究和盘中观察状态。
|
||||||
- **验证与未完成事项。** 开发机新增评析专项 19 项通过;包含本次规则切换的 35 个测试文件均完成配置隔离、禁网验证,其中高股息旧测试的两处相对路径已修复并定向复测。此条记录开发交付和授权边界,不代表运行参数已切换。候选镜像断网回归、155 部署、真实评析受理与完成、自然日研究及盘中观察仍须在发布阶段逐项判收,不注入交易制造结果。
|
- **验证与未完成事项。** 开发机新增评析专项 19 项通过;包含本次规则切换的 35 个测试文件均完成配置隔离、禁网验证,其中高股息旧测试的两处相对路径已修复并定向复测。此条记录开发交付和授权边界,不代表运行参数已切换。候选镜像断网回归、155 部署、真实评析受理与完成、自然日研究及盘中观察仍须在发布阶段逐项判收,不注入交易制造结果。
|
||||||
|
|
||||||
|
|
||||||
|
## 085 · 2026-11-05 · 买方评级变动留痕,同质地档三十日升优降后
|
||||||
|
|
||||||
|
- 日期:2026-11-05,北京时间。用户明确选择降级保留候选,只降低排序优先级。
|
||||||
|
- 改动:正式有效评析版本只追加留痕,保存前后等级、引用和真实时刻。首次覆盖为基线,同级不续期,最新升降覆盖当前排序方向。30个自然日内同质地档升级优先、降级后置,届满恢复普通排序;原始分数和建仓资格不变。
|
||||||
|
- 依据:当前评析索引会覆盖同报告期旧内容,仅比较持仓或相邻日榜无法完整记录变动。用户要求沿用质地排序,人工关注继续研究,建仓通过三源合议。此次排序不覆盖已上线的降级清仓与人工限制。
|
||||||
|
- 预期:每个正式固定报告只保存一次,失败或缺资料不伪装降级。选股固定截止时间和输入,五分钟自然修订识别期限届满。PMS继承上游名次,纯排序更新不重复发起模型研判。旧晨版和历史账本保留。
|
||||||
|
- 复核日期:发布当天核查表、镜像、参数与基线;首个自然升降事件到达后核查证据链及排序。部署与自然判收分别记录,不新增长期观察任务。详见同名规格与接续文档。
|
||||||
|
|
|
||||||
13
plan.py
13
plan.py
|
|
@ -26,6 +26,7 @@ import re
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
import card
|
import card
|
||||||
|
import rating_priority
|
||||||
import common
|
import common
|
||||||
import config
|
import config
|
||||||
import judgement
|
import judgement
|
||||||
|
|
@ -173,7 +174,8 @@ def _rerank_by_axis(ranked, cards: dict, axis: str, stale_days: int, has_tier: b
|
||||||
group = s - 200.0 - tier * 20.0 # 剥掉档位:传导档位不进次序
|
group = s - 200.0 - tier * 20.0 # 剥掉档位:传导档位不进次序
|
||||||
else:
|
else:
|
||||||
group = s # 观察档无档位,带内直接按原始分
|
group = s # 观察档无档位,带内直接按原始分
|
||||||
return (-int(band), not pointed, -group, -s, k) # 每层升序排,负号即降序
|
priority = rating_priority.key(c.get('company_review')) if config.PLAN_RATING_PRIORITY_ENABLED else 0
|
||||||
|
return (-int(band), -priority, not pointed, -group, -s, k) # 每层升序排,负号即降序
|
||||||
|
|
||||||
order = [k for k, _ in sorted(ranked.items(), key=_key)]
|
order = [k for k, _ in sorted(ranked.items(), key=_key)]
|
||||||
return ranked.reindex(order)
|
return ranked.reindex(order)
|
||||||
|
|
@ -471,7 +473,7 @@ def _assemble_cards(ds: str, codes: list, ev: dict, upside: pd.Series,
|
||||||
"pressure": n.get("pressure"), "date": n.get("conclusion_date")}
|
"pressure": n.get("pressure"), "date": n.get("conclusion_date")}
|
||||||
if n else None),
|
if n else None),
|
||||||
}
|
}
|
||||||
for i, (k, c) in enumerate(sorted(cards.items(), key=lambda kv: (*card.sort_key(kv[1], config.CARD_SORT_BY_QUALITY), kv[0])), 1):
|
for i, (k, c) in enumerate(sorted(cards.items(), key=lambda kv: (*card.sort_key(kv[1], config.CARD_SORT_BY_QUALITY, config.PLAN_RATING_PRIORITY_ENABLED), kv[0])), 1):
|
||||||
c["card_rank"] = i
|
c["card_rank"] = i
|
||||||
|
|
||||||
segs: dict = {}
|
segs: dict = {}
|
||||||
|
|
@ -647,7 +649,9 @@ def collect(date: str | None = None, top: int = 20, obs_top: int = 10,
|
||||||
industry_catalyst_text=c.get("industry_catalyst_text"),
|
industry_catalyst_text=c.get("industry_catalyst_text"),
|
||||||
# 公司深度(2026-09-09 接入方案):质地档与评议摘要,原值给程序,整句给人;
|
# 公司深度(2026-09-09 接入方案):质地档与评议摘要,原值给程序,整句给人;
|
||||||
# 质地进逻辑状态第五路与判决收敛(只降不升),评议文字只给人看与送研判。
|
# 质地进逻辑状态第五路与判决收敛(只降不升),评议文字只给人看与送研判。
|
||||||
company_review=c.get("company_review"), company_review_text=c.get("company_review_text"),
|
company_review=({key: value for key, value in c['company_review'].items() if key != 'rating_priority'} if c.get('company_review') else None),
|
||||||
|
rating_priority=(c.get('company_review') or {}).get('rating_priority'),
|
||||||
|
company_review_text=c.get("company_review_text"),
|
||||||
company_gate=c.get("company_gate"),
|
company_gate=c.get("company_gate"),
|
||||||
card={"pct0": c.get("pct0"), "net_z": c.get("net_z"),
|
card={"pct0": c.get("pct0"), "net_z": c.get("net_z"),
|
||||||
"heat_chg": c.get("heat_chg"), "accum": c.get("accum"),
|
"heat_chg": c.get("heat_chg"), "accum": c.get("accum"),
|
||||||
|
|
@ -807,7 +811,10 @@ def collect(date: str | None = None, top: int = 20, obs_top: int = 10,
|
||||||
out[b] = out.get(b, 0) + 1
|
out[b] = out.get(b, 0) + 1
|
||||||
return out
|
return out
|
||||||
result["rank_axis"] = axis
|
result["rank_axis"] = axis
|
||||||
|
result["rating_priority_policy"] = {"enabled": config.PLAN_RATING_PRIORITY_ENABLED, "days": config.PLAN_RATING_PRIORITY_DAYS}
|
||||||
result["rank_rule"] = "质地带(好3中2无评析1差0)降序 → 带内被指向优先 → 组内分 → 原始分 → 代码"
|
result["rank_rule"] = "质地带(好3中2无评析1差0)降序 → 带内被指向优先 → 组内分 → 原始分 → 代码"
|
||||||
|
if config.PLAN_RATING_PRIORITY_ENABLED:
|
||||||
|
result['rank_rule'] = result['rank_rule'].replace('带内被指向优先', '带内近30天评级上调优先、下调后置,再按被指向优先')
|
||||||
result["quality_band_counts"] = {"main": _band_counts(result["_full"]["main"]),
|
result["quality_band_counts"] = {"main": _band_counts(result["_full"]["main"]),
|
||||||
"observe": _band_counts(result["_full"]["observe"])}
|
"observe": _band_counts(result["_full"]["observe"])}
|
||||||
return result
|
return result
|
||||||
|
|
|
||||||
|
|
@ -113,7 +113,11 @@ class Bundle:
|
||||||
try:
|
try:
|
||||||
actual = dict(kw)
|
actual = dict(kw)
|
||||||
if name == 'sources.company_reviews':
|
if name == 'sources.company_reviews':
|
||||||
actual.update(cutoff_at=self.cutoff_at, strict=True)
|
import config
|
||||||
|
actual.update(cutoff_at=self.cutoff_at, strict=True,
|
||||||
|
include_rating=self.params.get('PLAN_RATING_PRIORITY_ENABLED', False) if self.replay else
|
||||||
|
self.params.get('PLAN_RATING_PRIORITY_ENABLED', config.PLAN_RATING_PRIORITY_ENABLED),
|
||||||
|
rating_days=self.params.get('PLAN_RATING_PRIORITY_DAYS', 30))
|
||||||
result = fn(*args, **actual)
|
result = fn(*args, **actual)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.records[key] = {'name': name, 'error': type(e).__name__, 'args': pack([args, kw])}
|
self.records[key] = {'name': name, 'error': type(e).__name__, 'args': pack([args, kw])}
|
||||||
|
|
|
||||||
|
|
@ -52,6 +52,9 @@ def refresh(day=None, *, now=None, regime_value=None):
|
||||||
if policy_changed:
|
if policy_changed:
|
||||||
params['CARD_ACCUM_CONFIRM_REQUIRED'] = desired_confirm
|
params['CARD_ACCUM_CONFIRM_REQUIRED'] = desired_confirm
|
||||||
pending.update(r['code'] for b in ('main', 'observe') for r in old.get(b, []))
|
pending.update(r['code'] for b in ('main', 'observe') for r in old.get(b, []))
|
||||||
|
rating_changed = params.get('PLAN_RATING_PRIORITY_ENABLED', False) != config.PLAN_RATING_PRIORITY_ENABLED
|
||||||
|
params['PLAN_RATING_PRIORITY_ENABLED'] = config.PLAN_RATING_PRIORITY_ENABLED
|
||||||
|
params['PLAN_RATING_PRIORITY_DAYS'] = config.PLAN_RATING_PRIORITY_DAYS
|
||||||
inputs = copy.deepcopy(env['inputs'])
|
inputs = copy.deepcopy(env['inputs'])
|
||||||
import user_candidates as uc
|
import user_candidates as uc
|
||||||
selected = uc.active(root, now)
|
selected = uc.active(root, now)
|
||||||
|
|
@ -76,7 +79,8 @@ def refresh(day=None, *, now=None, regime_value=None):
|
||||||
# 读取失败时无法确定哪些股票变化,保守暂停整个本次观察范围。
|
# 读取失败时无法确定哪些股票变化,保守暂停整个本次观察范围。
|
||||||
pending.update(args[0])
|
pending.update(args[0])
|
||||||
pv.health(root, day, pending_codes=sorted(pending), error=None)
|
pv.health(root, day, pending_codes=sorted(pending), error=None)
|
||||||
after = sources.company_reviews(*args, **dict(kw, cutoff_at=now.isoformat(), strict=True))
|
after = sources.company_reviews(*args, **dict(kw, cutoff_at=now.isoformat(), strict=True,
|
||||||
|
include_rating=params['PLAN_RATING_PRIORITY_ENABLED'], rating_days=params['PLAN_RATING_PRIORITY_DAYS']))
|
||||||
pending.difference_update(args[0])
|
pending.difference_update(args[0])
|
||||||
pending.update(c for c in set(before) | set(after) if before.get(c) != after.get(c))
|
pending.update(c for c in set(before) | set(after) if before.get(c) != after.get(c))
|
||||||
rec.pop('error', None)
|
rec.pop('error', None)
|
||||||
|
|
@ -90,7 +94,7 @@ def refresh(day=None, *, now=None, regime_value=None):
|
||||||
if policy_changed:
|
if policy_changed:
|
||||||
pending.update(r['code'] for b in ('main', 'observe') for r in old.get(b, []))
|
pending.update(r['code'] for b in ('main', 'observe') for r in old.get(b, []))
|
||||||
pv.health(root, day, pending_codes=sorted(pending), error=None)
|
pv.health(root, day, pending_codes=sorted(pending), error=None)
|
||||||
if pv.digest(inputs) == old['decision']['input_hash'] and not policy_changed:
|
if pv.digest(inputs) == old['decision']['input_hash'] and not policy_changed and not rating_changed:
|
||||||
pv.health(root, day, pending_codes=[], error=None, decision_id=old['decision']['id'])
|
pv.health(root, day, pending_codes=[], error=None, decision_id=old['decision']['id'])
|
||||||
return {'status': 'unchanged', 'decision': old['decision']}
|
return {'status': 'unchanged', 'decision': old['decision']}
|
||||||
bundle = pi.Bundle(records=None if candidates_changed else inputs['records'],
|
bundle = pi.Bundle(records=None if candidates_changed else inputs['records'],
|
||||||
|
|
@ -108,6 +112,10 @@ def refresh(day=None, *, now=None, regime_value=None):
|
||||||
regime=inputs.get('regime'))
|
regime=inputs.get('regime'))
|
||||||
reason = ('恢复吸筹确认规则' if desired_confirm else '吸筹改为三源合议参考') if policy_changed else (
|
reason = ('恢复吸筹确认规则' if desired_confirm else '吸筹改为三源合议参考') if policy_changed else (
|
||||||
'用户候选更新' if candidates_changed else '评析更新' if pending else '市场区制更新')
|
'用户候选更新' if candidates_changed else '评析更新' if pending else '市场区制更新')
|
||||||
|
if rating_changed:
|
||||||
|
reason = '启用评级变动三十日排序' if config.PLAN_RATING_PRIORITY_ENABLED else '关闭评级变动排序'
|
||||||
|
elif config.PLAN_RATING_PRIORITY_ENABLED and pending:
|
||||||
|
reason = '评析或评级排序期限更新'
|
||||||
published = pv.publish(root, data, inputs, params, cutoff_at=now.isoformat(), reason=reason)
|
published = pv.publish(root, data, inputs, params, cutoff_at=now.isoformat(), reason=reason)
|
||||||
plan.write_published_md(published)
|
plan.write_published_md(published)
|
||||||
return {'status': 'published', 'decision': published['decision']}
|
return {'status': 'published', 'decision': published['decision']}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
"""评级变化只影响同质地档排序;计算严格使用计划截止时间,时间不混入评分。"""
|
||||||
|
import datetime as dt
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
|
GRADES={'差':0,'中':1,'好':2}
|
||||||
|
def stamp(value):
|
||||||
|
result=dt.datetime.fromisoformat(str(value).replace('Z','+00:00'))
|
||||||
|
if result.tzinfo is None: raise ValueError('评级时刻必须包含时区')
|
||||||
|
return result
|
||||||
|
|
||||||
|
def evaluate(review, history, cutoff_at, days=30):
|
||||||
|
result={'priority':0,'status':'missing_history','window_days':days,'change':None,'expires_at':None}
|
||||||
|
if not isinstance(history,dict): return result
|
||||||
|
if (review.get('qual')!='ok' or review.get('brain_status')!='ok'
|
||||||
|
or review.get('overall') not in GRADES):
|
||||||
|
return {**result,'status':'invalid_review'}
|
||||||
|
if history.get('review_ref')!=review.get('review_ref') or history.get('grade')!=review.get('overall'):
|
||||||
|
return {**result,'status':'history_mismatch'}
|
||||||
|
try:
|
||||||
|
edge=stamp(cutoff_at)
|
||||||
|
head=stamp(history['report_ran_at'])
|
||||||
|
if head>edge or stamp(history['recorded_at'])>edge:
|
||||||
|
return {**result,'status':'future_history'}
|
||||||
|
change=history.get('last_change_json')
|
||||||
|
if isinstance(change,str): change=json.loads(change)
|
||||||
|
result['history_event_id']=history['event_id']
|
||||||
|
if not change: return {**result,'status':'baseline'}
|
||||||
|
before,after=change['before'],change['after']
|
||||||
|
direction='up' if GRADES[after]>GRADES[before] else 'down' if GRADES[after]<GRADES[before] else 'same'
|
||||||
|
if (direction not in ('up','down') or direction!=change['direction'] or after!=history['grade']
|
||||||
|
or any(not re.fullmatch('[0-9a-f]{64}',str(change.get(k) or '')) for k in ('event_id','before_ref','after_ref'))):
|
||||||
|
raise ValueError('升降记录不完整')
|
||||||
|
at=stamp(change['at'])
|
||||||
|
if at>head: raise ValueError('升降发生在报告之后')
|
||||||
|
expires=at+dt.timedelta(days=days)
|
||||||
|
active=at<=edge<expires
|
||||||
|
return {**result,'priority':(1 if direction=='up' else -1) if active else 0,
|
||||||
|
'status':'active' if active else 'expired','change':change,'expires_at':expires.isoformat()}
|
||||||
|
except (ValueError,TypeError,KeyError):
|
||||||
|
return {**result,'status':'invalid_history'}
|
||||||
|
|
||||||
|
def key(review):
|
||||||
|
value=(review or {}).get('rating_priority') or {}
|
||||||
|
return int(value.get('priority') or 0) if value.get('status')=='active' else 0
|
||||||
17
sources.py
17
sources.py
|
|
@ -1180,12 +1180,12 @@ def catalysts_for_codes(seg_of: dict, cat_by_seg: dict, *, limit: int = 3) -> di
|
||||||
# 公司深度评析(2026-09-09 接入方案,台账 053):数据基座 company_review_runs 索引表最新一行的摘要。
|
# 公司深度评析(2026-09-09 接入方案,台账 053):数据基座 company_review_runs 索引表最新一行的摘要。
|
||||||
# 质地由基座代码合成,这里只读不算;报告正文在对象存储,链接给人。表读不到整体缺席不断产。
|
# 质地由基座代码合成,这里只读不算;报告正文在对象存储,链接给人。表读不到整体缺席不断产。
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
def company_reviews(codes, ds: str, *, read_pg=None, cutoff_at=None, strict=False, include_check=False) -> dict:
|
def company_reviews(codes, ds: str, *, read_pg=None, cutoff_at=None, strict=False, include_check=False, include_rating=None, rating_days=30) -> dict:
|
||||||
"""{前缀码: {"period", "review_version", "overall", "groups", "valuation", "doubt_hard", "quality_reasons",
|
"""{前缀码: {"period", "review_version", "overall", "groups", "valuation", "doubt_hard", "quality_reasons",
|
||||||
"grade_counts", "grade_line", "thesis", "confidence", "invalidation", "antithesis", "catalyst", "brain_status",
|
"grade_counts", "grade_line", "thesis", "confidence", "invalidation", "antithesis", "catalyst", "brain_status",
|
||||||
"ran_at", "age_days", "report_url"}};没报告的票不在字典里。"""
|
"ran_at", "age_days", "report_url"}};没报告的票不在字典里。"""
|
||||||
rp = read_pg or db.read_pg
|
rp = read_pg or db.read_pg
|
||||||
want = sorted({c for c in (codes or []) if c})
|
want = sorted({_prefix_any(str(c)) for c in (codes or []) if re.fullmatch(r'(?:SH(?:60|68)|SZ(?:00|30))\d{4}', _prefix_any(str(c)))})
|
||||||
if not want:
|
if not want:
|
||||||
return {}
|
return {}
|
||||||
dots = [_to_dot(c) for c in want]
|
dots = [_to_dot(c) for c in want]
|
||||||
|
|
@ -1232,6 +1232,8 @@ def company_reviews(codes, ds: str, *, read_pg=None, cutoff_at=None, strict=Fals
|
||||||
except (TypeError, ValueError, AttributeError):
|
except (TypeError, ValueError, AttributeError):
|
||||||
ran_day, age = None, None
|
ran_day, age = None, None
|
||||||
k = _prefix_any(str(r.get("ts_code")))
|
k = _prefix_any(str(r.get("ts_code")))
|
||||||
|
if k not in want:
|
||||||
|
continue
|
||||||
brain = sm.get("brain") or {}
|
brain = sm.get("brain") or {}
|
||||||
if age is not None and age < 0:
|
if age is not None and age < 0:
|
||||||
age = 0 # 报告运行日晚于数据日(今早刚跑):算零天,不算负数
|
age = 0 # 报告运行日晚于数据日(今早刚跑):算零天,不算负数
|
||||||
|
|
@ -1261,6 +1263,17 @@ def company_reviews(codes, ds: str, *, read_pg=None, cutoff_at=None, strict=Fals
|
||||||
out[k]['checked_at'] = None
|
out[k]['checked_at'] = None
|
||||||
out[k]['report_version_url'] = (config.AKG_API_BASE + sm['report_version_path']
|
out[k]['report_version_url'] = (config.AKG_API_BASE + sm['report_version_path']
|
||||||
if sm.get('report_version_path') else None)
|
if sm.get('report_version_path') else None)
|
||||||
|
enabled = config.PLAN_RATING_PRIORITY_ENABLED if include_rating is None else include_rating
|
||||||
|
if enabled and out:
|
||||||
|
import rating_priority
|
||||||
|
# 两张表分开读取,不联表。读取失败不能当作评级下降或静默发布新榜。
|
||||||
|
history = rp("SELECT DISTINCT ON (ts_code) ts_code, event_id, review_ref, grade, report_ran_at, "
|
||||||
|
"recorded_at, last_change_json FROM company_review_rating_history "
|
||||||
|
"WHERE ts_code = ANY(%s) AND report_ran_at <= %s AND recorded_at <= %s "
|
||||||
|
"ORDER BY ts_code, report_ran_at DESC, recorded_at DESC, event_id DESC", (dots, cutoff, cutoff))
|
||||||
|
by_code = {_prefix_any(str(r['ts_code'])): r for r in history.to_dict('records')}
|
||||||
|
for code, value in out.items():
|
||||||
|
value['rating_priority'] = rating_priority.evaluate(value, by_code.get(code), cutoff, rating_days)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,121 @@
|
||||||
|
"""离线:30日边界、证据与同档排序,真实刷新路径及固定版本重放。"""
|
||||||
|
import copy
|
||||||
|
import datetime as dt
|
||||||
|
from contextlib import ExitStack
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
import pandas as pd
|
||||||
|
import test_plan_versions as fixture
|
||||||
|
import sources, config, plan, plan_inputs as pi, plan_versions as pv, plan_refresh
|
||||||
|
import rating_priority as rating
|
||||||
|
import card
|
||||||
|
|
||||||
|
AT='2026-10-06T01:00:00+00:00'
|
||||||
|
EDGE='2026-11-05T09:00:00+08:00'
|
||||||
|
def review(grade='中'):
|
||||||
|
return {'overall':grade,'qual':'ok','brain_status':'ok','review_ref':'b'*64,'age_days':1}
|
||||||
|
def history():
|
||||||
|
return {'ts_code':'600001.SH','review_ref':'b'*64,'grade':'中','event_id':'b'*64,
|
||||||
|
'report_ran_at':AT,'recorded_at':AT,'last_change_json':{'event_id':'b'*64,
|
||||||
|
'direction':'down','before':'好','after':'中','before_ref':'a'*64,'after_ref':'b'*64,'at':AT}}
|
||||||
|
|
||||||
|
class PriorityTest(unittest.TestCase):
|
||||||
|
def test_boundary_timezone_same_grade_and_latest(self):
|
||||||
|
before=dt.datetime.fromisoformat(EDGE)-dt.timedelta(microseconds=1)
|
||||||
|
a=rating.evaluate(review(),history(),before.isoformat())
|
||||||
|
self.assertEqual(a['priority'],-1)
|
||||||
|
self.assertEqual(rating.evaluate(review(),history(),EDGE)['priority'],0)
|
||||||
|
same=history();same.update(review_ref='c'*64,report_ran_at='2026-11-04T01:00:00+00:00')
|
||||||
|
r={**review(),'review_ref':'c'*64}
|
||||||
|
self.assertEqual(rating.evaluate(r,same,EDGE)['status'],'expired')
|
||||||
|
self.assertEqual(a,rating.evaluate(review(),history(),before.astimezone(dt.timezone.utc).isoformat()))
|
||||||
|
up=history();up['grade']='好';up['last_change_json'].update(direction='up',before='中',after='好',at='2026-11-04T01:00:00+00:00')
|
||||||
|
up['report_ran_at']='2026-11-04T01:00:00+00:00'
|
||||||
|
self.assertEqual(rating.evaluate(review('好'),up,EDGE)['priority'],1)
|
||||||
|
def test_baseline_missing_invalid_and_future(self):
|
||||||
|
self.assertEqual(rating.evaluate(review(),None,EDGE)['status'],'missing_history')
|
||||||
|
h=history();h['last_change_json']=None
|
||||||
|
self.assertEqual(rating.evaluate(review(),h,EDGE)['status'],'baseline')
|
||||||
|
for modified in ({'qual':'error'},{'brain_status':'timeout'},{'review_ref':'c'*64},{'overall':'证据不足'}):
|
||||||
|
self.assertEqual(rating.evaluate({**review(),**modified},history(),EDGE)['priority'],0)
|
||||||
|
for field in ('recorded_at','report_ran_at'):
|
||||||
|
self.assertEqual(rating.evaluate(review(),{**history(),field:'2027-01-01T00:00:00Z'},EDGE)['status'],'future_history')
|
||||||
|
h=history();h['last_change_json']['before_ref']='invalid'
|
||||||
|
self.assertEqual(rating.evaluate(review(),h,EDGE)['status'],'invalid_history')
|
||||||
|
def test_quality_first_candidates_retained_scores_unchanged_and_flag_off(self):
|
||||||
|
ranked=pd.Series({'good':200.,'up':201.,'neutral':209.,'down':210.})
|
||||||
|
cards={k:{'verdict':'候选','quality_band':3 if k=='good' else 2,'gates':{'pointed':True},
|
||||||
|
'company_review':{'rating_priority':{'status':'active','priority':{'up':1,'down':-1}.get(k,0)}}} for k in ranked.index}
|
||||||
|
with patch.object(config,'PLAN_RATING_PRIORITY_ENABLED',True):
|
||||||
|
out=plan._rerank_by_axis(ranked,cards,'quality',120,True)
|
||||||
|
self.assertEqual(list(out.index),['good','up','neutral','down'])
|
||||||
|
self.assertEqual(out.to_dict(),ranked.to_dict())
|
||||||
|
self.assertTrue(all(c['verdict']=='候选' for c in cards.values()))
|
||||||
|
order=sorted(cards,key=lambda k:card.sort_key(cards[k],True,True))
|
||||||
|
self.assertEqual(order,['good','up','neutral','down'])
|
||||||
|
with patch.object(config,'PLAN_RATING_PRIORITY_ENABLED',False):
|
||||||
|
self.assertEqual(list(plan._rerank_by_axis(ranked,cards,'quality',120,True).index),['good','neutral','up','down'])
|
||||||
|
def test_source_separate_tables_scope_failure_and_match(self):
|
||||||
|
calls=[]
|
||||||
|
def read(sql,args):
|
||||||
|
calls.append((sql,args));self.assertNotIn('JOIN',sql)
|
||||||
|
self.assertEqual(args[0],['600001.SH'])
|
||||||
|
if 'company_review_runs' in sql:
|
||||||
|
return pd.DataFrame([{'ts_code':'600001.SH','summary':review(),'brain_status':'ok','ran_at':AT}])
|
||||||
|
return pd.DataFrame([history()])
|
||||||
|
rows=sources.company_reviews(['SH600001','920001.BJ'],'2026-11-04',read_pg=read,cutoff_at=EDGE,include_rating=True)
|
||||||
|
self.assertEqual(len(calls),2)
|
||||||
|
self.assertEqual(rows['SH600001']['rating_priority']['status'],'expired')
|
||||||
|
with self.assertRaises(OSError):
|
||||||
|
sources.company_reviews(['SH600001'],'2026-11-04',read_pg=lambda sql,args: read(sql,args) if 'company_review_runs' in sql else (_ for _ in ()).throw(OSError('history unavailable')),cutoff_at=EDGE,include_rating=True)
|
||||||
|
def test_frozen_replay_does_not_read_or_expire(self):
|
||||||
|
source=lambda *a,**kw: {'SH600001':{**review(),'rating_priority':rating.evaluate(review(),history(),kw['cutoff_at'])}}
|
||||||
|
bundle=pi.Bundle(params={'PLAN_RATING_PRIORITY_ENABLED':True},cutoff_at='2026-11-05T08:59:00+08:00')
|
||||||
|
value=bundle.call('sources.company_reviews',source,(['SH600001'],'2026-11-04'),{})
|
||||||
|
replay=pi.Bundle(records=bundle.records,params=bundle.params,cutoff_at='2030-01-01T00:00:00Z')
|
||||||
|
again=replay.call('sources.company_reviews',lambda *a,**kw:self.fail('回源'),(['SH600001'],'2026-11-04'),{})
|
||||||
|
self.assertEqual(value,again)
|
||||||
|
self.assertEqual(again['SH600001']['rating_priority']['priority'],-1)
|
||||||
|
|
||||||
|
class RefreshTest(unittest.TestCase):
|
||||||
|
def test_expiration_publishes_once_and_keeps_morning(self):
|
||||||
|
import factors, judgement, logic_state_daily
|
||||||
|
codes=['SH600001','SH600002'];day='2026-11-04';cut='2026-11-05T08:59:00+08:00'
|
||||||
|
with tempfile.TemporaryDirectory() as root, ExitStack() as stack:
|
||||||
|
def stub(obj,name,**kw):return stack.enter_context(patch.object(obj,name,**kw))
|
||||||
|
stub(config,'PLAN_SNAPSHOT_DIR',new=root)
|
||||||
|
stub(config,'PLAN_RATING_PRIORITY_ENABLED',new=True)
|
||||||
|
stub(config,'PLAN_RANK_AXIS',new='quality')
|
||||||
|
stub(plan,'_factor',side_effect=lambda table,day:pd.Series([240.,230.] if 'score' in table else [.3,.2] if 'upside' in table else [2.,2.],index=codes))
|
||||||
|
stub(plan,'_latest_date',return_value=day);stub(plan,'_prev_date',return_value=None)
|
||||||
|
stub(plan,'_names',return_value=dict(zip(codes,['甲','乙'])))
|
||||||
|
stub(plan,'_evidence',return_value=({c:('材料',3,.1,10,1) for c in codes},{day}))
|
||||||
|
stub(plan,'_segments_of',return_value={});stub(factors,'_risk_set',return_value=set())
|
||||||
|
stub(judgement,'load_previous',return_value=[]);stub(judgement,'recent_rows',return_value={})
|
||||||
|
stub(logic_state_daily,'history',return_value={})
|
||||||
|
for name in ('moved_members','broker_reports','logic_claims','broker_actions','close_prices','valuation_scenarios','analyst_events','event_day_fields','news_flashes','segment_catalysts','catalysts_for_codes'):
|
||||||
|
stub(sources,name,return_value={})
|
||||||
|
stub(sources,'stock_daily',return_value={c:{'pct0':3} for c in codes})
|
||||||
|
stub(sources,'night_conclusions',return_value={c:{'accum_state':'明确吸筹','accum_age':0} for c in codes})
|
||||||
|
def read(*a,**kw):
|
||||||
|
return {c:{**review(),'rating_priority':rating.evaluate(review(),history() if i==0 else None,kw['cutoff_at'])} for i,c in enumerate(codes)}
|
||||||
|
stub(sources,'company_reviews',side_effect=read)
|
||||||
|
b=pi.Bundle(params=pi.effective_config(config),cutoff_at=cut)
|
||||||
|
with b.use(): data=plan.collect(day)
|
||||||
|
data.update(data.pop('_full'))
|
||||||
|
with pv.writer(root):morning=pv.publish(root,data,{'records':b.records,'market':{},'regime':None},b.params,cutoff_at=cut,reason='晨版')
|
||||||
|
self.assertEqual(morning['main'][0]['code'],codes[1])
|
||||||
|
stub(plan_refresh,'in_window',return_value=True)
|
||||||
|
self.assertEqual(plan_refresh.refresh(now=dt.datetime.fromisoformat(EDGE))['status'],'published')
|
||||||
|
latest=pv.load(root,day)
|
||||||
|
self.assertEqual(latest['main'][0]['code'],codes[0])
|
||||||
|
self.assertEqual(latest['main'][0]['rating_priority']['status'],'expired')
|
||||||
|
self.assertNotIn('rating_priority',latest['main'][0]['company_review'])
|
||||||
|
self.assertEqual(pv.load(root,day,morning=True),morning)
|
||||||
|
self.assertEqual(plan_refresh.refresh(now=dt.datetime.fromisoformat(EDGE)+dt.timedelta(minutes=5))['status'],'unchanged')
|
||||||
|
stub(config,'PLAN_RATING_PRIORITY_ENABLED',new=False)
|
||||||
|
self.assertEqual(plan_refresh.refresh(now=dt.datetime.fromisoformat(EDGE)+dt.timedelta(minutes=10))['status'],'published')
|
||||||
|
self.assertFalse(pv.load(root,day)['rating_priority_policy']['enabled'])
|
||||||
|
|
||||||
|
if __name__=='__main__':unittest.main()
|
||||||
Loading…
Reference in New Issue