2026-07-30 14:09:02 +08:00
|
|
|
|
"""桥侧计划 API(07-30 用户需求):对外提供每日选股计划。
|
|
|
|
|
|
|
|
|
|
|
|
容器常驻命令改为 uvicorn 后随容器启动(docker-compose 已配端口,默认 8300);
|
|
|
|
|
|
cron 的 docker exec 构建/出计划照旧,互不影响。局域网内部服务,v1 无鉴权。
|
|
|
|
|
|
|
|
|
|
|
|
GET /health 存活 + 最新计划日
|
|
|
|
|
|
GET /plan 最新一天的计划(JSON)
|
|
|
|
|
|
GET /plan?date=2026-07-30 指定日期
|
|
|
|
|
|
GET /plan?format=md Markdown 原文(浏览器直接可读)
|
|
|
|
|
|
GET /plan/dates 可用日期列表
|
2026-10-21 10:07:57 +08:00
|
|
|
|
GET /plan/check?code=SZ300693 已发布完整计划的逐票核验(不裁剪、不重装配)
|
2026-10-15 10:26:11 +08:00
|
|
|
|
POST /plan/refresh?date=...&key=... 按 XXL 鉴权排入计划修订,不在请求中重装配
|
2026-07-30 14:09:02 +08:00
|
|
|
|
|
2026-08-03 16:33:23 +08:00
|
|
|
|
统一任务调度平台(XXL-JOB)触发入口挂在 /api/v1/xxl/*(见 xxl.py,2026-08-03):
|
|
|
|
|
|
盘前链(build → plan → push-pool)可由平台拉起并回调结案,.env 配 XXL_TRIGGER_KEY 才启用。
|
2026-07-30 14:09:02 +08:00
|
|
|
|
"""
|
2026-09-02 16:39:52 +08:00
|
|
|
|
import logging
|
|
|
|
|
|
import os
|
2026-09-09 13:43:22 +08:00
|
|
|
|
import time
|
|
|
|
|
|
import threading
|
2026-09-02 16:39:52 +08:00
|
|
|
|
|
2026-07-30 14:09:02 +08:00
|
|
|
|
import pandas as pd
|
2026-11-03 11:37:28 +08:00
|
|
|
|
from fastapi import FastAPI, HTTPException, Request, Body, Header, BackgroundTasks
|
2026-10-21 16:17:46 +08:00
|
|
|
|
from fastapi.responses import PlainTextResponse, JSONResponse, HTMLResponse
|
2026-07-30 14:09:02 +08:00
|
|
|
|
|
2026-09-07 16:35:29 +08:00
|
|
|
|
import card
|
2026-09-09 12:05:03 +08:00
|
|
|
|
import sources
|
2026-09-03 11:44:16 +08:00
|
|
|
|
import config
|
2026-07-30 14:09:02 +08:00
|
|
|
|
import db
|
2026-09-07 14:21:42 +08:00
|
|
|
|
import logic_state_daily
|
2026-10-15 10:26:11 +08:00
|
|
|
|
import plan_versions
|
2026-07-30 14:09:02 +08:00
|
|
|
|
import plan
|
2026-08-18 16:01:40 +08:00
|
|
|
|
import plan_reconcile
|
2026-09-02 16:39:52 +08:00
|
|
|
|
import regime
|
2026-09-16 10:42:11 +08:00
|
|
|
|
import review_latest
|
2026-08-03 16:33:23 +08:00
|
|
|
|
from xxl import router as xxl_router
|
2026-10-21 16:17:46 +08:00
|
|
|
|
from dividend_jobs import router as dividend_router
|
2026-07-30 14:09:02 +08:00
|
|
|
|
|
2026-09-02 16:39:52 +08:00
|
|
|
|
_access = logging.getLogger("plan.access")
|
|
|
|
|
|
|
2026-07-30 14:09:02 +08:00
|
|
|
|
app = FastAPI(title="akg-factor-bridge · 每日选股计划", version="0.1")
|
2026-08-03 16:33:23 +08:00
|
|
|
|
app.include_router(xxl_router)
|
2026-10-21 16:17:46 +08:00
|
|
|
|
app.include_router(dividend_router)
|
2026-07-30 14:09:02 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/health")
|
|
|
|
|
|
def health():
|
2026-09-03 11:44:16 +08:00
|
|
|
|
"""存活探针。2026-09-03 起带 pool_top 与 pool_max:PMS 的池深探针拿它与自身的计划深度
|
|
|
|
|
|
比较(池深不变式,台账 008),库连不上时也照样返回这两项。"""
|
|
|
|
|
|
depth = {"pool_top": config.POOL_TOP, "pool_max": config.POOL_MAX}
|
2026-10-15 10:26:11 +08:00
|
|
|
|
import plan_health
|
|
|
|
|
|
plan_status, plan_detail = plan_health.inspect(config.PLAN_SNAPSHOT_DIR)
|
|
|
|
|
|
depth.update(plan_status=plan_status, plan=plan_detail)
|
2026-07-30 14:09:02 +08:00
|
|
|
|
try:
|
|
|
|
|
|
d = plan._latest_date("t_factor_akg_score") # noqa: SLF001 —— 桥内自用
|
|
|
|
|
|
except Exception as e: # noqa: BLE001 —— 库连不上也要能回答"我还活着"
|
2026-09-03 11:44:16 +08:00
|
|
|
|
return {"ok": False, "error": repr(e), **depth}
|
|
|
|
|
|
return {"ok": True, "latest_plan_date": d, **depth}
|
2026-07-30 14:09:02 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-10-21 16:17:46 +08:00
|
|
|
|
@app.get("/research/dividend", response_class=HTMLResponse)
|
|
|
|
|
|
def dividend_research():
|
|
|
|
|
|
"""独立研究页只读归档,不在请求内采集或调用模型。"""
|
|
|
|
|
|
import dividend_watch as watch
|
|
|
|
|
|
from build_readiness import expected_data_day
|
|
|
|
|
|
bundle = watch.read_latest(watch.DEFAULT_ROOT)
|
|
|
|
|
|
if not bundle:
|
|
|
|
|
|
raise HTTPException(status_code=404, detail="高股息研究尚未发布")
|
|
|
|
|
|
status = watch.health(watch.DEFAULT_ROOT, expected_data_day())
|
|
|
|
|
|
page = watch.report(bundle['result'])
|
|
|
|
|
|
if not status['ok']:
|
|
|
|
|
|
page = page.replace('<main>', '<p role="alert">本次检查尚未成功。以下保留上次研究,请留意行情日期。</p><main>')
|
|
|
|
|
|
return HTMLResponse(page)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/research/dividend/health")
|
|
|
|
|
|
def dividend_research_health():
|
|
|
|
|
|
import dividend_watch as watch
|
|
|
|
|
|
from build_readiness import expected_data_day
|
|
|
|
|
|
return watch.health(watch.DEFAULT_ROOT, expected_data_day())
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-22 10:37:51 +08:00
|
|
|
|
@app.get("/research/dividend/candidates")
|
|
|
|
|
|
def dividend_candidate_feed(code: str = None):
|
|
|
|
|
|
"""独立高股息资格与来源;不修改原主榜,不触发研究。"""
|
|
|
|
|
|
import re
|
|
|
|
|
|
import dividend_candidates
|
|
|
|
|
|
if code is not None and not re.fullmatch(r"\d{6}\.(SH|SZ|BJ)", code):
|
|
|
|
|
|
raise HTTPException(status_code=400, detail="股票代码格式无效")
|
|
|
|
|
|
try:
|
|
|
|
|
|
return dividend_candidates.read(code=code)
|
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
|
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
_access.exception("高股息候选读取失败")
|
|
|
|
|
|
raise HTTPException(status_code=503, detail="高股息资料暂不可用,请稍后再试") from exc
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-03 11:37:28 +08:00
|
|
|
|
@app.get('/plan/user-candidates/search')
|
|
|
|
|
|
def search_user_candidates(q: str = ''):
|
|
|
|
|
|
import user_candidates as uc
|
|
|
|
|
|
query = q.strip().upper()[:40]
|
|
|
|
|
|
if not query:
|
|
|
|
|
|
return {'ok': True, 'items': []}
|
2026-11-03 12:33:10 +08:00
|
|
|
|
names = uc.catalog()
|
2026-11-03 11:37:28 +08:00
|
|
|
|
items = []
|
|
|
|
|
|
for code, name in names.items():
|
|
|
|
|
|
try:
|
|
|
|
|
|
uc.normalize(code)
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
continue
|
|
|
|
|
|
if query in code or query in name.upper():
|
|
|
|
|
|
items.append({'code': code, 'name': name})
|
|
|
|
|
|
return {'ok': True, 'items': sorted(items, key=lambda x: x['code'])[:30]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get('/plan/user-candidates')
|
|
|
|
|
|
def list_user_candidates():
|
|
|
|
|
|
import user_candidates as uc
|
|
|
|
|
|
return uc.listing(config.PLAN_SNAPSHOT_DIR)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.post('/plan/user-candidates')
|
|
|
|
|
|
def add_user_candidates(background_tasks: BackgroundTasks, payload: dict = Body(...),
|
|
|
|
|
|
x_job_key: str = Header(None)):
|
|
|
|
|
|
from xxl import _require_key
|
|
|
|
|
|
import user_candidates as uc
|
|
|
|
|
|
_require_key(x_job_key, None)
|
|
|
|
|
|
try:
|
2026-11-03 12:33:10 +08:00
|
|
|
|
result = uc.save(config.PLAN_SNAPSHOT_DIR, payload, payload.get('actor') or 'PMS', names=uc.catalog())
|
2026-11-03 11:37:28 +08:00
|
|
|
|
except ValueError as exc:
|
|
|
|
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
|
|
|
|
background_tasks.add_task(uc.refresh_saved)
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.post('/plan/user-candidates/{identity}/remove')
|
|
|
|
|
|
def remove_user_candidate(identity: str, background_tasks: BackgroundTasks,
|
|
|
|
|
|
payload: dict = Body(...), x_job_key: str = Header(None)):
|
|
|
|
|
|
from xxl import _require_key
|
|
|
|
|
|
import user_candidates as uc
|
|
|
|
|
|
_require_key(x_job_key, None)
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = uc.remove(config.PLAN_SNAPSHOT_DIR, identity, payload.get('actor') or 'PMS')
|
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
|
|
|
|
background_tasks.add_task(uc.refresh_saved)
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-30 14:09:02 +08:00
|
|
|
|
@app.get("/plan/dates")
|
|
|
|
|
|
def plan_dates(limit: int = 30):
|
2026-10-15 10:26:11 +08:00
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
days = sorted((p.stem[5:] for p in Path(config.PLAN_SNAPSHOT_DIR).glob('plan_????-??-??.json')), reverse=True)
|
|
|
|
|
|
return {'dates': days[:max(0, min(int(limit), 3650))]}
|
2026-07-30 14:09:02 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-09-09 13:43:22 +08:00
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
# 实时计划的进程内缓存(2026-09-09)。装配一次要三四十秒:读基座因果论断 20 秒、四类券商
|
|
|
|
|
|
# 事件 7.6 秒、事件日字段 6 秒(09-08 加的两路),PMS 页面一次加载要拉几路,累计超过它
|
|
|
|
|
|
# 60 秒的超时,人在页面上看到的就是"上游的选股计划读不到"。
|
|
|
|
|
|
# 同一数据日、同一参数的装配结果在一天里是确定的(用的全是昨收与昨夜的数据,盘中不变),
|
|
|
|
|
|
# 所以缓存是安全的:键带数据日与三个参数,过期时间可配,默认十分钟;nocache=1 强制重算。
|
|
|
|
|
|
# 计划文件每早重新生成,数据日一变缓存自然失效。
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
_PLAN_CACHE: dict = {}
|
|
|
|
|
|
_PLAN_CACHE_LOCK = threading.Lock()
|
2026-09-10 09:09:40 +08:00
|
|
|
|
# 2026-09-10: 默认从 600 秒(10 分钟)改成 12 小时。
|
|
|
|
|
|
# 起因: 09-10 开盘前 PMS 在 08:40 预热了一次(花 39 秒),缓存 08:50 就过期;用户 09:02
|
|
|
|
|
|
# 打开页面正好撞上冷启动,页面几路并发一起等,叠加破了 60 秒超时。
|
|
|
|
|
|
# 为什么可以放这么长: 缓存键里带的是**真实数据日**,上游换日后旧那份立刻失效,不靠时间
|
|
|
|
|
|
# 保新鲜。12 小时是为了覆盖整个交易日(08:40 预热能管到 20:40),不是为了省算力。
|
|
|
|
|
|
# 当天要强刷仍然走 nocache 参数。
|
|
|
|
|
|
PLAN_CACHE_SEC = int(os.environ.get("PLAN_CACHE_SEC", "43200"))
|
2026-09-10 09:23:41 +08:00
|
|
|
|
# 2026-09-10(台账 057):接口优先读当日全量快照、按请求参数截取,不再每次现场装配。
|
|
|
|
|
|
# 装配那三十三秒本来就不该在请求里花 —— 计划是日频的,出计划时已经落了一份全量底本。
|
2026-10-15 10:26:11 +08:00
|
|
|
|
# 保留旧配置名称;完整版本上线后不再允许查询回落现算。
|
2026-09-10 09:23:41 +08:00
|
|
|
|
PLAN_FROM_SNAPSHOT = os.environ.get("PLAN_FROM_SNAPSHOT", "1").lower() not in ("0", "false", "no")
|
2026-09-09 13:43:22 +08:00
|
|
|
|
_PLAN_CACHE_MAX = 8 # 不同参数组合最多留几份,防内存慢涨
|
2026-09-10 09:09:40 +08:00
|
|
|
|
_PLAN_BUILD_LOCKS: dict = {} # 每个缓存键一把「正在算」的锁,见 _plan_cached 里的说明
|
2026-09-09 13:43:22 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-11-03 12:09:28 +08:00
|
|
|
|
def _plan_build(date, top, obs_top, theme_cap, decision_id=None, include_user_candidates=False) -> dict:
|
2026-10-15 10:26:11 +08:00
|
|
|
|
"""只读已发布版本。缺档明确报错,禁止用当前研究重构历史。"""
|
2026-11-03 12:09:28 +08:00
|
|
|
|
return plan.from_snapshot(date, top, obs_top, theme_cap, decision_id=decision_id,
|
|
|
|
|
|
include_user_candidates=include_user_candidates)
|
2026-09-10 09:23:41 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-11-03 12:09:28 +08:00
|
|
|
|
def _plan_cached(date, top, obs_top, theme_cap, nocache: bool, decision_id=None, include_user_candidates=False):
|
2026-09-09 13:43:22 +08:00
|
|
|
|
"""返回 (data, 命中与否)。data 是 plan.collect 的结果(已去掉 _full)。
|
|
|
|
|
|
|
|
|
|
|
|
键里放**真实数据日**而不是请求里的 date:不传 date 时数据日随构建更新,明早换日后
|
|
|
|
|
|
旧那一份必须立刻失效,不能等缓存到期。取最新数据日是一条毫秒级查询。"""
|
2026-10-15 10:26:11 +08:00
|
|
|
|
import plan_versions as pv
|
|
|
|
|
|
published = pv.load(config.PLAN_SNAPSHOT_DIR, date, decision_id)
|
|
|
|
|
|
ds_key = published['date']
|
|
|
|
|
|
pinned = (published.get('decision') or {}).get('id')
|
|
|
|
|
|
state = pv.health(config.PLAN_SNAPSHOT_DIR, ds_key) if not decision_id else {}
|
2026-11-03 11:37:28 +08:00
|
|
|
|
if not decision_id and not date:
|
|
|
|
|
|
import user_candidates as uc
|
|
|
|
|
|
state = dict(state, pending_codes=sorted(set(state.get('pending_codes') or []) | set(uc.live_pending(config.PLAN_SNAPSHOT_DIR, published))))
|
2026-11-03 12:09:28 +08:00
|
|
|
|
key = (pinned or pv.digest(published), pv.digest(state), int(top), int(obs_top), int(theme_cap), bool(include_user_candidates))
|
2026-09-09 13:43:22 +08:00
|
|
|
|
now = time.time()
|
|
|
|
|
|
if not nocache and PLAN_CACHE_SEC > 0:
|
|
|
|
|
|
with _PLAN_CACHE_LOCK:
|
|
|
|
|
|
hit = _PLAN_CACHE.get(key)
|
|
|
|
|
|
if hit and now - hit[0] < PLAN_CACHE_SEC:
|
|
|
|
|
|
return hit[1], True
|
2026-09-10 09:09:40 +08:00
|
|
|
|
|
|
|
|
|
|
# 同一个键同时只算一次 (2026-09-10)。原来 plan.collect 在锁外面, 缓存冷的时候页面
|
|
|
|
|
|
# 几路并发进来会**各跑一遍**这趟三十多秒的装配, 还互相抢同一批库连接, 实际耗时远超
|
|
|
|
|
|
# 单跑一次 —— 这正是 09-10 早上页面破 60 秒超时的那一半原因。
|
|
|
|
|
|
# 现在让第一个请求去算, 后到的等它算完直接吃缓存。等待用的是每个键自己的锁,
|
|
|
|
|
|
# 不同参数组合互不阻塞。
|
|
|
|
|
|
with _PLAN_CACHE_LOCK:
|
|
|
|
|
|
lock = _PLAN_BUILD_LOCKS.get(key)
|
|
|
|
|
|
if lock is None:
|
|
|
|
|
|
lock = _PLAN_BUILD_LOCKS[key] = threading.Lock()
|
|
|
|
|
|
with lock:
|
|
|
|
|
|
# 双重检查: 排在后面的请求进到这里时, 前一个多半已经把结果写进缓存了
|
|
|
|
|
|
if not nocache and PLAN_CACHE_SEC > 0:
|
|
|
|
|
|
with _PLAN_CACHE_LOCK:
|
|
|
|
|
|
hit = _PLAN_CACHE.get(key)
|
|
|
|
|
|
if hit and time.time() - hit[0] < PLAN_CACHE_SEC:
|
|
|
|
|
|
return hit[1], True
|
2026-11-03 12:09:28 +08:00
|
|
|
|
data = _plan_build(ds_key, top, obs_top, theme_cap, pinned,
|
|
|
|
|
|
**({'include_user_candidates': True} if include_user_candidates else {}))
|
2026-10-15 10:26:11 +08:00
|
|
|
|
data['refresh_status'] = state
|
2026-09-10 09:09:40 +08:00
|
|
|
|
if PLAN_CACHE_SEC > 0:
|
|
|
|
|
|
with _PLAN_CACHE_LOCK:
|
|
|
|
|
|
_PLAN_CACHE[key] = (time.time(), data)
|
|
|
|
|
|
if len(_PLAN_CACHE) > _PLAN_CACHE_MAX:
|
|
|
|
|
|
for k in sorted(_PLAN_CACHE, key=lambda x: _PLAN_CACHE[x][0])[:-_PLAN_CACHE_MAX]:
|
|
|
|
|
|
_PLAN_CACHE.pop(k, None)
|
|
|
|
|
|
_PLAN_BUILD_LOCKS.pop(k, None)
|
2026-09-09 13:43:22 +08:00
|
|
|
|
return data, False
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-09-10 13:17:22 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-07-30 14:09:02 +08:00
|
|
|
|
@app.get("/plan")
|
2026-09-02 16:39:52 +08:00
|
|
|
|
def get_plan(request: Request, date: str | None = None, format: str = "json",
|
2026-10-15 10:26:11 +08:00
|
|
|
|
top: int = 20, obs_top: int = 10, theme_cap: int = 5, nocache: int = 0,
|
2026-11-03 12:09:28 +08:00
|
|
|
|
decision_id: str | None = None, include_user_candidates: bool = False):
|
2026-09-02 16:39:52 +08:00
|
|
|
|
"""向下兼容承诺(2026-09-02 方案 2.7):main / observe 的装配、排序、裁剪与既有字段
|
|
|
|
|
|
一字不动,每行只多联入判决类字段;顶层只新增 generated_at、plan_version、regime、
|
2026-09-03 11:44:16 +08:00
|
|
|
|
card_counts、candidates、watch、segments_pointed、snapshot,2026-09-03 再加 market
|
|
|
|
|
|
(环境段市场四项,与 regime 一样只从当日快照读,快照缺失为空字典)。PMS 按字段名取值、忽略未知键。"""
|
2026-09-09 13:43:22 +08:00
|
|
|
|
t0 = time.time()
|
2026-07-30 14:09:02 +08:00
|
|
|
|
try:
|
2026-11-03 12:09:28 +08:00
|
|
|
|
data, cached = _plan_cached(date, top, obs_top, theme_cap, bool(nocache), decision_id, include_user_candidates)
|
2026-10-15 10:26:11 +08:00
|
|
|
|
except (RuntimeError, ValueError, OSError) as e:
|
2026-07-30 14:09:02 +08:00
|
|
|
|
raise HTTPException(status_code=404, detail=str(e))
|
2026-09-09 13:43:22 +08:00
|
|
|
|
data = dict(data) # 下面几个键按请求写,不污染缓存里那一份
|
2026-09-02 16:39:52 +08:00
|
|
|
|
ds = data["date"]
|
2026-10-15 10:26:11 +08:00
|
|
|
|
data["snapshot"] = "present"
|
|
|
|
|
|
data["regime"] = data.get('regime') or {"status": regime.UNKNOWN, "weak_day": None,
|
2026-09-02 16:39:52 +08:00
|
|
|
|
"source": "当日快照无环境段(08:45 追加未跑或快照缺失)"}
|
2026-10-15 10:26:11 +08:00
|
|
|
|
data["market"] = data.get('market') or {}
|
|
|
|
|
|
n_cr = 0 # 评析只在完整版本发布时变化。
|
2026-09-02 16:39:52 +08:00
|
|
|
|
_access.info("plan client=%s date=%s regime=%s generated_at=%s version=%s "
|
2026-09-10 13:17:22 +08:00
|
|
|
|
"top=%s obs_top=%s theme_cap=%s cache=%s source=%s 评析补%s只 耗时=%.1fs",
|
2026-09-02 16:39:52 +08:00
|
|
|
|
request.client.host if request.client else "-", ds,
|
|
|
|
|
|
data["regime"].get("status"), data.get("generated_at"),
|
2026-09-09 13:43:22 +08:00
|
|
|
|
data.get("plan_version"), top, obs_top, theme_cap,
|
2026-09-10 09:23:41 +08:00
|
|
|
|
"hit" if cached else "miss", data.get("plan_source") or "-",
|
2026-09-10 13:17:22 +08:00
|
|
|
|
n_cr, time.time() - t0)
|
2026-07-30 14:09:02 +08:00
|
|
|
|
if format == "md":
|
|
|
|
|
|
return PlainTextResponse(plan.render_md(data),
|
|
|
|
|
|
media_type="text/markdown; charset=utf-8")
|
2026-10-21 10:07:57 +08:00
|
|
|
|
# 同步路由的工作线程完成编码,避免大计划编码阻塞逐票检查与其他请求。
|
|
|
|
|
|
return JSONResponse(content=data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get('/plan/check')
|
2026-11-03 12:09:28 +08:00
|
|
|
|
def check_plan_stock(code: str, include_user_candidates: bool = False):
|
2026-10-21 10:07:57 +08:00
|
|
|
|
"""采纳专用逐票读取。只读已发布计划,不装配、不查研究库。"""
|
|
|
|
|
|
from common import to_prefix
|
|
|
|
|
|
try:
|
2026-11-03 12:09:28 +08:00
|
|
|
|
return JSONResponse(content=plan_versions.stock_check(config.PLAN_SNAPSHOT_DIR, to_prefix(code),
|
|
|
|
|
|
include_user_candidates=include_user_candidates))
|
2026-10-21 10:07:57 +08:00
|
|
|
|
except (OSError, ValueError, RuntimeError) as e:
|
|
|
|
|
|
raise HTTPException(status_code=503, detail=str(e))
|
2026-07-30 14:09:02 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.post("/plan/refresh")
|
2026-10-15 10:26:11 +08:00
|
|
|
|
def refresh(date: str | None = None, key: str | None = None):
|
|
|
|
|
|
from xxl import trigger_daily_build
|
|
|
|
|
|
return trigger_daily_build(callbackUrl=None, steps='plan-refresh', date=date,
|
|
|
|
|
|
key=key, x_job_key=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-03 12:09:28 +08:00
|
|
|
|
def _published_stock_rows(want, date, decision_id, include_user_candidates=False):
|
2026-07-30 14:09:02 +08:00
|
|
|
|
try:
|
2026-10-15 10:26:11 +08:00
|
|
|
|
published = plan_versions.load(config.PLAN_SNAPSHOT_DIR, date, decision_id)
|
|
|
|
|
|
except (OSError, ValueError):
|
|
|
|
|
|
if decision_id or date:
|
|
|
|
|
|
raise HTTPException(status_code=404, detail='指定计划版本不可用')
|
|
|
|
|
|
return {}, {}
|
2026-11-03 12:09:28 +08:00
|
|
|
|
import user_candidates as uc
|
|
|
|
|
|
published = uc.consumer_view(published, include_user_candidates)
|
2026-10-15 10:26:11 +08:00
|
|
|
|
rows = {r['code']: dict(r, decision=bucket, source='published',
|
|
|
|
|
|
traceability=published.get('traceability') or 'legacy_unverified',
|
|
|
|
|
|
decision_version=published.get('decision'), date=published['date'],
|
|
|
|
|
|
verdict_text=r.get('basis') or r.get('verdict'))
|
|
|
|
|
|
for bucket in ('main', 'observe') for r in published.get(bucket, [])}
|
|
|
|
|
|
wanted = []
|
|
|
|
|
|
for c in want:
|
|
|
|
|
|
try:
|
|
|
|
|
|
wanted.append(plan_reconcile._norm_code(c))
|
|
|
|
|
|
except SystemExit:
|
|
|
|
|
|
continue
|
|
|
|
|
|
return {c: rows[c] for c in wanted if c in rows}, published
|
2026-08-18 16:01:40 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/plan/verdict")
|
|
|
|
|
|
def plan_verdict(codes: str | None = None, code: str | None = None,
|
2026-10-15 10:26:11 +08:00
|
|
|
|
date: str | None = None, decision_id: str | None = None):
|
2026-08-18 16:01:40 +08:00
|
|
|
|
"""逐票『计划判决』(只读)——今日页 / 机会线索页对齐用。
|
|
|
|
|
|
|
|
|
|
|
|
GET /plan/verdict?codes=300750,600438,SH688041 多只(逗号分隔)
|
|
|
|
|
|
GET /plan/verdict?code=300750&date=2026-08-04 单只 + 指定档位日
|
|
|
|
|
|
|
|
|
|
|
|
每只票返回 decision(main 主榜 / observe 观察档 / reject 不采纳 / absent 无此票)、
|
|
|
|
|
|
与命令行 plan_reconcile 完全同口径的 verdict_text(页面直接展示的一行解释),
|
|
|
|
|
|
以及 score/rank/tier/upside/热度/传导/赛道/图谱证据等明细。
|
|
|
|
|
|
date 缺省=当日档位日。三种代码形态都收(600000.SH / SH600000 / 600000)。纯 SELECT,不写任何库。
|
|
|
|
|
|
"""
|
|
|
|
|
|
raw = (codes or code or "").strip()
|
|
|
|
|
|
want = [c.strip() for c in raw.split(",") if c.strip()]
|
|
|
|
|
|
if not want:
|
|
|
|
|
|
raise HTTPException(status_code=400, detail="缺少 code / codes 参数")
|
2026-10-15 10:26:11 +08:00
|
|
|
|
frozen, published = _published_stock_rows(want, date, decision_id)
|
|
|
|
|
|
if decision_id or date or len(frozen) == len(want):
|
|
|
|
|
|
return {'date': published.get('date'), 'decision_version': published.get('decision'),
|
|
|
|
|
|
'verdicts': list(frozen.values()), 'count': len(frozen), 'stale': ''}
|
2026-08-18 16:01:40 +08:00
|
|
|
|
d = date or plan_reconcile.latest_date()
|
|
|
|
|
|
if not d:
|
|
|
|
|
|
raise HTTPException(status_code=404, detail="档位表为空——先跑当日构建")
|
|
|
|
|
|
try:
|
|
|
|
|
|
L = plan_reconcile._load(d) # noqa: SLF001 —— 桥内自用只读加载
|
|
|
|
|
|
except Exception as e: # noqa: BLE001 —— 数据层异常统一收成 500
|
|
|
|
|
|
raise HTTPException(status_code=500, detail=f"加载档位数据失败: {e!r}")
|
|
|
|
|
|
verdicts = []
|
|
|
|
|
|
for c in want:
|
|
|
|
|
|
try:
|
|
|
|
|
|
k = plan_reconcile._norm_code(c) # noqa: SLF001
|
|
|
|
|
|
except SystemExit as e: # _norm_code 认不出的形态会 raise SystemExit
|
|
|
|
|
|
verdicts.append({"input": c, "error": str(e)})
|
|
|
|
|
|
continue
|
2026-09-02 11:48:26 +08:00
|
|
|
|
try:
|
|
|
|
|
|
v = plan_reconcile.verdict(k, L)
|
|
|
|
|
|
except Exception as e: # noqa: BLE001 —— 单票数据异常(如 score 缺行)不崩整批,
|
|
|
|
|
|
verdicts.append({"input": c, "code": k, # 与上面认不出形态的处理对称
|
|
|
|
|
|
"error": f"{type(e).__name__}: {e}"})
|
|
|
|
|
|
continue
|
2026-10-15 10:26:11 +08:00
|
|
|
|
v = frozen.get(k, dict(v, observation_at=plan_versions.now(), observation_scope='independent'))
|
2026-08-18 16:01:40 +08:00
|
|
|
|
v["input"] = c
|
|
|
|
|
|
verdicts.append(v)
|
|
|
|
|
|
return {"date": d, "stale": L.get("stale", ""),
|
|
|
|
|
|
"count": len(verdicts), "verdicts": verdicts}
|
2026-09-07 14:21:42 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/logic_state")
|
|
|
|
|
|
def logic_state_lookup(codes: str | None = None, code: str | None = None,
|
2026-10-15 10:26:11 +08:00
|
|
|
|
date: str | None = None, decision_id: str | None = None):
|
2026-09-07 14:21:42 +08:00
|
|
|
|
"""逐票逻辑状态四态(只读)——给 PMS 早上拉完计划后查在持票用(2026-09-07 第三件桥侧前置)。
|
|
|
|
|
|
|
|
|
|
|
|
GET /logic_state?codes=300750,SH688041 多只(逗号分隔)
|
|
|
|
|
|
GET /logic_state?code=300750&date=2026-09-04 单只 + 指定数据日
|
|
|
|
|
|
|
|
|
|
|
|
持仓票在候选筛选第一步就被整行剔掉,/plan 里读不到它,所以要有这个入口。
|
|
|
|
|
|
每只票优先回逐票日频表里当日那一行(早上生成计划时落定的,带代码版本,可回溯),
|
|
|
|
|
|
标 source=daily;当日表里没有这只票(不在档位表、或当日还没生成)就按此刻的数据现算、
|
|
|
|
|
|
按表里的历史做抗抖动,标 source=computed——现算的是"此刻"不是"早上",复盘别把它当当日态。
|
|
|
|
|
|
date 缺省=档位表最新日(与 /plan 的数据日同口径)。三种代码形态都收。纯 SELECT,不写任何库。
|
|
|
|
|
|
"""
|
|
|
|
|
|
raw = (codes or code or "").strip()
|
|
|
|
|
|
want = [c.strip() for c in raw.split(",") if c.strip()]
|
|
|
|
|
|
if not want:
|
|
|
|
|
|
raise HTTPException(status_code=400, detail="缺少 code / codes 参数")
|
2026-10-15 10:26:11 +08:00
|
|
|
|
frozen, published = _published_stock_rows(want, date, decision_id)
|
|
|
|
|
|
if decision_id or date or len(frozen) == len(want):
|
|
|
|
|
|
return {'date': published.get('date'), 'decision_version': published.get('decision'),
|
|
|
|
|
|
'states': [dict(r, **(r.get('logic_state') or {})) for r in frozen.values()],
|
|
|
|
|
|
'count': len(frozen)}
|
2026-09-07 14:21:42 +08:00
|
|
|
|
d = date or plan._latest_date("t_factor_akg_score") # noqa: SLF001 —— 桥内自用
|
|
|
|
|
|
if not d:
|
|
|
|
|
|
raise HTTPException(status_code=404, detail="档位表为空——先跑当日构建")
|
|
|
|
|
|
keyed, bad = {}, []
|
|
|
|
|
|
for c in want:
|
|
|
|
|
|
try:
|
|
|
|
|
|
keyed.setdefault(plan_reconcile._norm_code(c), c) # noqa: SLF001
|
|
|
|
|
|
except SystemExit as e: # _norm_code 认不出的形态会 raise SystemExit
|
|
|
|
|
|
bad.append({"input": c, "error": str(e)})
|
|
|
|
|
|
stored = logic_state_daily.lookup(list(keyed), d)
|
|
|
|
|
|
todo = [k for k in keyed if k not in stored]
|
|
|
|
|
|
computed = {}
|
|
|
|
|
|
if todo:
|
|
|
|
|
|
try:
|
|
|
|
|
|
computed = plan.logic_states_for(todo, d)
|
|
|
|
|
|
except Exception as e: # noqa: BLE001 —— 数据层异常统一收成 500
|
|
|
|
|
|
raise HTTPException(status_code=500, detail=f"现算逻辑状态失败: {e!r}")
|
|
|
|
|
|
out = []
|
|
|
|
|
|
for k, c in keyed.items():
|
|
|
|
|
|
if k in stored:
|
|
|
|
|
|
row = stored[k]
|
|
|
|
|
|
out.append({"input": c, "code": k, "date": d, "source": "daily",
|
|
|
|
|
|
"verdict": row.get("verdict"), "card_rank": row.get("card_rank"),
|
|
|
|
|
|
"plan_version": row.get("plan_version"),
|
|
|
|
|
|
**logic_state_daily.row_to_out(row)})
|
|
|
|
|
|
else:
|
|
|
|
|
|
out.append({"input": c, "code": k, "date": d, "source": "computed",
|
|
|
|
|
|
"verdict": None, "card_rank": None, "plan_version": None,
|
|
|
|
|
|
**(plan._state_out(computed.get(k)) or {})}) # noqa: SLF001
|
2026-09-07 16:35:29 +08:00
|
|
|
|
# 安全边际三情景随状态一起回(第四件;2026-09-07 拍板持仓页显示中性情景作参考目标价,只显示不触发)。
|
|
|
|
|
|
# 逐票日频表里不存它,每次按此刻现算;算失败整批不带这两键,状态照回。
|
|
|
|
|
|
try:
|
|
|
|
|
|
vals = plan.valuations_for(list(keyed), d)
|
|
|
|
|
|
for item in out:
|
|
|
|
|
|
v = vals.get(item["code"])
|
|
|
|
|
|
item["valuation"] = v
|
|
|
|
|
|
item["valuation_text"] = card.valuation_view(v)
|
|
|
|
|
|
except Exception as e: # noqa: BLE001 —— 估值算不出不该拖垮状态查询
|
|
|
|
|
|
_access.warning("logic_state valuation failed date=%s err=%r", d, e)
|
2026-09-09 12:05:03 +08:00
|
|
|
|
# 公司深度两键随状态一起回(2026-09-09 接入方案):持仓页"证据还在不在"旁显示质地与失效条件。读不到整批不带。
|
|
|
|
|
|
try:
|
2026-10-15 10:26:11 +08:00
|
|
|
|
crs = sources.company_reviews(list(keyed), d, cutoff_at=plan_versions.now() if not date else None)
|
2026-09-09 12:05:03 +08:00
|
|
|
|
for item in out:
|
|
|
|
|
|
cr = crs.get(item["code"])
|
|
|
|
|
|
item["company_review"] = cr
|
|
|
|
|
|
item["company_review_text"] = card.company_review_view(cr)
|
|
|
|
|
|
except Exception as e: # noqa: BLE001
|
|
|
|
|
|
_access.warning("logic_state company_review failed date=%s err=%r", d, e)
|
2026-10-15 10:26:11 +08:00
|
|
|
|
out = [dict(frozen[r['code']], **(frozen[r['code']].get('logic_state') or {}))
|
|
|
|
|
|
if r['code'] in frozen else dict(r, observation_at=plan_versions.now(), observation_scope='independent')
|
|
|
|
|
|
for r in out]
|
2026-09-07 14:21:42 +08:00
|
|
|
|
return {"date": d, "count": len(out) + len(bad), "states": out + bad}
|
2026-09-16 10:42:11 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/review/latest")
|
|
|
|
|
|
def review_latest_endpoint():
|
|
|
|
|
|
"""最新一份复盘周报的只读读数(2026-09-16 小改,配合数据基座判收读数包):文件名、日期、大小、
|
|
|
|
|
|
前二十行、三个标记行计数(公司质地=、五日头、二十日头)。没有周报回 404。纯文件读取,不连库。"""
|
|
|
|
|
|
p = review_latest.payload()
|
|
|
|
|
|
if p is None:
|
|
|
|
|
|
raise HTTPException(status_code=404, detail="还没有生成过复盘周报")
|
|
|
|
|
|
return p
|