Files
MoFin/deploy/profile-scripts/ab_research_daily.py
T

95 lines
3.8 KiB
Python
Raw 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.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AB路线每日LLM主导研究 v2(老莫2026-08-18
在原规则化分析基础上,集成 LLM 生成深度研究结论(真正"LLM主导"
1. 读温区覆盖 + 进化中心 + B组候选
2. LLM 分析薄弱环节 → 建议尝试
3. 写 strategy_research_log 表
"""
import sys, os, json, sqlite3
from datetime import datetime
sys.path.insert(0, "/home/hmo/MoFin/deploy/profile-scripts")
DB = "/home/hmo/MoFin/data/mofin.db"
CENTER = "/home/hmo/MoFin/data/evolution_center.json"
def ensure_table(conn):
conn.execute("""CREATE TABLE IF NOT EXISTS strategy_research_log (
id INTEGER PRIMARY KEY AUTOINCREMENT, log_date TEXT NOT NULL, market TEXT,
weak_regime TEXT, finding TEXT, experiment TEXT, result TEXT,
produced_strategy TEXT, produced_verified INTEGER DEFAULT 0, llm_model TEXT, created_at TEXT)""")
conn.commit()
def load_center():
if not os.path.exists(CENTER): return {}
try: return json.load(open(CENTER))
except: return {}
def build_prompt(coverage, center):
"""构造 LLM 研究 prompt"""
line = []
line.append("你是MoFin策略研究员。分析当前策略覆盖,找出薄弱环节并给出研究建议。")
line.append("温区覆盖(trades>=302y):")
for c in coverage:
line.append(f"- {c['market']}/{c['regime']}: {c['count']}个策略")
bg = center.get("b_group") or []
if bg:
line.append(f"B组候选: {len(bg)}条")
for b in bg[:3]:
line.append(f" - {str(b)[:80]}")
line.append("\n请输出:")
line.append("1. 最薄弱的温区/环节(策略匮乏或合格策略少)")
line.append("2. 具体研究建议(做什么尝试)")
line.append("3. 预期成果类型")
line.append("格式:发现|建议|预期")
return "\n".join(line)
def analyze_llm(coverage, center):
"""LLM 生成研究结论"""
try:
from llm_client import call_llm
prompt = build_prompt(coverage, center)
res = call_llm(prompt)
return str(res)[:400] if res else None
except Exception as e:
return f"[LLM调用失败: {e}]"
def main():
conn = sqlite3.connect(DB, timeout=30)
conn.execute("PRAGMA busy_timeout=30000")
ensure_table(conn)
today = datetime.now().strftime("%Y-%m-%d")
if conn.execute("SELECT COUNT(*) FROM strategy_research_log WHERE log_date=?", (today,)).fetchone()[0]:
print(f"[AB研究] {today} 已有记录"); conn.close(); return
# 读取覆盖
rows = conn.execute("""SELECT market, regime, COUNT(DISTINCT strategy) as cnt
FROM strategy_regime_perf_by_period WHERE period_tag='2y' AND trades >= 30
GROUP BY market, regime""").fetchall()
coverage = [{"market": r[0], "regime": r[1], "count": r[2]} for r in rows]
center = load_center()
# 基础规则发现
findings = []
weak = []
if coverage:
c_sorted = sorted(coverage, key=lambda x: x["count"])
weak = c_sorted[:2]
findings.append("覆盖最少的温区: " + "; ".join(f"{c['market']}/{c['regime']}({c['count']})" for c in weak))
# LLM 深度分析
if coverage:
llm_res = analyze_llm(coverage, center)
if llm_res:
findings.append("LLM分析: " + llm_res)
finding_text = "; ".join(findings) or "无明显薄弱点"
weak_rg = weak[0]["regime"] if weak else ""
weak_mkt = weak[0]["market"] if weak else "a"
conn.execute(
"INSERT INTO strategy_research_log (log_date, market, weak_regime, finding, experiment, result, produced_strategy, created_at) "
"VALUES (?,?,?,?,?,?,?,?)",
(today, weak_mkt, weak_rg, finding_text, "LLM主导温区覆盖+B组分析", "记录待验证", "",
datetime.now().isoformat()))
conn.commit()
print(f"[AB研究] {today} 记录完成 (LLM主导)")
conn.close()
if __name__ == "__main__":
main()