116 lines
5.2 KiB
Python
116 lines
5.2 KiB
Python
"""个股深度评析的目标名单(2026-09-09 方案附录甲):每早出计划时把主榜与观察档写进 153 库一张小表,
|
||
数据基座的 00:45 任务读它选目标(178 的容器打不到 155 的接口,只能走库)。
|
||
|
||
表 t_akg_review_targets:plan_date、ts_code(点后缀式 600000.SH)、source(main / observe / manual)、rank、name。
|
||
幂等:删该日行再整批插。写失败不拦计划(try 包住)。"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
|
||
import config
|
||
import db
|
||
|
||
TABLE = os.environ.get("REVIEW_TARGETS_TABLE", "t_akg_review_targets")
|
||
TOP_MAIN = int(os.environ.get("REVIEW_TARGETS_MAIN", "100")) # 主榜按原始分前一百只(跟着雷达走)
|
||
TOP_MAIN_RANK = int(os.environ.get("REVIEW_TARGETS_MAIN_RANK", "50")) # 主榜按新序前五十只(好公司报告保持新鲜)
|
||
TOP_OBS = int(os.environ.get("REVIEW_TARGETS_OBS", "20")) # 观察档前二十只
|
||
COLUMNS = ("plan_date", "ts_code", "source", "rank", "name")
|
||
_CREATE = """
|
||
CREATE TABLE IF NOT EXISTS {t} (
|
||
plan_date DATE NOT NULL,
|
||
ts_code VARCHAR(16) NOT NULL,
|
||
source VARCHAR(16) NOT NULL,
|
||
`rank` INT NOT NULL,
|
||
name VARCHAR(64),
|
||
PRIMARY KEY (plan_date, ts_code)
|
||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||
"""
|
||
|
||
|
||
def to_dot(code: str) -> str:
|
||
s = (code or "").strip().upper()
|
||
if len(s) == 8 and s[:2] in ("SH", "SZ", "BJ") and s[2:].isdigit():
|
||
return f"{s[2:]}.{s[:2]}"
|
||
return s
|
||
|
||
|
||
def build_rows(ds: str, main_rows: list, obs_rows: list, user_rows=None) -> list[dict]:
|
||
from user_candidates import normalize
|
||
seen: set = set()
|
||
out: list[dict] = []
|
||
for src, rows in (("main", main_rows), ("observe", obs_rows), ("manual", user_rows)):
|
||
for i, r in enumerate(rows or [], 1):
|
||
try:
|
||
code = to_dot(normalize(r.get('code')))
|
||
except ValueError:
|
||
continue
|
||
if code in seen:
|
||
continue
|
||
seen.add(code)
|
||
out.append({"plan_date": ds, "ts_code": code, "source": src, "rank": i, "name": (r.get("name") or "")[:64]})
|
||
return out
|
||
|
||
|
||
def save(ds: str, rows: list, conn_factory=None) -> None:
|
||
factory = conn_factory or db.factor_conn
|
||
cols = ",".join(f"`{c}`" for c in COLUMNS)
|
||
marks = ",".join(["%s"] * len(COLUMNS))
|
||
payload = [tuple(r.get(c) for c in COLUMNS) for r in rows]
|
||
with factory() as conn:
|
||
with conn.cursor() as cur:
|
||
cur.execute(_CREATE.format(t=TABLE))
|
||
conn.commit()
|
||
with conn.cursor() as cur:
|
||
cur.execute(f"DELETE FROM {TABLE} WHERE plan_date = %s", (ds,))
|
||
if payload:
|
||
cur.executemany(f"INSERT INTO {TABLE} ({cols}) VALUES ({marks})", payload)
|
||
conn.commit()
|
||
|
||
|
||
def pick_main_targets(main_rows: list, axis: str, top_score: int, top_rank: int) -> list:
|
||
"""评析目标名单的主榜取法(纯函数,2026-09-17)。评析覆盖不能被排序轴锁死——只取新序前列的话,
|
||
新被指向的公司永远排在已评析公司后面、永远拿不到报告,所以名单要与排序轴解耦。
|
||
|
||
both(默认):按 score 降序前 top_score(跟着雷达走)∪ 按 rank 升序前 top_rank(好公司报告保持新鲜),
|
||
去重后按 rank 升序排。score:只按 score 降序前 top_score(逐字回旧)。"""
|
||
def _score(r):
|
||
return -(r.get("score") or 0.0)
|
||
|
||
def _rank(r):
|
||
return r.get("rank") if r.get("rank") is not None else 1 << 60
|
||
|
||
if axis != "both":
|
||
return sorted(main_rows, key=_score)[:top_score]
|
||
seen: set = set()
|
||
union: list = []
|
||
for r in sorted(main_rows, key=_score)[:top_score] + sorted(main_rows, key=_rank)[:top_rank]:
|
||
code = r.get("code")
|
||
if code not in seen:
|
||
seen.add(code)
|
||
union.append(r)
|
||
union.sort(key=_rank)
|
||
return union
|
||
|
||
|
||
def persist(ds: str, snap: dict, write=None, user_rows=None) -> dict:
|
||
"""目标是主榜(按 REVIEW_TARGETS_AXIS 取,both 是原始分前 TOP_MAIN ∪ 新序前 TOP_MAIN_RANK)加观察档前
|
||
TOP_OBS 只(快照里的 main / observe 已是新序全部行,每行带 score 与 rank),约一百二十到一百五十家。"""
|
||
main_sel = pick_main_targets(snap.get("main") or [], config.REVIEW_TARGETS_AXIS, TOP_MAIN, TOP_MAIN_RANK)
|
||
rows = build_rows(ds, main_sel, (snap.get("observe") or [])[:TOP_OBS],
|
||
snap.get('user_candidates', []) if user_rows is None else user_rows)
|
||
(write or save)(ds, rows)
|
||
n_main = sum(1 for r in rows if r["source"] == "main")
|
||
n_manual = sum(1 for r in rows if r['source'] == 'manual')
|
||
n_obs = len(rows) - n_main - n_manual
|
||
print(f" 评析目标名单 {ds}:主榜 {n_main},观察 {n_obs},人工关注 {n_manual},写入 {TABLE}")
|
||
return {"date": ds, "rows": len(rows), "main": n_main, 'observe': n_obs, 'manual': n_manual}
|
||
|
||
|
||
def from_plan_file(ds: str, plan_dir: str | None = None, write=None) -> dict:
|
||
"""从已生成的计划文件补写(手工入口 run.py review-targets --date)。"""
|
||
path = os.path.join(plan_dir or config.PLAN_SNAPSHOT_DIR, f"plan_{ds}.json")
|
||
with open(path, encoding="utf-8") as f:
|
||
snap = json.load(f)
|
||
return persist(ds, snap, write=write)
|