```
feat(market): 添加市场分析数据基础架构和功能模块 - 新增市场分析相关数据库表结构,包括市场工具、每日报价、财务指标、 宏观指标和公告等数据模型 - 创建市场分析相关的Alembic迁移脚本,包含完整的up和downgrade逻辑 - 集成市场分析路由到主API路由器中 - 添加市场数据定时任务调度,支持盘前、收盘和周度市场分析报告 - 实现市场数据后台任务队列,包含报告生成和收盘分析功能 - 扩展系统配置设置,添加市场分析启用开关和相关参数配置 - 增加AI智能技能支持,包含市场概览分析和股票分析功能 - 添加审计日志记录,支持市场数据同步和自选股更新操作追踪 - 实现飞书命令集成,支持股票分析、自选股管理、公告查询等交互 - 提供市场数据服务层,包含行业分析、股票对比、市场概览等功能 ```
This commit is contained in:
@@ -26,6 +26,8 @@ from app.modules.reports.constants import ReportResponseKey
|
||||
from app.modules.reports.chart import lifecycle_chart_alt, render_lifecycle_chart
|
||||
from app.modules.feishu.service import FeishuService
|
||||
from app.modules.reports.services import ReportService
|
||||
from app.modules.market.chart import render_market_chart
|
||||
from app.modules.market.service import MarketService
|
||||
from app.modules.risk.constants import RiskSummaryKey
|
||||
from app.modules.risk.services import RiskService
|
||||
|
||||
@@ -38,20 +40,48 @@ RISK_TITLE = "风险预警"
|
||||
DEFAULT_AI_PROMPT = "请说明你能做什么。"
|
||||
RULE_TITLE = "AI 学习规则"
|
||||
RULE_CREATE_PATTERN = re.compile(r"^学习规则(?:\s+(\d{1,3}))?\s*[::]\s*(.*)$")
|
||||
MARKET_RULE_CREATE_PATTERN = re.compile(
|
||||
r"^学习市场规则(?:\s+(\d{1,3}))?\s*[::]\s*(.*)$"
|
||||
)
|
||||
RULE_DISABLE_PATTERN = re.compile(r"^停用规则\s+(MEM-[A-Za-z0-9-]+)$", re.IGNORECASE)
|
||||
RULE_ENABLE_PATTERN = re.compile(r"^启用规则\s+(MEM-[A-Za-z0-9-]+)$", re.IGNORECASE)
|
||||
RULE_LIST_COMMANDS = {"查看规则", "规则列表"}
|
||||
RULE_COMMAND_PREFIXES = ("学习规则", "查看规则", "规则列表", "停用规则", "启用规则")
|
||||
RULE_LIST_COMMANDS = {"查看规则", "规则列表", "查看市场规则"}
|
||||
RULE_COMMAND_PREFIXES = (
|
||||
"学习市场规则",
|
||||
"学习规则",
|
||||
"查看市场规则",
|
||||
"查看规则",
|
||||
"规则列表",
|
||||
"停用规则",
|
||||
"启用规则",
|
||||
)
|
||||
RULE_COMMAND_HELP = (
|
||||
"规则指令格式:\n"
|
||||
"学习规则:<规则内容>\n"
|
||||
"学习规则 80:<规则内容>\n"
|
||||
"学习市场规则 80:<仅用于市场分析的规则内容>\n"
|
||||
"查看规则\n"
|
||||
"停用规则 <规则编号>\n"
|
||||
"启用规则 <规则编号>"
|
||||
)
|
||||
PROJECT_FINANCE_PATTERN = re.compile(r"^项目资金\s+(.+)$")
|
||||
FINANCE_COMMANDS = {"资金需求", "未来30天资金需求"}
|
||||
STOCK_ANALYSIS_PATTERN = re.compile(
|
||||
r"^(?:股票分析|估值分析|财报分析)\s+([0-9]{6}(?:\.(?:SH|SZ|BJ))?)$", re.IGNORECASE
|
||||
)
|
||||
WATCHLIST_ADD_PATTERN = re.compile(r"^加入自选\s+([0-9]{6}(?:\.(?:SH|SZ|BJ))?)$", re.IGNORECASE)
|
||||
MARKET_COMMANDS = {
|
||||
"市场分析",
|
||||
"今日收盘分析",
|
||||
"本周市场分析",
|
||||
"宏观金融分析",
|
||||
"最新公告",
|
||||
}
|
||||
INDUSTRY_ANALYSIS_PATTERN = re.compile(r"^行业分析\s+(.+)$")
|
||||
STOCK_COMPARE_PATTERN = re.compile(
|
||||
r"^股票对比\s+([0-9]{6}(?:\.(?:SH|SZ|BJ))?)\s+" r"([0-9]{6}(?:\.(?:SH|SZ|BJ))?)$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _parse_content_text(content: Any) -> str:
|
||||
@@ -59,9 +89,7 @@ def _parse_content_text(content: Any) -> str:
|
||||
|
||||
if isinstance(content, dict):
|
||||
return str(
|
||||
content.get(FeishuPayloadKey.TEXT)
|
||||
or content.get(FeishuPayloadKey.CONTENT)
|
||||
or ""
|
||||
content.get(FeishuPayloadKey.TEXT) or content.get(FeishuPayloadKey.CONTENT) or ""
|
||||
)
|
||||
if not isinstance(content, str):
|
||||
return ""
|
||||
@@ -70,11 +98,7 @@ def _parse_content_text(content: Any) -> str:
|
||||
except json.JSONDecodeError:
|
||||
return content
|
||||
if isinstance(data, dict):
|
||||
return str(
|
||||
data.get(FeishuPayloadKey.TEXT)
|
||||
or data.get(FeishuPayloadKey.CONTENT)
|
||||
or ""
|
||||
)
|
||||
return str(data.get(FeishuPayloadKey.TEXT) or data.get(FeishuPayloadKey.CONTENT) or "")
|
||||
return content
|
||||
|
||||
|
||||
@@ -163,6 +187,10 @@ class FeishuCommandService:
|
||||
if finance_result is not None:
|
||||
return finance_result
|
||||
|
||||
market_result = self._handle_market_command(command_text, chat_id, actor, auto_reply)
|
||||
if market_result is not None:
|
||||
return market_result
|
||||
|
||||
if any(keyword in command_text for keyword in DAILY_REPORT_KEYWORDS):
|
||||
report = ReportService(self.db).daily_brief()
|
||||
if auto_reply:
|
||||
@@ -284,9 +312,7 @@ class FeishuCommandService:
|
||||
if command_text not in FINANCE_COMMANDS and project_match is None:
|
||||
return None
|
||||
command = (
|
||||
FeishuCommandName.PROJECT_FINANCE
|
||||
if project_match
|
||||
else FeishuCommandName.FINANCE_NEEDS
|
||||
FeishuCommandName.PROJECT_FINANCE if project_match else FeishuCommandName.FINANCE_NEEDS
|
||||
)
|
||||
if not get_settings().finance_needs_enabled:
|
||||
content = "项目资金需求分析尚未启用,请先配置并启用财务只读同步。"
|
||||
@@ -362,6 +388,184 @@ class FeishuCommandService:
|
||||
report[ReportResponseKey.LINES],
|
||||
)
|
||||
|
||||
def _handle_market_command(
|
||||
self, text: str, chat_id: str | None, actor: str, auto_reply: bool
|
||||
) -> dict[str, Any] | None:
|
||||
stock = STOCK_ANALYSIS_PATTERN.fullmatch(text)
|
||||
add = WATCHLIST_ADD_PATTERN.fullmatch(text)
|
||||
industry = INDUSTRY_ANALYSIS_PATTERN.fullmatch(text)
|
||||
comparison = STOCK_COMPARE_PATTERN.fullmatch(text)
|
||||
if (
|
||||
text not in MARKET_COMMANDS
|
||||
and text != "查看自选"
|
||||
and not stock
|
||||
and not add
|
||||
and not industry
|
||||
and not comparison
|
||||
):
|
||||
return None
|
||||
if not get_settings().market_analysis_enabled:
|
||||
content = "市场分析尚未启用,请配置市场数据源后启用。"
|
||||
response = (
|
||||
self._send_text_if_configured(chat_id, content, actor) if auto_reply else None
|
||||
)
|
||||
return _command_result(
|
||||
FeishuCommandName.MARKET_OVERVIEW,
|
||||
FeishuReplyType.TEXT,
|
||||
"市场分析",
|
||||
content,
|
||||
response,
|
||||
)
|
||||
service = MarketService(self.db)
|
||||
if add:
|
||||
if get_settings().read_only_mode:
|
||||
content = "当前为只读模式,不能修改自选股。请由管理员启用操作后重试。"
|
||||
response = (
|
||||
self._send_text_if_configured(chat_id, content, actor)
|
||||
if auto_reply
|
||||
else None
|
||||
)
|
||||
return _command_result(
|
||||
FeishuCommandName.WATCHLIST_ADD,
|
||||
FeishuReplyType.TEXT,
|
||||
"自选股",
|
||||
content,
|
||||
response,
|
||||
)
|
||||
item = service.add_watchlist(actor, add.group(1))
|
||||
content = f"已加入自选:{item['symbol']}"
|
||||
response = (
|
||||
self._send_text_if_configured(chat_id, content, actor) if auto_reply else None
|
||||
)
|
||||
return _command_result(
|
||||
FeishuCommandName.WATCHLIST_ADD, FeishuReplyType.TEXT, "自选股", content, response
|
||||
)
|
||||
if text == "查看自选":
|
||||
items = service.watchlist(actor)
|
||||
content = "自选股:" + ("、".join(item["symbol"] for item in items) or "暂无")
|
||||
response = (
|
||||
self._send_text_if_configured(chat_id, content, actor) if auto_reply else None
|
||||
)
|
||||
return _command_result(
|
||||
FeishuCommandName.WATCHLIST_LIST, FeishuReplyType.TEXT, "自选股", content, response
|
||||
)
|
||||
if text == "最新公告":
|
||||
items = service.announcements(limit=10)["items"]
|
||||
content = (
|
||||
"最新公告:\n"
|
||||
+ "\n".join(
|
||||
f"- {item['announcement_date']} {item['symbol'] or '市场'}:{item['title']}"
|
||||
for item in items
|
||||
)
|
||||
if items
|
||||
else "公告元数据尚未接入。"
|
||||
)
|
||||
response = (
|
||||
self._send_text_if_configured(chat_id, content, actor) if auto_reply else None
|
||||
)
|
||||
return _command_result(
|
||||
FeishuCommandName.MARKET_ANNOUNCEMENTS,
|
||||
FeishuReplyType.TEXT,
|
||||
"最新公告",
|
||||
content,
|
||||
response,
|
||||
)
|
||||
if industry:
|
||||
try:
|
||||
data = service.industry_analysis(industry.group(1).strip())
|
||||
content = (
|
||||
f"{data['industry']} 平均涨跌 {data['average_pct_change']}%\n"
|
||||
+ "\n".join(
|
||||
f"- {item['name']}({item['symbol']}):{item['pct_change']}%"
|
||||
for item in data["items"][:10]
|
||||
)
|
||||
)
|
||||
except HTTPException:
|
||||
content = "未找到该行业的最新市场数据。"
|
||||
response = (
|
||||
self._send_text_if_configured(chat_id, content, actor) if auto_reply else None
|
||||
)
|
||||
return _command_result(
|
||||
FeishuCommandName.MARKET_OVERVIEW,
|
||||
FeishuReplyType.TEXT,
|
||||
"行业分析",
|
||||
content,
|
||||
response,
|
||||
)
|
||||
if comparison:
|
||||
try:
|
||||
content = service.compare_stocks([comparison.group(1), comparison.group(2)])[
|
||||
"content"
|
||||
]
|
||||
except HTTPException:
|
||||
content = "至少一只股票缺少可用行情,暂时无法比较。"
|
||||
response = (
|
||||
self._send_text_if_configured(chat_id, content, actor) if auto_reply else None
|
||||
)
|
||||
return _command_result(
|
||||
FeishuCommandName.STOCK_ANALYSIS,
|
||||
FeishuReplyType.TEXT,
|
||||
"股票对比",
|
||||
content,
|
||||
response,
|
||||
)
|
||||
command = FeishuCommandName.STOCK_ANALYSIS if stock else FeishuCommandName.MARKET_OVERVIEW
|
||||
if text == "宏观金融分析":
|
||||
command = FeishuCommandName.MARKET_MACRO
|
||||
try:
|
||||
if stock:
|
||||
report = service.stock_analysis(stock.group(1), True, actor)
|
||||
elif text == "本周市场分析":
|
||||
report = service.weekly_overview(include_ai=True, actor=actor)
|
||||
elif text == "宏观金融分析":
|
||||
report = service.macro_analysis(include_ai=True, actor=actor)
|
||||
else:
|
||||
report = service.market_overview(include_ai=True, actor=actor)
|
||||
except HTTPException:
|
||||
content = "未找到该股票的可用行情,请确认代码或先执行行情同步。"
|
||||
response = (
|
||||
self._send_text_if_configured(chat_id, content, actor) if auto_reply else None
|
||||
)
|
||||
return _command_result(command, FeishuReplyType.TEXT, "股票分析", content, response)
|
||||
ai = report.get("ai_analysis") or {}
|
||||
if not report.get("data_available"):
|
||||
content = "市场数据未接入,暂不生成分析报告。"
|
||||
elif not ai.get("ok"):
|
||||
content = "AI 当前不可用,本次市场分析报告未发送。"
|
||||
else:
|
||||
content = report["content"]
|
||||
response = None
|
||||
if auto_reply:
|
||||
if ai.get("ok"):
|
||||
if text == "宏观金融分析":
|
||||
response = self._send_text_if_configured(chat_id, content, actor)
|
||||
else:
|
||||
image = self.feishu.upload_image(render_market_chart(report), actor)
|
||||
image_key = (image.get("data") or {}).get("image_key")
|
||||
if not image_key:
|
||||
raise ValueError("Feishu image upload did not return image_key")
|
||||
card = FeishuService.build_basic_card(
|
||||
report["title"],
|
||||
report["lines"],
|
||||
image_key=image_key,
|
||||
image_alt=report["title"],
|
||||
)
|
||||
response = self.feishu.send_card(card, receive_id=chat_id, actor=actor)
|
||||
else:
|
||||
response = self._send_text_if_configured(chat_id, content, actor)
|
||||
return _command_result(
|
||||
command,
|
||||
(
|
||||
FeishuReplyType.CARD
|
||||
if ai.get("ok") and text != "宏观金融分析"
|
||||
else FeishuReplyType.TEXT
|
||||
),
|
||||
report["title"],
|
||||
content,
|
||||
response,
|
||||
report["lines"] if ai.get("ok") else None,
|
||||
)
|
||||
|
||||
def _send_finance_card_if_configured(
|
||||
self,
|
||||
chat_id: str | None,
|
||||
@@ -401,13 +605,30 @@ class FeishuCommandService:
|
||||
command = FeishuCommandName.RULE_DISABLE
|
||||
elif command_text.startswith("启用规则"):
|
||||
command = FeishuCommandName.RULE_ENABLE
|
||||
elif command_text.startswith(("查看规则", "规则列表")):
|
||||
elif command_text.startswith(("查看市场规则", "查看规则", "规则列表")):
|
||||
command = FeishuCommandName.RULE_LIST
|
||||
else:
|
||||
command = FeishuCommandName.RULE_CREATE
|
||||
if command in {
|
||||
FeishuCommandName.RULE_CREATE,
|
||||
FeishuCommandName.RULE_DISABLE,
|
||||
FeishuCommandName.RULE_ENABLE,
|
||||
} and get_settings().read_only_mode:
|
||||
content = "当前为只读模式,不能新增或修改学习规则。请由管理员启用操作后重试。"
|
||||
provider_response = (
|
||||
self._send_text_if_configured(chat_id, content, actor) if auto_reply else None
|
||||
)
|
||||
return _command_result(
|
||||
command,
|
||||
FeishuReplyType.TEXT,
|
||||
RULE_TITLE,
|
||||
content,
|
||||
provider_response,
|
||||
)
|
||||
content = RULE_COMMAND_HELP
|
||||
try:
|
||||
create_match = RULE_CREATE_PATTERN.fullmatch(command_text)
|
||||
market_create_match = MARKET_RULE_CREATE_PATTERN.fullmatch(command_text)
|
||||
create_match = market_create_match or RULE_CREATE_PATTERN.fullmatch(command_text)
|
||||
disable_match = RULE_DISABLE_PATTERN.fullmatch(command_text)
|
||||
enable_match = RULE_ENABLE_PATTERN.fullmatch(command_text)
|
||||
memory = AIMemoryService(self.db)
|
||||
@@ -422,10 +643,10 @@ class FeishuCommandService:
|
||||
else:
|
||||
rule = memory.create_rule(
|
||||
content=rule_content,
|
||||
scope="global",
|
||||
subject="company",
|
||||
scope="market" if market_create_match else "global",
|
||||
subject="market" if market_create_match else "company",
|
||||
priority=priority,
|
||||
tags=["feishu"],
|
||||
tags=["feishu", *(["market"] if market_create_match else [])],
|
||||
actor=actor,
|
||||
)
|
||||
content = (
|
||||
@@ -438,6 +659,7 @@ class FeishuCommandService:
|
||||
elif command_text in RULE_LIST_COMMANDS:
|
||||
command = FeishuCommandName.RULE_LIST
|
||||
rules = memory.list_rules(
|
||||
scope="market" if command_text == "查看市场规则" else None,
|
||||
status_filter=AIMemoryStatus.ACTIVE,
|
||||
limit=20,
|
||||
)
|
||||
@@ -457,9 +679,7 @@ class FeishuCommandService:
|
||||
elif disable_match or enable_match:
|
||||
enabled = enable_match is not None
|
||||
command = (
|
||||
FeishuCommandName.RULE_ENABLE
|
||||
if enabled
|
||||
else FeishuCommandName.RULE_DISABLE
|
||||
FeishuCommandName.RULE_ENABLE if enabled else FeishuCommandName.RULE_DISABLE
|
||||
)
|
||||
match = enable_match or disable_match
|
||||
rule = memory.update_rule(
|
||||
|
||||
Reference in New Issue
Block a user