akg-factor-bridge/review_latest.py

77 lines
2.9 KiB
Python
Raw Permalink 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-16 选股系统小改,配合数据基座判收读数包)。
数据基座的判收命令要读周报里三处标记行的计数:公司质地分组("公司质地=")、量价两个头
("五日头""二十日头")。这里只做纯文件读取——取最新一份周报、前二十行、三个标记行计数——
不连任何库,api.py 的 GET /review/latest 直接调 payload。周报文件由 run.py plan-review 子进程
生成在 REVIEW_DIR(默认 data/review),文件名形如 复盘_2026-09-18_next_close.md。
"""
from __future__ import annotations
import os
import re
from typing import Optional
from config import REVIEW_DIR
DEFAULT_MARKERS = ("公司质地=", "五日头", "二十日头")
_NAME_RE = re.compile(r"^复盘_(\d{4}-\d{2}-\d{2})_(?P<start>[a-z_]+)\.md$")
def latest_report(dir_: str = REVIEW_DIR, *, start: str = "next_close") -> Optional[dict]:
"""最新一份周报:只认 复盘_YYYY-MM-DD_{start}.md,按日期倒序取第一。目录不存在或无匹配返回 None。"""
try:
names = os.listdir(dir_)
except OSError:
return None
found = []
for name in names:
m = _NAME_RE.match(name)
if m and m.group("start") == start:
found.append((m.group(1), name))
if not found:
return None
date, name = sorted(found, reverse=True)[0]
return {"file": name, "date": date, "path": os.path.join(dir_, name)}
def head_lines(path: str, n: int = 20) -> list[str]:
"""前 n 行(去掉行尾换行)。读不到返回空列表。"""
try:
with open(path, encoding="utf-8") as f:
out = []
for line in f:
out.append(line.rstrip("\n"))
if len(out) >= n:
break
return out
except OSError:
return []
def marker_counts(path: str, markers: tuple = DEFAULT_MARKERS) -> dict[str, int]:
"""每个标记在正文里出现的行数(含该标记的行计一次)。读不到全给零。"""
counts = {m: 0 for m in markers}
try:
with open(path, encoding="utf-8") as f:
for line in f:
for m in markers:
if m in line:
counts[m] += 1
except OSError:
pass
return counts
def payload(dir_: str = REVIEW_DIR, *, start: str = "next_close", markers: tuple = DEFAULT_MARKERS) -> Optional[dict]:
"""/review/latest 的返回体:文件名、日期、大小、前二十行、三个标记行计数。没有周报返回 None。"""
rep = latest_report(dir_, start=start)
if not rep:
return None
path = rep["path"]
try:
size = os.path.getsize(path)
except OSError:
size = None
return {"file": rep["file"], "date": rep["date"], "size": size,
"head": head_lines(path, 20), "marker_counts": marker_counts(path, markers)}