|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse |
| 4 | +import datetime as dt |
| 5 | +import json |
| 6 | +from pathlib import Path |
| 7 | +from typing import Any |
| 8 | + |
| 9 | + |
| 10 | +HORIZON_LABELS_ZH = { |
| 11 | + "short": "短线", |
| 12 | + "medium": "中线", |
| 13 | + "long": "长线", |
| 14 | +} |
| 15 | + |
| 16 | +HORIZON_WINDOWS_ZH = { |
| 17 | + "short": "1-10个交易日", |
| 18 | + "medium": "2-12周", |
| 19 | + "long": "1-3年", |
| 20 | +} |
| 21 | + |
| 22 | + |
| 23 | +def utc_now_iso() -> str: |
| 24 | + return dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z") |
| 25 | + |
| 26 | + |
| 27 | +def load_report(path: str | Path) -> dict[str, Any]: |
| 28 | + with Path(path).open(encoding="utf-8") as handle: |
| 29 | + return json.load(handle) |
| 30 | + |
| 31 | + |
| 32 | +def final_recommendations(report: dict[str, Any]) -> list[dict[str, Any]]: |
| 33 | + decisions = report.get("final_decisions") |
| 34 | + if not isinstance(decisions, dict): |
| 35 | + return [] |
| 36 | + items = decisions.get("recommendations", []) |
| 37 | + return [item for item in items if isinstance(item, dict) and item.get("symbol")] |
| 38 | + |
| 39 | + |
| 40 | +def symbols(items: list[dict[str, Any]]) -> list[str]: |
| 41 | + return [str(item["symbol"]).upper() for item in items] |
| 42 | + |
| 43 | + |
| 44 | +def horizon_buckets(items: list[dict[str, Any]]) -> dict[str, list[str]]: |
| 45 | + buckets = {"short": [], "medium": [], "long": []} |
| 46 | + for item in items: |
| 47 | + horizon = str(item.get("primary_horizon", "")) |
| 48 | + if horizon in buckets: |
| 49 | + buckets[horizon].append(str(item["symbol"]).upper()) |
| 50 | + return buckets |
| 51 | + |
| 52 | + |
| 53 | +def compact_pick(item: dict[str, Any]) -> dict[str, Any]: |
| 54 | + return { |
| 55 | + "symbol": str(item.get("symbol", "")).upper(), |
| 56 | + "name": str(item.get("name", "")), |
| 57 | + "primary_horizon": str(item.get("primary_horizon", "")), |
| 58 | + "primary_horizon_label": str(item.get("primary_horizon_label", "")), |
| 59 | + "primary_horizon_window": str(item.get("primary_horizon_window", "")), |
| 60 | + "combined_score": item.get("combined_score"), |
| 61 | + "source_score": item.get("source_score"), |
| 62 | + "momentum_score": item.get("momentum_score"), |
| 63 | + "ai_signal_score": item.get("ai_signal_score"), |
| 64 | + "business_summary": str(item.get("business_summary", "")), |
| 65 | + "prospect_summary": str(item.get("prospect_summary", "")), |
| 66 | + "risk_summary": str(item.get("risk_summary", "")), |
| 67 | + } |
| 68 | + |
| 69 | + |
| 70 | +def build_monthly_review( |
| 71 | + *, |
| 72 | + current_report: dict[str, Any], |
| 73 | + previous_report: dict[str, Any] | None = None, |
| 74 | + current_report_path: str | Path = "", |
| 75 | + previous_report_path: str | Path = "", |
| 76 | +) -> dict[str, Any]: |
| 77 | + current_items = final_recommendations(current_report) |
| 78 | + previous_items = final_recommendations(previous_report or {}) |
| 79 | + current_symbols = symbols(current_items) |
| 80 | + previous_symbols = symbols(previous_items) |
| 81 | + current_set = set(current_symbols) |
| 82 | + previous_set = set(previous_symbols) |
| 83 | + data_quality_warnings: list[str] = [] |
| 84 | + if previous_report is None: |
| 85 | + data_quality_warnings.append("No previous report supplied; month-over-month changes are not available.") |
| 86 | + if not current_items: |
| 87 | + data_quality_warnings.append("Current report has no final recommendations.") |
| 88 | + |
| 89 | + return { |
| 90 | + "schema_version": "1", |
| 91 | + "mode": "monthly_advisory_review", |
| 92 | + "as_of": str(current_report.get("as_of", "")), |
| 93 | + "generated_at": utc_now_iso(), |
| 94 | + "source_artifacts": { |
| 95 | + "current_report": str(current_report_path), |
| 96 | + "previous_report": str(previous_report_path) if previous_report_path else "", |
| 97 | + }, |
| 98 | + "summary": { |
| 99 | + "current_final_recommendations": current_symbols, |
| 100 | + "previous_final_recommendations": previous_symbols, |
| 101 | + "added_symbols": sorted(current_set - previous_set), |
| 102 | + "removed_symbols": sorted(previous_set - current_set), |
| 103 | + "unchanged_symbols": [symbol for symbol in current_symbols if symbol in previous_set], |
| 104 | + "current_horizon_buckets": horizon_buckets(current_items), |
| 105 | + "data_quality_warnings": data_quality_warnings, |
| 106 | + }, |
| 107 | + "current_recommendations": [compact_pick(item) for item in current_items], |
| 108 | + "previous_recommendations": [compact_pick(item) for item in previous_items], |
| 109 | + "policy": { |
| 110 | + "execution_allowed": False, |
| 111 | + "portfolio_allocation_allowed": False, |
| 112 | + "personalized_advice_allowed": False, |
| 113 | + "downstream_use": "Monthly review of non-personalized model recommendations only.", |
| 114 | + }, |
| 115 | + } |
| 116 | + |
| 117 | + |
| 118 | +def render_monthly_review_markdown(review: dict[str, Any]) -> str: |
| 119 | + lines = [f"# 月度模型推荐复盘 - {review.get('as_of', '')}", ""] |
| 120 | + summary = review.get("summary", {}) |
| 121 | + buckets = summary.get("current_horizon_buckets", {}) |
| 122 | + lines.append("## 本月最终推荐") |
| 123 | + lines.append("") |
| 124 | + for horizon in ("short", "medium", "long"): |
| 125 | + label = HORIZON_LABELS_ZH[horizon] |
| 126 | + window = HORIZON_WINDOWS_ZH[horizon] |
| 127 | + value = ", ".join(buckets.get(horizon, [])) or "暂无最终推荐" |
| 128 | + lines.append(f"- {label}({window}):{value}") |
| 129 | + lines.append("") |
| 130 | + lines.append("## 较上次变化") |
| 131 | + lines.append("") |
| 132 | + lines.append(f"- 新增:{', '.join(summary.get('added_symbols', [])) or '无'}") |
| 133 | + lines.append(f"- 移除:{', '.join(summary.get('removed_symbols', [])) or '无'}") |
| 134 | + lines.append(f"- 保持:{', '.join(summary.get('unchanged_symbols', [])) or '无'}") |
| 135 | + warnings = summary.get("data_quality_warnings", []) |
| 136 | + if warnings: |
| 137 | + lines.append("") |
| 138 | + lines.append("## 数据质量提示") |
| 139 | + lines.extend(f"- {warning}" for warning in warnings) |
| 140 | + picks = review.get("current_recommendations", []) |
| 141 | + if picks: |
| 142 | + lines.append("") |
| 143 | + lines.append("## 标的摘要") |
| 144 | + for item in picks: |
| 145 | + lines.extend( |
| 146 | + [ |
| 147 | + "", |
| 148 | + f"### {item.get('symbol')} - {item.get('name')}", |
| 149 | + f"- 周期:{item.get('primary_horizon_label')}({item.get('primary_horizon_window')})", |
| 150 | + f"- 股票背景:{item.get('business_summary')}", |
| 151 | + f"- 推荐理由:{item.get('prospect_summary')}", |
| 152 | + f"- 主要风险:{item.get('risk_summary')}", |
| 153 | + ] |
| 154 | + ) |
| 155 | + return "\n".join(lines).rstrip() + "\n" |
| 156 | + |
| 157 | + |
| 158 | +def write_json(path: str | Path, payload: dict[str, Any]) -> None: |
| 159 | + output_path = Path(path) |
| 160 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 161 | + output_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") |
| 162 | + |
| 163 | + |
| 164 | +def write_text(path: str | Path, content: str) -> None: |
| 165 | + output_path = Path(path) |
| 166 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 167 | + output_path.write_text(content, encoding="utf-8") |
| 168 | + |
| 169 | + |
| 170 | +def build_arg_parser() -> argparse.ArgumentParser: |
| 171 | + parser = argparse.ArgumentParser(description="Build a monthly review artifact from advisory report JSON files.") |
| 172 | + parser.add_argument("--current-report", required=True, help="Current advisory report JSON path.") |
| 173 | + parser.add_argument("--previous-report", help="Optional previous advisory report JSON path.") |
| 174 | + parser.add_argument("--output-json", required=True, help="Output monthly review JSON path.") |
| 175 | + parser.add_argument("--output-md", required=True, help="Output monthly review Markdown path.") |
| 176 | + return parser |
| 177 | + |
| 178 | + |
| 179 | +def main(argv: list[str] | None = None) -> None: |
| 180 | + args = build_arg_parser().parse_args(argv) |
| 181 | + current = load_report(args.current_report) |
| 182 | + previous = load_report(args.previous_report) if args.previous_report else None |
| 183 | + review = build_monthly_review( |
| 184 | + current_report=current, |
| 185 | + previous_report=previous, |
| 186 | + current_report_path=args.current_report, |
| 187 | + previous_report_path=args.previous_report or "", |
| 188 | + ) |
| 189 | + write_json(args.output_json, review) |
| 190 | + write_text(args.output_md, render_monthly_review_markdown(review)) |
| 191 | + |
| 192 | + |
| 193 | +if __name__ == "__main__": |
| 194 | + main() |
0 commit comments