diff --git a/.env.example b/.env.example index c9e1e940220..413b6234932 100644 --- a/.env.example +++ b/.env.example @@ -402,6 +402,8 @@ BRAVE_API_KEYS= # 因此默认关闭。推荐配置自建实例地址(SEARXNG_BASE_URLS),或使用上方任一带 key 的搜索渠道。 SEARXNG_BASE_URLS= SEARXNG_PUBLIC_INSTANCES_ENABLED=false +# 自建 SearXNG 单次搜索超时(秒,默认 10,最小 1);公共实例不受此配置影响 +SEARXNG_TIMEOUT_SECONDS=10 # =================================== # Social Sentiment Intelligence (US stocks only) diff --git a/.github/workflows/00-daily-analysis.yml b/.github/workflows/00-daily-analysis.yml index 2a72fb1e49b..2a8e173bcf8 100644 --- a/.github/workflows/00-daily-analysis.yml +++ b/.github/workflows/00-daily-analysis.yml @@ -309,6 +309,7 @@ jobs: BRAVE_API_KEYS: ${{ secrets.BRAVE_API_KEYS }} SEARXNG_BASE_URLS: ${{ vars.SEARXNG_BASE_URLS || secrets.SEARXNG_BASE_URLS }} SEARXNG_PUBLIC_INSTANCES_ENABLED: ${{ vars.SEARXNG_PUBLIC_INSTANCES_ENABLED || secrets.SEARXNG_PUBLIC_INSTANCES_ENABLED }} + SEARXNG_TIMEOUT_SECONDS: ${{ vars.SEARXNG_TIMEOUT_SECONDS || secrets.SEARXNG_TIMEOUT_SECONDS }} # ========================================== # 通知渠道(可同时配置多个,全部推送) diff --git a/api/v1/__init__.py b/api/v1/__init__.py index 2c308a5878d..cc36f6d1fd3 100644 --- a/api/v1/__init__.py +++ b/api/v1/__init__.py @@ -5,9 +5,17 @@ =================================== 职责: -1. 导出 v1 版本 API 的路由 +1. 延迟导出 v1 版本 API 的路由,避免 schema import 触发整棵 endpoint 导入树 """ -from api.v1.router import router as api_v1_router +from typing import Any __all__ = ["api_v1_router"] + + +def __getattr__(name: str) -> Any: + if name != "api_v1_router": + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + from api.v1.router import router + + return router diff --git a/api/v1/endpoints/stocks.py b/api/v1/endpoints/stocks.py index e435704a8a9..794d5cbe43a 100644 --- a/api/v1/endpoints/stocks.py +++ b/api/v1/endpoints/stocks.py @@ -24,6 +24,7 @@ ExtractItem, KLineData, StockHistoryResponse, + StockProfileResponse, StockQuote, ) from api.v1.schemas.history import WatchlistRequest, WatchlistResponse @@ -39,6 +40,8 @@ parse_import_from_text, ) from src.services.stock_service import StockService +from src.services.stock_profile_service import InvalidStockProfileCode, StockProfileService +from src.services.run_diagnostics import sanitize_diagnostic_text from src.services.stock_list_parser import split_stock_list from src.services.system_config_service import SystemConfigService from data_provider.base import normalize_stock_code @@ -82,6 +85,9 @@ def _write_watchlist_codes(service: SystemConfigService, codes: list) -> None: r"|\d{1,5}\.HK" # HK suffix format r"|HK\d{1,5}" # HK prefix format r"|\d{5}" # bare 5-digit HK code + r"|\d{4,5}\.T" # Japan Yahoo suffix format + r"|\d{6}\.(?:KS|KQ)" # Korea Yahoo suffix format + r"|\d{4,6}\.(?:TW|TWO)" # Taiwan Yahoo suffix format r"|[A-Z]{1,5}(?:\.(?:US|[A-Z]))?" # US ticker r")$", re.IGNORECASE, @@ -405,6 +411,40 @@ def remove_from_watchlist( ) +@router.get( + "/{stock_code}/profile", + response_model=StockProfileResponse, + responses={ + 400: {"description": "股票代码无效", "model": ErrorResponse}, + 500: {"description": "服务器错误", "model": ErrorResponse}, + }, + summary="获取个股研究聚合档案", + description="按独立质量状态聚合行情、历史、研究产物、资讯、持仓关系和监控规则。", +) +def get_stock_profile( + stock_code: str, + history_days: int = Query(60, ge=1, le=365, description="日线历史天数"), +) -> StockProfileResponse: + """Return partial profile data without failing on one optional block.""" + _validate_and_normalize_stock_code(stock_code) + try: + return StockProfileResponse( + **StockProfileService().get_profile(stock_code, history_days=history_days) + ) + except InvalidStockProfileCode: + raise HTTPException( + status_code=400, + detail={"error": "invalid_stock_code", "message": "股票代码与交易所不匹配"}, + ) + except Exception as exc: + sanitized = sanitize_diagnostic_text(str(exc), max_length=300) or "internal profile error" + logger.error("获取个股研究聚合档案失败: %s", sanitized) + raise HTTPException( + status_code=500, + detail={"error": "internal_error", "message": "获取个股研究聚合档案失败"}, + ) + + @router.get( "/{stock_code}/quote", response_model=StockQuote, diff --git a/api/v1/schemas/__init__.py b/api/v1/schemas/__init__.py index 62d98b70eb4..95fd63fb832 100644 --- a/api/v1/schemas/__init__.py +++ b/api/v1/schemas/__init__.py @@ -48,6 +48,7 @@ StockQuote, StockHistoryResponse, KLineData, + StockProfileResponse, ) from api.v1.schemas.backtest import ( BacktestRunRequest, @@ -184,6 +185,7 @@ "StockQuote", "StockHistoryResponse", "KLineData", + "StockProfileResponse", # backtest "BacktestRunRequest", "BacktestRunResponse", diff --git a/api/v1/schemas/stocks.py b/api/v1/schemas/stocks.py index 2f962d4f374..7f65807a365 100644 --- a/api/v1/schemas/stocks.py +++ b/api/v1/schemas/stocks.py @@ -9,10 +9,16 @@ 2. 定义历史 K 线数据模型 """ -from typing import Optional, List +from typing import Dict, Literal, Optional, List from pydantic import BaseModel, ConfigDict, Field +from api.v1.schemas.history import HistoryItem +from api.v1.schemas.intelligence import IntelligenceItem +from api.v1.schemas.research_artifact import ResearchArtifact + +StockProfileStatus = Literal["fresh", "partial", "unavailable"] + class StockQuote(BaseModel): """股票实时行情""" @@ -106,3 +112,77 @@ class StockHistoryResponse(BaseModel): "data": [] } }) + + +class StockProfileQuoteBlock(BaseModel): + status: StockProfileStatus + data: Optional[StockQuote] = None + limitations: List[str] = Field(default_factory=list) + + +class StockProfileHistoryBlock(BaseModel): + status: StockProfileStatus + period: Literal["daily"] = "daily" + data: List[KLineData] = Field(default_factory=list) + limitations: List[str] = Field(default_factory=list) + + +class StockProfileResearchData(BaseModel): + latest_report: Optional[HistoryItem] = None + recent_reports: List[HistoryItem] = Field(default_factory=list) + structured_report: Optional[ResearchArtifact] = None + + +class StockProfileResearchBlock(BaseModel): + status: StockProfileStatus + data: StockProfileResearchData = Field(default_factory=StockProfileResearchData) + limitations: List[str] = Field(default_factory=list) + + +class StockProfileIntelligenceBlock(BaseModel): + status: StockProfileStatus + items: List[IntelligenceItem] = Field(default_factory=list) + limitations: List[str] = Field(default_factory=list) + + +class StockProfilePortfolioRelation(BaseModel): + held: bool = False + matched_markets: List[str] = Field(default_factory=list) + + +class StockProfilePortfolioBlock(BaseModel): + status: StockProfileStatus + data: StockProfilePortfolioRelation = Field(default_factory=StockProfilePortfolioRelation) + limitations: List[str] = Field(default_factory=list) + + +class StockProfileMonitorData(BaseModel): + total_rule_count: int = 0 + enabled_rule_count: int = 0 + rule_ids: List[int] = Field(default_factory=list) + + +class StockProfileMonitorBlock(BaseModel): + status: StockProfileStatus + data: StockProfileMonitorData = Field(default_factory=StockProfileMonitorData) + limitations: List[str] = Field(default_factory=list) + + +class StockProfileEvidenceQuality(BaseModel): + status: StockProfileStatus + blocks: Dict[str, StockProfileStatus] = Field(default_factory=dict) + limitations: List[str] = Field(default_factory=list) + + +class StockProfileResponse(BaseModel): + requested_code: str + canonical_code: str + market: Literal["cn", "hk", "us", "jp", "kr", "tw"] + as_of: str + quote: StockProfileQuoteBlock + history: StockProfileHistoryBlock + research: StockProfileResearchBlock + intelligence: StockProfileIntelligenceBlock + portfolio: StockProfilePortfolioBlock + monitors: StockProfileMonitorBlock + evidence_quality: StockProfileEvidenceQuality diff --git a/apps/dsa-desktop/package-lock.json b/apps/dsa-desktop/package-lock.json index 5e47fe31810..1e5f78b7762 100644 --- a/apps/dsa-desktop/package-lock.json +++ b/apps/dsa-desktop/package-lock.json @@ -2827,9 +2827,19 @@ } }, "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", + "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { "argparse": "^2.0.1" diff --git a/apps/dsa-desktop/package.json b/apps/dsa-desktop/package.json index 61b243d7e6d..49d74c29ae4 100644 --- a/apps/dsa-desktop/package.json +++ b/apps/dsa-desktop/package.json @@ -61,6 +61,7 @@ } }, "overrides": { - "builder-util-runtime": "9.7.0" + "builder-util-runtime": "9.7.0", + "js-yaml": "4.3.1" } } diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e313ab921b6..6d49172cace 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,8 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/). > For user-friendly release highlights, see the [GitHub Releases](https://github.com/ZhuLinsen/daily_stock_analysis/releases) page. ## [Unreleased] +- [新功能] 新增 `SEARXNG_TIMEOUT_SECONDS` 配置自建 SearXNG 单次搜索超时(默认 10 秒),已接线全部 SearchService 构造入口(含题材搜索子进程重建)与默认 GitHub Actions 工作流 + - [修复] 美股日线路由现按各数据源当前优先级排序,单项 `*_PRIORITY` 配置(如 `YFINANCE_PRIORITY=0`)对美股即时生效;指数固定首选与 Longbridge preferred 语义保持不变 +- [新功能] 新增个股研究聚合 API,以统一 canonical code 返回行情、历史、研究产物、资讯、缓存持仓关系和监控规则,并对每个块独立标记 fresh/partial/unavailable。 +- [修复] 个股研究聚合拒绝交易所冲突的股票身份,在市场限定后无历史候选时保持空结果,兼容市场限定裸码与混合大小写旧数据,并从独立基本面快照补齐 ResearchArtifact 的财报与分红证据。 + - [新功能] 支持通过 `main.py --stocks` 一次性分析已登记板块指数,自动使用指数适用的数据与分析能力,并保持报告、历史和决策信号兼容。 - [修复] `main.py --stocks` 在解析股票列表前先 best-effort 刷新股票索引注册表,保证首次运行能吃到刷新后的指数 alias/身份;刷新失败、超时或禁用不阻断分析。 - [修复] 交易日过滤对市场未知的指数 code(如 `sh000016`/`csi930955`/`930955.CSI`)按 `market=cn` 参与 A 股休市过滤,避免休市日指数被 fail-open 保留;市场仍未知的非指数 code 继续保留。 @@ -21,6 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). - [新功能] 新增 ResearchArtifact 结构化研究产物契约,在 `AnalysisReport.structured_report` 中承载 Thesis、Evidence、Invalidation Conditions、Next Actions 和 Data Quality,并提供从现有报告生成结构化产物的后端 helper 与 Web 类型。 - [修复] 同步 ResearchArtifact 与 `AnalysisReport.structured_report` 到静态 OpenAPI,避免公开 API 规格与运行时契约漂移。 - [修复] Linux/Docker 分享图补齐 Noto CJK 字体与中韩文字体栈,避免 PNG 只显示数字和英文、中文或韩文内容消失。 +- [修复] 股票名称归一:AkShare 部分名称带无意义内嵌空格(“五 粮 液”、“万 科A”)与全角宽度拼写(“京东方A” 的全角 A),统一经 `_normalize_stock_name()` 做 NFKC 宽度归一 + 去空白(原 `_compact_stock_name` 仅去空白):本地映射初值、`_build_name_map_from_df()` 构建与 `extend_AkShare()` 合并、磁盘缓存加载三个入库口(含归一后为空的条目守卫)与 `resolver_name_to_code_list()` / `is_known_stock_name()` / `resolve_name_to_code()` 三个查询入口同源归一;消除空格/全角拼写与本地无空格半角拼写比较不相等造成的假性改名别名,源形态输入(带空格/全角)与常规拼写同样可解析,覆盖 `/analyze` API、按名称导入与 Bot 文本解析等全部调用路径;全角拼写此前与分词管道 NFKC 归一后的半角输入(“京东方A”)永不相等——全名精确匹配落空且会被更短库内名误切出错误实体(“京东”),归一后半角/全角输入产出一致、展示名统一为归一拼写;磁盘缓存中的历史未归一数据(带空格/全角)经合并与加载入口自动归一,无需迁移。 - [新功能] Web Chat 意图识别层新增分词模块:`web_intent_tokenizer` 六步管道(多股票全名实体扫描 → 标点/空白切分 → 代码形提取 → 市场关键词 → 无歧义关键词 → 残存 gap 多策略 DFS 匹配)把用户消息切分为携带语义标签的 Token 序列;配套 `web_intent_types` 数据字典(Token 结构、Market 枚举、21 个语义 tag、clean/extend 双词池与正则机器)。核心原则"宁可不做,不可做错":Step 1~5 只做精确匹配,Step 6 要求整段 TAG 全覆盖(交叉验证)才产出,未覆盖片段保持空 tag 交下游 LLM 兜底;代码形 token 辨认为 `stock_code`(附 code/name/market 三元组)/ `wrong_{market}_code` / `unknown_{market}_code` 三态,token 层代码拼写统一 canonical 归一(a=6 位裸数字、hk=HK+5 位、us=大写 ticker)。意图枚举与意图识别结果随后续 `web_intent_resolver` PR 引入。新增 183 个分词单元测试。 diff --git a/docs/INDEX.md b/docs/INDEX.md index 74f0cb7a4a1..bba4a7d3bee 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -45,6 +45,7 @@ | [Bot 命令与接入](bot-command.md) | Bot 命令、Webhook、平台接入和回调说明 | | [Bot 平台配置](bot/) | 飞书、钉钉、Discord 等 Bot 配置截图和补充说明 | | [实时告警中心](alerts.md) | EventMonitor 基线、Web 规则管理、通知结果、冷却状态和 Phase 边界 | +| [个股研究聚合 API](stock-profile-api.md) | 单一 stock-profile 契约、分块质量状态、代码归一与后续 Web 边界 | | [DecisionSignal 决策信号专题](decision-signals.md) | AI 建议池字段语义、API、Web 展示、告警/通知/组合风险联动、后验评估、脱敏、迁移与回滚 | | [ResearchArtifact 结构化研究产物](research-artifact.md) | structured_report 字段、Thesis / Evidence / Invalidation / Next Action / Data Quality 契约和旧报告兼容边界 | | [资讯 / 情报源](intelligence-sources.md) | RSS/Atom 合规资讯源配置、测试、拉取、去重、存储、查询与安全边界 | diff --git a/docs/INDEX_EN.md b/docs/INDEX_EN.md index e41a620c941..488688c9a5a 100644 --- a/docs/INDEX_EN.md +++ b/docs/INDEX_EN.md @@ -45,6 +45,7 @@ This is the entry point for project documentation. The README covers the project | [Bot Commands (EN)](bot-command_EN.md) | Bot commands, webhooks, platform integration, and callback behavior | | [Bot Platform Docs](bot/) ![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat) (Chinese-only) | Feishu, DingTalk, Discord, and related Bot configuration screenshots and notes | | [Real-Time Alert Center](alerts.md) ![P4 Badge](https://img.shields.io/badge/P4-yellow?style=flat) (Chinese-only) | EventMonitor baseline, Web rule management, notification attempts, cooldown state, and phase boundaries | +| [Stock Profile API](stock-profile-api.md) ![P1 Badge](https://img.shields.io/badge/P1-yellow?style=flat) (Chinese-only) | Single stock-profile contract, per-block quality status, code normalization, and Web phase boundaries | | [DecisionSignal Topic](decision-signals.md) ![P7 Badge](https://img.shields.io/badge/P7-orange?style=flat) (Chinese-only) | AI signal fields, API, Web display, alert/notification/portfolio-risk linkage, outcome evaluation, redaction, migration, and rollback | | [ResearchArtifact Contract](research-artifact.md) ![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat) (Chinese-only) | Structured thesis, evidence, invalidation conditions, deterministic fallback identity, and the boundary before persistence/API integration | | [Analysis Context Pack Contract, Runtime Consumption, And Visibility](analysis-context-pack.md) ![P6 Badge](https://img.shields.io/badge/P6-orange?style=flat) (Chinese-only) | AnalysisContextPack first-scope boundaries, field quality states, P1/P2 internal contracts, P3 prompt-summary consumption, P4 history/API/Web low-sensitivity visibility, P5 data-quality scoring, and P6 migration/rollback notes, plus source anchors; the full guide adds #1386 market-phase analysis, migration, and rollback entry points | diff --git a/docs/architecture/api_spec.json b/docs/architecture/api_spec.json index 0578455620b..7170ee7eb37 100644 --- a/docs/architecture/api_spec.json +++ b/docs/architecture/api_spec.json @@ -2736,6 +2736,83 @@ } } } + }, + "/api/v1/stocks/{stock_code}/profile": { + "get": { + "tags": [ + "Stocks" + ], + "summary": "获取个股研究聚合档案", + "description": "按独立质量状态聚合行情、历史、研究产物、资讯、持仓关系和监控规则。", + "operationId": "get_stock_profile_api_v1_stocks__stock_code__profile_get", + "parameters": [ + { + "name": "stock_code", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Stock Code" + } + }, + { + "name": "history_days", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 365, + "minimum": 1, + "description": "日线历史天数", + "default": 60, + "title": "History Days" + }, + "description": "日线历史天数" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StockProfileResponse" + } + } + } + }, + "400": { + "description": "股票代码无效", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "500": { + "description": "服务器错误", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } } }, "components": { @@ -8362,6 +8439,635 @@ ], "title": "DataProviderCapability", "description": "Visible capability metadata for one data provider." + }, + "StockProfileResearchBlock": { + "properties": { + "status": { + "type": "string", + "enum": [ + "fresh", + "partial", + "unavailable" + ], + "title": "Status" + }, + "data": { + "$ref": "#/components/schemas/StockProfileResearchData" + }, + "limitations": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Limitations" + } + }, + "type": "object", + "required": [ + "status" + ], + "title": "StockProfileResearchBlock" + }, + "StockProfileResearchData": { + "properties": { + "latest_report": { + "anyOf": [ + { + "$ref": "#/components/schemas/HistoryItem" + }, + { + "type": "null" + } + ] + }, + "recent_reports": { + "items": { + "$ref": "#/components/schemas/HistoryItem" + }, + "type": "array", + "title": "Recent Reports" + }, + "structured_report": { + "anyOf": [ + { + "$ref": "#/components/schemas/ResearchArtifact" + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "title": "StockProfileResearchData" + }, + "StockProfileHistoryBlock": { + "properties": { + "status": { + "type": "string", + "enum": [ + "fresh", + "partial", + "unavailable" + ], + "title": "Status" + }, + "period": { + "type": "string", + "const": "daily", + "title": "Period", + "default": "daily" + }, + "data": { + "items": { + "$ref": "#/components/schemas/KLineData" + }, + "type": "array", + "title": "Data" + }, + "limitations": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Limitations" + } + }, + "type": "object", + "required": [ + "status" + ], + "title": "StockProfileHistoryBlock" + }, + "KLineData": { + "properties": { + "date": { + "type": "string", + "title": "Date", + "description": "日期" + }, + "open": { + "type": "number", + "title": "Open", + "description": "开盘价" + }, + "high": { + "type": "number", + "title": "High", + "description": "最高价" + }, + "low": { + "type": "number", + "title": "Low", + "description": "最低价" + }, + "close": { + "type": "number", + "title": "Close", + "description": "收盘价" + }, + "volume": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Volume", + "description": "成交量" + }, + "amount": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Amount", + "description": "成交额" + }, + "change_percent": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Change Percent", + "description": "涨跌幅 (%)" + } + }, + "type": "object", + "required": [ + "date", + "open", + "high", + "low", + "close" + ], + "title": "KLineData", + "description": "K 线数据点", + "example": { + "amount": 18000000000, + "change_percent": 0.84, + "close": 1800.0, + "date": "2024-01-01", + "high": 1810.0, + "low": 1780.0, + "open": 1785.0, + "volume": 10000000 + } + }, + "ResearchResponse": { + "properties": { + "success": { + "type": "boolean", + "title": "Success" + }, + "content": { + "type": "string", + "title": "Content" + }, + "sources": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Sources" + }, + "token_usage": { + "type": "integer", + "title": "Token Usage", + "default": 0 + }, + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Error" + } + }, + "type": "object", + "required": [ + "success", + "content" + ], + "title": "ResearchResponse" + }, + "StockProfilePortfolioBlock": { + "properties": { + "status": { + "type": "string", + "enum": [ + "fresh", + "partial", + "unavailable" + ], + "title": "Status" + }, + "data": { + "$ref": "#/components/schemas/StockProfilePortfolioRelation" + }, + "limitations": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Limitations" + } + }, + "type": "object", + "required": [ + "status" + ], + "title": "StockProfilePortfolioBlock" + }, + "StockProfilePortfolioRelation": { + "properties": { + "held": { + "type": "boolean", + "title": "Held", + "default": false + }, + "matched_markets": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Matched Markets" + } + }, + "type": "object", + "title": "StockProfilePortfolioRelation" + }, + "StockProfileEvidenceQuality": { + "properties": { + "status": { + "type": "string", + "enum": [ + "fresh", + "partial", + "unavailable" + ], + "title": "Status" + }, + "blocks": { + "additionalProperties": { + "type": "string", + "enum": [ + "fresh", + "partial", + "unavailable" + ] + }, + "type": "object", + "title": "Blocks" + }, + "limitations": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Limitations" + } + }, + "type": "object", + "required": [ + "status" + ], + "title": "StockProfileEvidenceQuality" + }, + "ResearchRequest": { + "properties": { + "question": { + "type": "string", + "title": "Question" + }, + "stock_code": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Stock Code" + } + }, + "type": "object", + "required": [ + "question" + ], + "title": "ResearchRequest" + }, + "StockProfileMonitorBlock": { + "properties": { + "status": { + "type": "string", + "enum": [ + "fresh", + "partial", + "unavailable" + ], + "title": "Status" + }, + "data": { + "$ref": "#/components/schemas/StockProfileMonitorData" + }, + "limitations": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Limitations" + } + }, + "type": "object", + "required": [ + "status" + ], + "title": "StockProfileMonitorBlock" + }, + "StockProfileMonitorData": { + "properties": { + "total_rule_count": { + "type": "integer", + "title": "Total Rule Count", + "default": 0 + }, + "enabled_rule_count": { + "type": "integer", + "title": "Enabled Rule Count", + "default": 0 + }, + "rule_ids": { + "items": { + "type": "integer" + }, + "type": "array", + "title": "Rule Ids" + } + }, + "type": "object", + "title": "StockProfileMonitorData" + }, + "StockProfileIntelligenceBlock": { + "properties": { + "status": { + "type": "string", + "enum": [ + "fresh", + "partial", + "unavailable" + ], + "title": "Status" + }, + "items": { + "items": { + "$ref": "#/components/schemas/IntelligenceItem" + }, + "type": "array", + "title": "Items" + }, + "limitations": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Limitations" + } + }, + "type": "object", + "required": [ + "status" + ], + "title": "StockProfileIntelligenceBlock" + }, + "IntelligenceItem": { + "properties": { + "id": { + "type": "integer", + "title": "Id" + }, + "source_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Source Id" + }, + "source_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Source Name" + }, + "source_type": { + "type": "string", + "title": "Source Type" + }, + "title": { + "type": "string", + "title": "Title" + }, + "summary": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Summary" + }, + "url": { + "type": "string", + "title": "Url" + }, + "source": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Source" + }, + "published_at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Published At" + }, + "fetched_at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fetched At" + }, + "scope_type": { + "type": "string", + "title": "Scope Type" + }, + "scope_value": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Scope Value" + }, + "market": { + "type": "string", + "title": "Market" + } + }, + "type": "object", + "required": [ + "id", + "source_type", + "title", + "url", + "scope_type", + "market" + ], + "title": "IntelligenceItem" + }, + "StockProfileResponse": { + "properties": { + "requested_code": { + "type": "string", + "title": "Requested Code" + }, + "canonical_code": { + "type": "string", + "title": "Canonical Code" + }, + "market": { + "type": "string", + "enum": [ + "cn", + "hk", + "us", + "jp", + "kr", + "tw" + ], + "title": "Market" + }, + "as_of": { + "type": "string", + "title": "As Of" + }, + "quote": { + "$ref": "#/components/schemas/StockProfileQuoteBlock" + }, + "history": { + "$ref": "#/components/schemas/StockProfileHistoryBlock" + }, + "research": { + "$ref": "#/components/schemas/StockProfileResearchBlock" + }, + "intelligence": { + "$ref": "#/components/schemas/StockProfileIntelligenceBlock" + }, + "portfolio": { + "$ref": "#/components/schemas/StockProfilePortfolioBlock" + }, + "monitors": { + "$ref": "#/components/schemas/StockProfileMonitorBlock" + }, + "evidence_quality": { + "$ref": "#/components/schemas/StockProfileEvidenceQuality" + } + }, + "type": "object", + "required": [ + "requested_code", + "canonical_code", + "market", + "as_of", + "quote", + "history", + "research", + "intelligence", + "portfolio", + "monitors", + "evidence_quality" + ], + "title": "StockProfileResponse" + }, + "StockProfileQuoteBlock": { + "properties": { + "status": { + "type": "string", + "enum": [ + "fresh", + "partial", + "unavailable" + ], + "title": "Status" + }, + "data": { + "anyOf": [ + { + "$ref": "#/components/schemas/StockQuote" + }, + { + "type": "null" + } + ] + }, + "limitations": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Limitations" + } + }, + "type": "object", + "required": [ + "status" + ], + "title": "StockProfileQuoteBlock" } }, "securitySchemes": { diff --git a/docs/full-guide.md b/docs/full-guide.md index 330d5ce6c86..f0de651d7a2 100644 --- a/docs/full-guide.md +++ b/docs/full-guide.md @@ -165,6 +165,7 @@ daily_stock_analysis/ | `MINIMAX_API_KEYS` | [MiniMax](https://platform.minimax.io/) Coding Plan Web Search(结构化搜索结果) | 可选 | | `SEARXNG_BASE_URLS` | SearXNG 自建实例(无配额兜底,需在 settings.yml 启用 format: json);留空时仅在显式启用公共实例发现后使用 `searx.space` | 可选 | | `SEARXNG_PUBLIC_INSTANCES_ENABLED` | 是否在 `SEARXNG_BASE_URLS` 为空时自动从 `searx.space` 获取公共实例(默认 `false`)。公共实例普遍限流或未开启 JSON 输出,开启后每次分析可能多耗 30~60 秒且新闻面为空 | 可选 | +| `SEARXNG_TIMEOUT_SECONDS` | 自建 SearXNG 单次搜索超时(秒,默认 `10`,最小 `1`);实例较慢(如聚合引擎较多的 NAS 部署)时可调大,公共实例超时不受影响。GitHub Actions 需显式映射该变量 | 可选 | | `TUSHARE_TOKEN` | [Tushare Pro](https://tushare.pro/weborder/#/login?reg=834638 ) Token | 可选 | | `TUSHARE_HTTP_URL` | Tushare Pro HTTP 接入地址;留空(或未设置/空白)时使用官方端点 `http://api.tushare.pro`,仅在需通过公司内网代理、跨境网络或自建镜像时填写 `http://` 或 `https://` 开头的完整地址 | 可选 | | `TICKFLOW_API_KEY` | [TickFlow](https://tickflow.org) API Key;可选,用于 A 股日 K、实时行情、股票列表/名称与大盘复盘增强;失败或权限不足时自动回退。 | 可选 | @@ -375,6 +376,7 @@ daily_stock_analysis/ | `SOCIAL_SENTIMENT_API_URL` | Stock Sentiment API 地址(默认 `https://api.adanos.org`) | 可选 | | `SEARXNG_BASE_URLS` | SearXNG 自建实例(无配额兜底,需在 settings.yml 启用 format: json);留空时仅在显式启用公共实例发现后使用 `searx.space` | 可选 | | `SEARXNG_PUBLIC_INSTANCES_ENABLED` | 是否在 `SEARXNG_BASE_URLS` 为空时自动从 `searx.space` 获取公共实例(默认 `false`)。公共实例普遍限流或未开启 JSON 输出,开启后每次分析可能多耗 30~60 秒且新闻面为空 | 可选 | +| `SEARXNG_TIMEOUT_SECONDS` | 自建 SearXNG 单次搜索超时(秒,默认 `10`,最小 `1`);实例较慢(如聚合引擎较多的 NAS 部署)时可调大,公共实例超时不受影响。GitHub Actions 需显式映射该变量 | 可选 | | `NEWS_STRATEGY_PROFILE` | 新闻策略窗口档位:`ultra_short`(1天)/`short`(3天)/`medium`(7天)/`long`(30天);实际窗口取与 `NEWS_MAX_AGE_DAYS` 的最小值 | 默认 `short` | | `NEWS_MAX_AGE_DAYS` | 新闻最大时效(天),搜索时限制结果在近期内 | 默认 `3` | | `BIAS_THRESHOLD` | 乖离率阈值(%),超过提示不追高;强势趋势股自动放宽到 1.5 倍 | 默认 `5.0` | diff --git a/docs/full-guide_EN.md b/docs/full-guide_EN.md index f5e8587a31a..4520eefc4ba 100644 --- a/docs/full-guide_EN.md +++ b/docs/full-guide_EN.md @@ -158,6 +158,7 @@ Go to your forked repo → `Settings` → `Secrets and variables` → `Actions` | `MINIMAX_API_KEYS` | [MiniMax](https://platform.minimax.io/) Coding Plan Web Search (structured search results) | Optional | | `SEARXNG_BASE_URLS` | SearXNG self-hosted instances (quota-free fallback, enable format: json in settings.yml); when empty, `searx.space` discovery is used only if public instances are explicitly enabled | Optional | | `SEARXNG_PUBLIC_INSTANCES_ENABLED` | Auto-discover public SearXNG instances from `searx.space` when `SEARXNG_BASE_URLS` is empty (default `false`). Public instances are commonly rate-limited or do not return JSON, so enabling this can add 30-60s per run and still yield no news | Optional | +| `SEARXNG_TIMEOUT_SECONDS` | Per-search timeout in seconds for self-hosted SearXNG instances (default `10`, minimum `1`). Increase for slow instances (e.g. NAS deployments aggregating many engines); public-instance timeout is unaffected. GitHub Actions requires explicit variable mapping | Optional | | `TUSHARE_TOKEN` | [Tushare Pro](https://tushare.pro/weborder/#/login?reg=834638) Token | Optional | | `TUSHARE_HTTP_URL` | Tushare Pro HTTP endpoint; when unset/empty defaults to the official `http://api.tushare.pro`. Set to a `http://` or `https://` URL only when routing through a corporate proxy, cross-border network, or a self-hosted mirror | Optional | | `TICKFLOW_API_KEY` | [TickFlow](https://tickflow.org) API key for optional A-share daily K-lines, realtime quotes, stock list/name lookup, and CN market review enhancement; permission or entitlement failures fall back to existing providers | Optional | diff --git a/docs/stock-profile-api.md b/docs/stock-profile-api.md new file mode 100644 index 00000000000..5a5e29b9da2 --- /dev/null +++ b/docs/stock-profile-api.md @@ -0,0 +1,41 @@ +# 个股研究聚合 API + +本文档说明 Issue #2279 的后端契约阶段。目标是让后续 `/stocks/:code` 工作台通过单一端点消费数据,而不是在浏览器并发拼装行情、历史、报告、资讯、持仓和监控接口。 + +## 端点 + +`GET /api/v1/stocks/{stock_code}/profile?history_days=60` + +端点先把输入统一为 canonical code。实时行情、历史和报告链使用 canonical code;对可能由旧入口按别名持久化的 intelligence 与 monitor 记录,读取时会展开仓库既有等价代码集合并按 ID 去重: + +- A 股:`SH600519`、`600519.SH` 等收敛为 `600519`。入口已经显式携带 `SH` / `SZ` / `BJ` 时,后续报告、资讯和监控别名展开会持续保留该市场身份;即使股票索引存在同形日韩代码,也不会重新按裸数字推断为其他市场。显式交易所与代码规则冲突(如 `600519.SZ`)时返回 400,不会剥离交易所后查询另一标的。 +- 日股:`7203.T` 保留 Yahoo canonical suffix,并返回 `market=jp`。 +- 韩股:`005930.KS`、`035720.KQ` 保留 Yahoo canonical suffix,并返回 `market=kr`;股票索引唯一识别出的旧裸代码也沿用解析后的韩国市场身份。缓存持仓中的旧裸六位韩股在 market 已明确为 `kr` 时按解析身份与档案 suffix 的数字主体比较,不会再次按无 market 的 A 股规则解释。 +- 台股:profile 入口接受 4–6 位 `.TW` / `.TWO` Yahoo suffix(包括六位 ETF),并返回 `market=tw`。市场限定的资讯查询兼容旧裸数字 scope,但 `global` 查询继续排除该歧义别名;缓存持仓已明确 `market=tw` 时,旧裸代码按同市场数字主体与档案匹配。 +- 港股:`00700`、`00700.HK`、`HK00700` 收敛为 `HK00700`;缓存持仓已明确 `market=hk` 时,`700` 等旧短格式也会补零后参与身份比较。 +- 美股 ticker 统一为裸大写形式,例如 `aapl`、`AAPL.US` 都收敛为 `AAPL`;持久化读取仍查询裸 ticker 与 `.US` 等价别名。 + +响应包含 `quote`、`history`、`research`、`intelligence`、`portfolio`、`monitors` 六个独立块,以及顶层 `evidence_quality` 汇总。每个块的 `status` 只允许: + +| 状态 | 语义 | +| --- | --- | +| `fresh` | 本次请求成功取得可用数据;不代表所有外部来源具有同一时区或刷新频率 | +| `partial` | 核心信息仍可用,但存在明确限制,例如只有报告列表、缺少详情,或持仓关系只来自缓存 | +| `unavailable` | 本次没有可用数据;原因以稳定的 `limitations` code 返回,不暴露原始异常或密钥 | + +任一可选块失败不会让其他块消失。例如 quote 失败时,历史报告、结构化 ResearchArtifact、symbol intelligence 和监控规则仍可返回;最新报告详情失败时,`research.recent_reports` 仍保留,`structured_report` 为 `null` 并标记 `latest_report_detail_unavailable`。 + +## 数据来源与边界 + +- quote/history:复用 `StockService`,不新增数据获取器。 +- research:复用 `HistoryService` 和 #2291 的 `ResearchArtifact` builder。报告查询把档案入口已经解析出的 market hint 传到 `HistoryService` 的候选生成层:只保留能在无提示解析时仍确认属于当前市场的裸数字别名;例如 `600519` 可继续兼容 A 股旧记录,`005930` 可兼容已唯一登记为韩股的旧报告,而与韩股同形的显式 A 股 `SZ000660` 不会查询裸 `000660`。日韩台查询保留交易所后缀及其他已确认同市场的旧裸数字代码,但不展开可能命中其他市场历史记录的别名;市场限定后候选为空时直接返回空分页,不会退化成无过滤查询。artifact 同时复用历史详情的上下文、raw result 和独立基本面快照 fallback,保留财报、分红与市场结构专项证据及其 source count。 +- service 导入边界:`api.v1` 的 router 改为延迟导出,因此 `StockProfileService -> ResearchArtifact schema` 不会反向触发全部 API endpoints。CLI、独立脚本和单元测试可在没有预先导入 `api.app` 的情况下直接导入 profile service。 +- intelligence:复用 `IntelligenceService` 的 symbol scope 查询,并兼容 canonical、交易所前后缀、港股前后缀、混合大小写及日韩台市场限定的裸数字历史别名;无法无提示解析回当前市场的歧义裸码不会进入 `global` 查询。查询别名按 casefold identity 去重,由 repository 的 symbol-only 不区分大小写过滤兼容历史大小写,避免重复 count/select。任一别名/市场查询失败时块保持 partial limitation,即使其余查询成功但为空,也不误报为已确认无资讯。 +- portfolio:只读 `PortfolioRepository.list_cached_position_identities()`,并使用每条缓存持仓自己的 market 解析旧裸代码;只有 market 与档案身份一致时才算持有。不为了打开个股页触发实时估值或写 snapshot,所以状态固定为 `partial` 并包含 `cached_positions_only`。 +- monitors:复用 `AlertService.list_rules()`,以不区分大小写的 symbol 过滤分页汇总并去重 canonical code 及等价历史别名下的 `single_symbol` 规则。由于现有告警目标没有独立 market 字段,日韩台档案不会查询可能与 A/HK 同形的裸数字别名,避免跨市场规则误归属。 + +本阶段不新增 Web 路由/页面、不接线 Home/Watchlist/Screening/Portfolio/Report 入口,也不包含日历事件。后续 Web PR 必须消费本端点并分别渲染块状态;不得重新恢复多请求页面聚合。日历事件在 #2307 契约合入后再作为独立块扩展。 + +## 回滚 + +Revert 本 PR 即可移除 profile schema、service、endpoint、测试和文档。没有数据库迁移、配置变更或数据清理步骤。 diff --git a/src/config.py b/src/config.py index e54df9b0b70..e40f4ec76c7 100644 --- a/src/config.py +++ b/src/config.py @@ -983,6 +983,7 @@ class Config: serpapi_keys: List[str] = field(default_factory=list) # SerpAPI Keys searxng_base_urls: List[str] = field(default_factory=list) # SearXNG instance URLs (self-hosted, no quota) searxng_public_instances_enabled: bool = False # Opt in to public discovery when base URLs are absent + searxng_timeout_seconds: int = 10 # 自建 SearXNG 单次搜索超时(秒) # === Social Sentiment (US stocks only, api.adanos.org) === social_sentiment_api_key: Optional[str] = None @@ -1880,6 +1881,9 @@ def _load_from_env(cls) -> 'Config': serpapi_keys=serpapi_keys, searxng_base_urls=searxng_base_urls, searxng_public_instances_enabled=searxng_public_instances_enabled, + searxng_timeout_seconds=parse_env_int( + os.getenv('SEARXNG_TIMEOUT_SECONDS'), 10, field_name='SEARXNG_TIMEOUT_SECONDS', minimum=1 + ), social_sentiment_api_key=os.getenv('SOCIAL_SENTIMENT_API_KEY') or None, social_sentiment_api_url=os.getenv('SOCIAL_SENTIMENT_API_URL', 'https://api.adanos.org').rstrip('/'), news_max_age_days=parse_env_int(os.getenv('NEWS_MAX_AGE_DAYS'), 3, field_name='NEWS_MAX_AGE_DAYS', minimum=1), diff --git a/src/core/config_registry.py b/src/core/config_registry.py index 1a243a662e3..fdf803a4871 100644 --- a/src/core/config_registry.py +++ b/src/core/config_registry.py @@ -79,6 +79,7 @@ "USE_PROXY", "PROXY_HOST", "PROXY_PORT", + "SEARXNG_TIMEOUT_SECONDS", } _FIELD_DEFINITIONS: Dict[str, Dict[str, Any]] = { diff --git a/src/core/market_review_runtime.py b/src/core/market_review_runtime.py index 53378bc346d..3292161c902 100644 --- a/src/core/market_review_runtime.py +++ b/src/core/market_review_runtime.py @@ -105,6 +105,7 @@ def build_market_review_runtime( "searxng_public_instances_enabled", False, ), + searxng_timeout_seconds=getattr(config, "searxng_timeout_seconds", None), news_max_age_days=getattr(config, "news_max_age_days", 3), news_strategy_profile=getattr(config, "news_strategy_profile", "short"), ) diff --git a/src/core/pipeline.py b/src/core/pipeline.py index 2978b108562..8764f4ec987 100644 --- a/src/core/pipeline.py +++ b/src/core/pipeline.py @@ -309,6 +309,7 @@ def __init__( minimax_keys=self.config.minimax_api_keys, searxng_base_urls=self.config.searxng_base_urls, searxng_public_instances_enabled=self.config.searxng_public_instances_enabled, + searxng_timeout_seconds=getattr(self.config, "searxng_timeout_seconds", None), news_max_age_days=self.config.news_max_age_days, news_strategy_profile=getattr(self.config, "news_strategy_profile", "short"), ) diff --git a/src/repositories/alert_repo.py b/src/repositories/alert_repo.py index b1104df5603..757354cf764 100644 --- a/src/repositories/alert_repo.py +++ b/src/repositories/alert_repo.py @@ -79,7 +79,10 @@ def list_rules( if target_scope: conditions.append(AlertRuleRecord.target_scope == target_scope) if target: - conditions.append(AlertRuleRecord.target == target) + if target_scope == "single_symbol": + conditions.append(func.lower(AlertRuleRecord.target) == target.strip().lower()) + else: + conditions.append(AlertRuleRecord.target == target) if source: conditions.append(AlertRuleRecord.source == source) diff --git a/src/repositories/intelligence_repo.py b/src/repositories/intelligence_repo.py index cf1e9df6c8c..f461540572a 100644 --- a/src/repositories/intelligence_repo.py +++ b/src/repositories/intelligence_repo.py @@ -165,7 +165,11 @@ def list_items( if scope_type: conditions.append(IntelligenceItem.scope_type == scope_type) if scope_value: - conditions.append(IntelligenceItem.scope_value == self._normalize_scope_value(scope_value)) + normalized_scope = self._normalize_scope_value(scope_value) + if scope_type == "symbol": + conditions.append(func.lower(IntelligenceItem.scope_value) == normalized_scope.lower()) + else: + conditions.append(IntelligenceItem.scope_value == normalized_scope) if market: conditions.append(IntelligenceItem.market == market) if query: diff --git a/src/search_service.py b/src/search_service.py index de1cb2beac9..9a5b8052d68 100644 --- a/src/search_service.py +++ b/src/search_service.py @@ -1843,10 +1843,20 @@ class SearXNGSearchProvider(BaseSearchProvider): _public_instances_stale_retry_after: float = 0.0 _public_instances_lock = threading.Lock() - def __init__(self, base_urls: Optional[List[str]] = None, *, use_public_instances: bool = False): + def __init__( + self, + base_urls: Optional[List[str]] = None, + *, + use_public_instances: bool = False, + self_hosted_timeout_seconds: Optional[int] = None, + ): normalized_base_urls = [url.rstrip("/") for url in (base_urls or []) if url.strip()] super().__init__(normalized_base_urls, "SearXNG") self._base_urls = normalized_base_urls + if self_hosted_timeout_seconds and int(self_hosted_timeout_seconds) > 0: + self._self_hosted_timeout_seconds = int(self_hosted_timeout_seconds) + else: + self._self_hosted_timeout_seconds = self.SELF_HOSTED_TIMEOUT_SECONDS self._use_public_instances = bool(use_public_instances and not self._base_urls) self._cursor = 0 self._cursor_lock = threading.Lock() @@ -2157,7 +2167,7 @@ def search(self, query: str, max_results: int = 5, days: int = 7) -> SearchRespo max_attempts=len(self._base_urls), ) retry_enabled = True - timeout = self.SELF_HOSTED_TIMEOUT_SECONDS + timeout = self._self_hosted_timeout_seconds empty_error = "SearXNG 未配置可用实例" elif self._use_public_instances: public_instances = self._get_public_instances() @@ -2390,6 +2400,7 @@ def __init__( minimax_keys: Optional[List[str]] = None, searxng_base_urls: Optional[List[str]] = None, searxng_public_instances_enabled: bool = False, + searxng_timeout_seconds: Optional[int] = None, news_max_age_days: int = 3, news_strategy_profile: str = "short", ): @@ -2417,6 +2428,7 @@ def __init__( "minimax_keys": list(minimax_keys or []), "searxng_base_urls": list(searxng_base_urls or []), "searxng_public_instances_enabled": bool(searxng_public_instances_enabled), + "searxng_timeout_seconds": searxng_timeout_seconds, "news_max_age_days": int(news_max_age_days), "news_strategy_profile": news_strategy_profile, } @@ -2468,6 +2480,7 @@ def __init__( searxng_provider = SearXNGSearchProvider( searxng_base_urls, use_public_instances=bool(searxng_public_instances_enabled and not searxng_base_urls), + self_hosted_timeout_seconds=searxng_timeout_seconds, ) if searxng_provider.is_available: self._providers.append(searxng_provider) @@ -4890,6 +4903,7 @@ def get_search_service() -> SearchService: minimax_keys=config.minimax_api_keys, searxng_base_urls=config.searxng_base_urls, searxng_public_instances_enabled=config.searxng_public_instances_enabled, + searxng_timeout_seconds=getattr(config, "searxng_timeout_seconds", None), news_max_age_days=config.news_max_age_days, news_strategy_profile=getattr(config, "news_strategy_profile", "short"), ) diff --git a/src/services/history_service.py b/src/services/history_service.py index 2c63a4a7a82..dc0dc0f2e5e 100644 --- a/src/services/history_service.py +++ b/src/services/history_service.py @@ -19,6 +19,7 @@ from src.config import get_config, resolve_news_window_days from src.formatters import markdown_to_plain_text from src.data.stock_index_loader import resolve_index_stock_code +from src.services.stock_code_utils import resolve_daily_stock_identity from src.report_language import ( get_bias_status_emoji, get_localized_stock_name, @@ -104,7 +105,11 @@ def _serialize_created_at(value: Optional[datetime]) -> Optional[str]: return value.astimezone().isoformat() @staticmethod - def _history_code_filter_candidates(stock_code: str) -> List[str]: + def _history_code_filter_candidates( + stock_code: str, + *, + market_hint: Optional[str] = None, + ) -> List[str]: raw_code = str(stock_code or "").strip() if not raw_code: return [] @@ -116,6 +121,20 @@ def add(candidate: str) -> None: if candidate and candidate not in candidates: candidates.append(candidate) + trusted_market = str(market_hint or "").strip().lower() + if trusted_market: + identity = resolve_daily_stock_identity(raw_code, market_hint=trusted_market) + if identity is None or identity.market != trusted_market: + return [] + for candidate in identity.code_candidates: + candidate_text = str(candidate or "").strip() + if candidate_text.isdigit(): + unhinted_identity = resolve_daily_stock_identity(candidate_text) + if unhinted_identity is None or unhinted_identity.market != trusted_market: + continue + add(candidate) + return candidates + try: from data_provider.base import ( canonical_stock_code, @@ -219,7 +238,9 @@ def get_history_list( start_date: Optional[str] = None, end_date: Optional[str] = None, page: int = 1, - limit: int = 20 + limit: int = 20, + include_ambiguous_numeric_aliases: bool = True, + market_hint: Optional[str] = None, ) -> Dict[str, Any]: """ Get history analysis list. @@ -231,13 +252,24 @@ def get_history_list( end_date: End date (YYYY-MM-DD) page: Page number limit: Items per page + include_ambiguous_numeric_aliases: Whether to include bare numeric + aliases that may collide across offshore markets. + market_hint: Trusted market identity for candidate expansion. When + present, candidates from other indexed markets are excluded. Returns: Dictionary containing total count and items """ try: if stock_code: - stock_code = self._history_code_filter_candidates(stock_code) + stock_code = self._history_code_filter_candidates( + stock_code, + market_hint=market_hint, + ) + if not include_ambiguous_numeric_aliases and not market_hint: + stock_code = [candidate for candidate in stock_code if not candidate.isdigit()] + if not stock_code: + return {"total": 0, "items": []} # Parse date parameters start_dt = None @@ -573,6 +605,18 @@ def get_history_detail_by_id(self, record_id: int) -> Optional[Dict[str, Any]]: logger.error(f"根据 ID 查询历史详情失败: {e}", exc_info=True) return None + def get_latest_fundamental_snapshot( + self, + *, + query_id: str, + stock_code: str, + ) -> Optional[Dict[str, Any]]: + """Read the same persisted fundamental fallback used by history detail APIs.""" + return self.db.get_latest_fundamental_snapshot( + query_id=query_id, + code=stock_code, + ) + @staticmethod def _normalize_display_sniper_value(value: Any) -> Optional[str]: """Normalize sniper point values for history display.""" diff --git a/src/services/name_to_code_resolver.py b/src/services/name_to_code_resolver.py index 9668d449ee8..3b70e49cee3 100644 --- a/src/services/name_to_code_resolver.py +++ b/src/services/name_to_code_resolver.py @@ -18,6 +18,7 @@ import re import threading import time +import unicodedata from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Optional, Set, Tuple @@ -83,6 +84,22 @@ def _contains_cjk(text: str) -> bool: return any("\u3400" <= ch <= "\u9fff" for ch in text) +def _normalize_stock_name(name: str) -> str: + """股票名称的统一归一:NFKC 宽度归一(全角字母/数字 → 半角)+ 去除全部 + 空白。 + + 分词管道对用户输入做同样的 NFKC(web_intent_tokenizer._preprocess_text + 的工作副本),库内名称若保留源数据拼写(AkShare 的 "京东方A" 全角A、 + "五 粮 液" 内嵌空格),窗口/片段与归一后的输入永远不相等——不仅全名 + 精确匹配落空,还会被更短的库内名误切出错误实体("京东方A" 落空后 + 2 字窗口命中 "京东")。输入侧与库侧必须同源同变换:本地映射初值、 + AkShare 构建与合并、磁盘缓存加载三个入库口,与全部查询口共用本函数 + (磁盘缓存里的历史未归一数据同样在此归一)。展示名随之统一为归一拼写 + (与 token 层"单一代码身份"原则一致)。 + """ + return "".join(unicodedata.normalize("NFKC", name).split()) + + def _is_code_like(s: str) -> bool: """共享的“形似代码”检查的向后兼容包装。""" return is_code_like(s) @@ -121,7 +138,7 @@ def _build_local_name_indexes(code_to_name: Dict[str, str]) -> Tuple[Dict[str, s for code, name in code_to_name.items(): if not name or not code: continue - normalized_name = name.strip() + normalized_name = _normalize_stock_name(name) if not normalized_name: continue name_to_codes.setdefault(normalized_name, set()).add(code) @@ -184,7 +201,7 @@ def _build_name_map_from_df(df) -> Dict[str, str]: base, suffix = code_str.rsplit(".", 1) if suffix.upper() in ("SH", "SZ", "SS") and base.isdigit(): code_str = base - code_to_name[code_str] = str(name).strip() + code_to_name[code_str] = _normalize_stock_name(str(name)) return _build_reverse_map_no_duplicates(code_to_name) @@ -199,7 +216,12 @@ def _try_load_disk_cache_locked() -> None: ts = payload.get("ts") raw_map = payload.get("map") if isinstance(ts, (int, float)) and isinstance(raw_map, dict): - name_map = {str(k): str(v) for k, v in raw_map.items() if k and v} + # 历史落盘可能含未归一名称(全角拼写/内嵌空格):加载即归一 + name_map = { + _normalize_stock_name(str(k)): str(v) + for k, v in raw_map.items() + if k and v + } if name_map: _akshare_cache = (float(ts), name_map) logger.info( @@ -371,7 +393,11 @@ class Stock: # ========================================================================= -stockDB: Dict[str, str] = dict(STOCK_NAME_MAP) +stockDB: Dict[str, str] = { + # 初值即归一(与输入侧 NFKC 同变换):源数据的全角拼写/内嵌空白 + # 不带入库内视图 + code: _normalize_stock_name(name) for code, name in STOCK_NAME_MAP.items() +} # 已存在代码被 AkShare 更新为当前官方名称时,旧名称作为别名保留, # 避免证券改名后旧名称彻底不可解析。 @@ -401,15 +427,21 @@ def extend_AkShare() -> bool: if _akshare_merged is akshare_map: return False changed = False - # akshare_map 是 name->code 反向映射,stockDB 是 code->name + # akshare_map 是 name->code 反向映射,stockDB 是 code->name;名称 + # 统一归一(NFKC 宽度 + 去内嵌空白)后比较/写入,避免与归一后的 + # 输入/本地拼写形成假性改名(制造无谓别名)——磁盘缓存里的历史 + # 未归一数据同样在此归一 for name, code in akshare_map.items(): + compact = _normalize_stock_name(name) + if not compact: + continue if code not in stockDB: - stockDB[code] = name + stockDB[code] = compact changed = True - elif stockDB[code] != name: + elif stockDB[code] != compact: # 证券改名:保留旧名称作为别名,再更新为 AkShare 当前官方名称。 stockAliases.setdefault(code, set()).add(stockDB[code]) - stockDB[code] = name + stockDB[code] = compact changed = True _akshare_merged = akshare_map if changed: @@ -607,7 +639,9 @@ def resolver_name_to_code_list(name: str) -> List[Stock]: """ if not name or not isinstance(name, str): return [] - s = name.strip() + # 查询输入与入库同源归一:源形态(全角拼写/内嵌空格,如自 AkShare 数据 + # 复制的 "京东方A"/"五 粮 液")与常规拼写同样可解析 + s = _normalize_stock_name(name) # 单字符不可能是股票名(最短 2 字),短路避免全名表扫描 if len(s) < 2: return [] @@ -694,7 +728,7 @@ def is_known_stock_name(name: str) -> bool: """ if not isinstance(name, str): return False - s = name.strip() + s = _normalize_stock_name(name) if not s: return False return s in _database_names(stockDB) @@ -720,7 +754,7 @@ def resolve_name_to_code(name: str) -> Optional[str]: """ if not name or not isinstance(name, str): return None - s = name.strip() + s = _normalize_stock_name(name) if not s: return None diff --git a/src/services/stock_code_utils.py b/src/services/stock_code_utils.py index f2b6004cb4a..7603eeae0f0 100644 --- a/src/services/stock_code_utils.py +++ b/src/services/stock_code_utils.py @@ -352,7 +352,9 @@ def resolve_daily_stock_identity( identity_code = raw_code trusted_market = str(market_hint or "").strip().lower() - if raw_code.isdigit() and len(raw_code) in {4, 5, 6}: + if trusted_market == "hk" and raw_code.isdigit() and 1 <= len(raw_code) <= 3: + identity_code = raw_code.zfill(5) + elif raw_code.isdigit() and len(raw_code) in {4, 5, 6}: from src.data.stock_index_loader import resolve_index_stock_code_candidates indexed_candidates = resolve_index_stock_code_candidates(raw_code) @@ -363,9 +365,9 @@ def resolve_daily_stock_identity( indexed_offshore = [ (candidate, market) for candidate, market in indexed_identities - if market in {"jp", "kr"} + if market in {"jp", "kr", "tw"} ] - if trusted_market in {"jp", "kr"}: + if trusted_market in {"jp", "kr", "tw"}: matching_candidates = [ candidate for candidate, market in indexed_offshore @@ -373,6 +375,13 @@ def resolve_daily_stock_identity( ] if len(matching_candidates) == 1: identity_code = matching_candidates[0] + elif trusted_market == "tw" and len(raw_code) in {4, 5, 6}: + return DailyStockIdentity( + normalized_code=raw_code, + market="tw", + refill_code="", + code_candidates=(raw_code,), + ) elif indexed_candidates: return None elif trusted_market == "jp" and len(raw_code) in {4, 5}: diff --git a/src/services/stock_profile_service.py b/src/services/stock_profile_service.py new file mode 100644 index 00000000000..b0fa912ce69 --- /dev/null +++ b/src/services/stock_profile_service.py @@ -0,0 +1,474 @@ +# -*- coding: utf-8 -*- +"""Aggregate existing stock research capabilities behind one partial-data contract.""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional + +from data_provider.base import canonical_stock_code +from src.analysis_context_pack_overview import extract_analysis_context_pack_overview +from src.repositories.portfolio_repo import PortfolioRepository +from src.services.alert_service import AlertService +from src.services.history_service import HistoryService +from src.services.intelligence_service import IntelligenceService +from src.services.market_symbol_utils import get_suffix_market +from src.services.research_artifact_service import build_research_artifact +from src.services.stock_code_utils import resolve_daily_stock_identity +from src.services.stock_service import StockService +from src.utils.data_processing import ( + extract_fundamental_detail_fields, + extract_market_structure_detail_field, +) + +_BLOCK_NAMES = ("quote", "history", "research", "intelligence", "portfolio", "monitors") + + +class InvalidStockProfileCode(ValueError): + """Raised when a stock profile request has no unambiguous shared identity.""" + + +class StockProfileService: + """Build a stock profile while isolating optional-source failures by block.""" + + def __init__( + self, + *, + stock_service: Optional[StockService] = None, + history_service: Optional[HistoryService] = None, + intelligence_service: Optional[IntelligenceService] = None, + portfolio_repository: Optional[PortfolioRepository] = None, + alert_service: Optional[AlertService] = None, + ): + self.stock_service = stock_service + self.history_service = history_service + self.intelligence_service = intelligence_service + self.portfolio_repository = portfolio_repository + self.alert_service = alert_service + + def get_profile(self, requested_code: str, *, history_days: int = 60) -> Dict[str, Any]: + canonical_code = self.canonicalize_code(requested_code) + market = self.market_for_code(canonical_code) + blocks = { + "quote": self._quote_block(canonical_code), + "history": self._history_block(canonical_code, history_days=history_days), + "research": self._research_block(canonical_code, market=market), + "intelligence": self._intelligence_block(canonical_code, market=market), + "portfolio": self._portfolio_block(canonical_code, market=market), + "monitors": self._monitor_block(canonical_code, market=market), + } + return { + "requested_code": str(requested_code).strip(), + "canonical_code": canonical_code, + "market": market, + "as_of": datetime.now().astimezone().isoformat(), + **blocks, + "evidence_quality": self._evidence_quality(blocks), + } + + @staticmethod + def canonicalize_code(value: str) -> str: + raw = str(value or "").strip() + identity = resolve_daily_stock_identity(raw) + if identity is None: + raise InvalidStockProfileCode("stock code has no unambiguous market identity") + normalized = canonical_stock_code(identity.refill_code or identity.normalized_code) + if normalized.isdigit() and len(normalized) == 5: + return f"HK{normalized.zfill(5)}" + return normalized.upper() + + @staticmethod + def market_for_code(canonical_code: str) -> str: + if canonical_code.startswith("HK"): + return "hk" + suffix_market = get_suffix_market(canonical_code) + if suffix_market: + return suffix_market + if canonical_code.isdigit() and len(canonical_code) == 6: + return "cn" + return "us" + + def _quote_block(self, code: str) -> Dict[str, Any]: + try: + quote = self._stock_service().get_realtime_quote(code) + except Exception: + quote = None + if not quote: + return self._unavailable("quote_unavailable", data=None) + return {"status": "fresh", "data": quote, "limitations": []} + + def _history_block(self, code: str, *, history_days: int) -> Dict[str, Any]: + try: + result = self._stock_service().get_history_data(code, period="daily", days=history_days) + rows = list(result.get("data") or []) + except Exception: + rows = [] + if not rows: + return { + "status": "unavailable", + "period": "daily", + "data": [], + "limitations": ["history_unavailable"], + } + return {"status": "fresh", "period": "daily", "data": rows, "limitations": []} + + def _research_block(self, code: str, *, market: str) -> Dict[str, Any]: + empty_data = {"latest_report": None, "recent_reports": [], "structured_report": None} + try: + query_options: Dict[str, Any] = { + "stock_code": code, + "page": 1, + "limit": 5, + "market_hint": market, + } + if market in {"jp", "kr", "tw"}: + query_options["include_ambiguous_numeric_aliases"] = False + result = self._history_service().get_history_list(**query_options) + reports = list(result.get("items") or []) + except Exception: + return self._unavailable("report_list_unavailable", data=empty_data) + if not reports: + return self._unavailable("no_reports", data=empty_data) + + latest = reports[0] + record_id = latest.get("id") + if record_id is None: + return { + "status": "partial", + "data": { + "latest_report": latest, + "recent_reports": reports, + "structured_report": None, + }, + "limitations": ["latest_report_id_unavailable"], + } + try: + detail = self._history_service().get_history_detail_by_id(int(record_id)) + except Exception: + detail = None + if not detail: + return { + "status": "partial", + "data": { + "latest_report": latest, + "recent_reports": reports, + "structured_report": None, + }, + "limitations": ["latest_report_detail_unavailable"], + } + try: + artifact = build_research_artifact(self._artifact_input(detail)) + except Exception: + artifact = None + return { + "status": "fresh" if artifact else "partial", + "data": { + "latest_report": latest, + "recent_reports": reports, + "structured_report": artifact, + }, + "limitations": [] if artifact else ["structured_report_unavailable"], + } + + def _intelligence_block(self, code: str, *, market: str) -> Dict[str, Any]: + items_by_id: Dict[Any, Dict[str, Any]] = {} + successful_queries = 0 + failed_queries = 0 + markets = [market] if market == "global" else [market, "global"] + aliases = self._code_aliases(code, market_hint=market) + safe_global_aliases = set( + self._code_aliases( + code, + market_hint=market, + include_ambiguous_numeric=False, + ) + ) + for alias in aliases: + for query_market in markets: + if query_market == "global" and alias not in safe_global_aliases: + continue + try: + result = self._intelligence_service().list_items( + scope_type="symbol", + scope_value=alias, + market=query_market, + page=1, + page_size=10, + ) + successful_queries += 1 + except Exception: + failed_queries += 1 + continue + for item in result.get("items") or []: + key = item.get("id") + if key is None: + key = (item.get("source_type"), item.get("url"), item.get("title")) + items_by_id.setdefault(key, item) + if successful_queries == 0: + return self._unavailable("intelligence_query_failed", items=[]) + items = sorted( + items_by_id.values(), + key=lambda item: ( + str(item.get("published_at") or item.get("fetched_at") or item.get("created_at") or ""), + int(item.get("id") or 0), + ), + reverse=True, + )[:10] + if not items: + if failed_queries: + return { + "status": "partial", + "items": [], + "limitations": ["intelligence_alias_query_partial"], + } + return self._unavailable("no_symbol_intelligence", items=[]) + return { + "status": "partial" if failed_queries else "fresh", + "items": items, + "limitations": ["intelligence_alias_query_partial"] if failed_queries else [], + } + + def _portfolio_block(self, code: str, *, market: str) -> Dict[str, Any]: + try: + profile_identity = resolve_daily_stock_identity(code, market_hint=market) + identities = self._portfolio_repository().list_cached_position_identities() + matches = [] + for position_market, symbol in identities: + normalized_market = str(position_market or "").strip().lower() + identity = resolve_daily_stock_identity(symbol, market_hint=normalized_market) + if identity is None or identity.market != normalized_market or identity.market != market: + continue + if self._same_profile_identity(identity, profile_identity): + matches.append(normalized_market) + except Exception: + return self._unavailable( + "portfolio_relation_unavailable", + data={"held": False, "matched_markets": []}, + ) + return { + "status": "partial", + "data": {"held": bool(matches), "matched_markets": list(dict.fromkeys(matches))}, + "limitations": ["cached_positions_only"], + } + + @staticmethod + def _same_profile_identity(position_identity: Any, profile_identity: Any) -> bool: + if profile_identity is None: + return False + position_codes = { + str(position_identity.normalized_code or "").strip().upper(), + str(position_identity.refill_code or "").strip().upper(), + } - {""} + profile_codes = { + str(profile_identity.normalized_code or "").strip().upper(), + str(profile_identity.refill_code or "").strip().upper(), + } - {""} + if position_codes & profile_codes: + return True + if position_identity.market in {"kr", "tw"} and not position_identity.refill_code: + profile_base = str(profile_identity.normalized_code or "").split(".", 1)[0] + return position_identity.normalized_code == profile_base + return False + + def _monitor_block(self, code: str, *, market: str) -> Dict[str, Any]: + rules_by_id: Dict[Any, Dict[str, Any]] = {} + successful_queries = 0 + failed_queries = 0 + for alias in self._code_aliases( + code, + market_hint=market, + include_ambiguous_numeric=False, + ): + page = 1 + scanned = 0 + try: + while True: + result = self._alert_service().list_rules( + target_scope="single_symbol", + target=alias, + page=page, + page_size=100, + ) + successful_queries += 1 + rules = list(result.get("items") or []) + for rule in rules: + key = rule.get("id") + if key is None: + key = (alias, rule.get("name"), rule.get("alert_type")) + rules_by_id.setdefault(key, rule) + scanned += len(rules) + total = int(result.get("total") or 0) + if scanned >= total or not rules: + break + page += 1 + except Exception: + failed_queries += 1 + if successful_queries == 0: + return self._unavailable( + "monitor_query_failed", + data={"total_rule_count": 0, "enabled_rule_count": 0, "rule_ids": []}, + ) + rules = list(rules_by_id.values()) + return { + "status": "partial" if failed_queries else "fresh", + "data": { + "total_rule_count": len(rules), + "enabled_rule_count": sum(1 for rule in rules if rule.get("enabled")), + "rule_ids": [int(rule["id"]) for rule in rules if rule.get("id") is not None], + }, + "limitations": ["monitor_alias_query_partial"] if failed_queries else [], + } + + @staticmethod + def _code_aliases( + code: str, + *, + market_hint: Optional[str] = None, + include_ambiguous_numeric: bool = True, + ) -> List[str]: + market = str(market_hint or StockProfileService.market_for_code(code)).strip().lower() + identity = resolve_daily_stock_identity(code, market_hint=market) + candidates = list(identity.code_candidates) if identity is not None and identity.market == market else [code] + if include_ambiguous_numeric and market in {"jp", "kr", "tw"} and "." in code: + numeric_base = code.split(".", 1)[0] + if numeric_base.isdigit(): + candidates.append(numeric_base) + aliases: List[str] = [] + seen_aliases = set() + for candidate in candidates or [code]: + candidate_text = str(candidate).strip() + if not include_ambiguous_numeric and candidate_text.isdigit(): + unhinted_identity = resolve_daily_stock_identity(candidate_text) + same_market = unhinted_identity is not None and unhinted_identity.market == market + legacy_short_hk = ( + market == "hk" + and len(candidate_text) <= 3 + and ( + hinted_identity := resolve_daily_stock_identity( + candidate_text, + market_hint="hk", + ) + ) is not None + and hinted_identity.market == "hk" + ) + if not same_market and not legacy_short_hk: + continue + alias_key = candidate_text.casefold() + if candidate_text and alias_key not in seen_aliases: + seen_aliases.add(alias_key) + aliases.append(candidate_text) + return aliases + + def _artifact_input(self, detail: Dict[str, Any]) -> Dict[str, Any]: + context_snapshot = detail.get("context_snapshot") + raw_result = detail.get("raw_result") + raw_fundamental = ( + raw_result.get("fundamental_context") or raw_result + if isinstance(raw_result, dict) + else None + ) + extracted_fundamental = extract_fundamental_detail_fields( + context_snapshot, + raw_fundamental, + ) + try: + persisted_fundamental = self._history_service().get_latest_fundamental_snapshot( + query_id=str(detail.get("query_id") or "").strip(), + stock_code=str( + detail.get("storage_stock_code") or detail.get("stock_code") or "" + ).strip(), + ) + except Exception: + persisted_fundamental = None + persisted_fields = extract_fundamental_detail_fields( + None, + persisted_fundamental, + ) + context_overview = extract_analysis_context_pack_overview(context_snapshot) + market_structure = extract_market_structure_detail_field( + context_snapshot, + raw_result, + ) + return { + "meta": { + "id": detail.get("id"), + "query_id": detail.get("query_id"), + "stock_code": detail.get("stock_code"), + "stock_name": detail.get("stock_name"), + "created_at": detail.get("created_at"), + }, + "summary": { + "analysis_summary": detail.get("analysis_summary"), + "operation_advice": detail.get("operation_advice"), + "action": detail.get("action"), + "action_label": detail.get("action_label"), + "trend_prediction": detail.get("trend_prediction"), + "sentiment_score": detail.get("sentiment_score"), + }, + "strategy": { + "ideal_buy": detail.get("ideal_buy"), + "secondary_buy": detail.get("secondary_buy"), + "stop_loss": detail.get("stop_loss"), + "take_profit": detail.get("take_profit"), + }, + "details": { + "news_content": detail.get("news_content"), + "empty_news_disclosure": detail.get("empty_news_disclosure"), + "analysis_context_pack_overview": context_overview, + "financial_report": detail.get("financial_report") + or extracted_fundamental.get("financial_report") + or persisted_fields.get("financial_report"), + "dividend_metrics": detail.get("dividend_metrics") + or extracted_fundamental.get("dividend_metrics") + or persisted_fields.get("dividend_metrics"), + "market_structure": detail.get("market_structure") or market_structure, + }, + } + + def _stock_service(self) -> StockService: + if self.stock_service is None: + self.stock_service = StockService() + return self.stock_service + + def _history_service(self) -> HistoryService: + if self.history_service is None: + self.history_service = HistoryService() + return self.history_service + + def _intelligence_service(self) -> IntelligenceService: + if self.intelligence_service is None: + self.intelligence_service = IntelligenceService() + return self.intelligence_service + + def _portfolio_repository(self) -> PortfolioRepository: + if self.portfolio_repository is None: + self.portfolio_repository = PortfolioRepository() + return self.portfolio_repository + + def _alert_service(self) -> AlertService: + if self.alert_service is None: + self.alert_service = AlertService() + return self.alert_service + + @staticmethod + def _unavailable(limitation: str, **payload: Any) -> Dict[str, Any]: + return {"status": "unavailable", **payload, "limitations": [limitation]} + + @staticmethod + def _evidence_quality(blocks: Dict[str, Dict[str, Any]]) -> Dict[str, Any]: + statuses = {name: str(blocks[name]["status"]) for name in _BLOCK_NAMES} + status_values = set(statuses.values()) + if status_values == {"fresh"}: + overall = "fresh" + elif status_values == {"unavailable"}: + overall = "unavailable" + else: + overall = "partial" + limitations = [] + for name in _BLOCK_NAMES: + limitations.extend(str(item) for item in blocks[name].get("limitations") or []) + return { + "status": overall, + "blocks": statuses, + "limitations": list(dict.fromkeys(limitations)), + } diff --git a/tests/test_alert_api.py b/tests/test_alert_api.py index ef5f7ff8f8d..deff27f04ef 100644 --- a/tests/test_alert_api.py +++ b/tests/test_alert_api.py @@ -248,6 +248,19 @@ def test_supported_rule_types_and_filters(self) -> None: self.assertEqual(payload["items"][0]["target"], "300750") self.assertEqual(payload["items"][0]["parameters"]["change_pct"], 3.5) + def test_single_symbol_filter_is_case_insensitive_for_legacy_targets(self) -> None: + created = self._create_rule({"target": "Brk.B"}) + + resp = self.client.get( + "/api/v1/alerts/rules", + params={"target_scope": "single_symbol", "target": "BRK.B"}, + ) + + self.assertEqual(resp.status_code, 200, resp.text) + self.assertEqual(resp.json()["total"], 1) + self.assertEqual(resp.json()["items"][0]["id"], created["id"]) + self.assertEqual(resp.json()["items"][0]["target"], "Brk.B") + def test_create_p5_technical_indicator_rules(self) -> None: cases = [ ("ma_price_cross", {"direction": "above", "window": 20}), diff --git a/tests/test_analysis_history.py b/tests/test_analysis_history.py index 1a7db78e343..b1c3f4a32eb 100644 --- a/tests/test_analysis_history.py +++ b/tests/test_analysis_history.py @@ -80,6 +80,66 @@ def test_unregistered_csi_form_is_not_converged(self): candidates = HistoryService._history_code_filter_candidates("csi930956") self.assertNotIn("csi930956", candidates) + def test_market_aware_offshore_lookup_keeps_same_market_bare_numeric_alias(self): + db = MagicMock() + db.get_analysis_history_paginated.return_value = ([], 0) + + HistoryService(db).get_history_list( + stock_code="005930.KS", + page=1, + limit=5, + include_ambiguous_numeric_aliases=False, + market_hint="kr", + ) + + queried_codes = db.get_analysis_history_paginated.call_args.kwargs["code"] + self.assertIn("005930.KS", queried_codes) + self.assertIn("005930", queried_codes) + + def test_market_hint_blocks_indexed_cross_market_reexpansion(self): + db = MagicMock() + db.get_analysis_history_paginated.return_value = ([], 0) + + HistoryService(db).get_history_list( + stock_code="000660", + page=1, + limit=5, + market_hint="cn", + ) + + queried_codes = db.get_analysis_history_paginated.call_args.kwargs["code"] + self.assertIn("SZ000660", queried_codes) + self.assertIn("000660.SZ", queried_codes) + self.assertNotIn("000660", queried_codes) + self.assertNotIn("000660.KS", queried_codes) + + def test_market_hint_keeps_unambiguous_same_market_bare_numeric_alias(self): + db = MagicMock() + db.get_analysis_history_paginated.return_value = ([], 0) + + HistoryService(db).get_history_list( + stock_code="600519", + page=1, + limit=5, + market_hint="cn", + ) + + queried_codes = db.get_analysis_history_paginated.call_args.kwargs["code"] + self.assertIn("600519", queried_codes) + + def test_empty_market_qualified_candidate_set_fails_closed(self): + db = MagicMock() + + result = HistoryService(db).get_history_list( + stock_code="AAPL", + page=1, + limit=5, + market_hint="cn", + ) + + self.assertEqual(result, {"total": 0, "items": []}) + db.get_analysis_history_paginated.assert_not_called() + def _analysis_context_pack_overview() -> dict: return { diff --git a/tests/test_intelligence_service.py b/tests/test_intelligence_service.py index 6a832c0e052..86bc8624841 100644 --- a/tests/test_intelligence_service.py +++ b/tests/test_intelligence_service.py @@ -157,6 +157,34 @@ def test_create_fetch_and_deduplicate_rss_source(self) -> None: self.assertEqual(items["items"][0]["scope_type"], "market") self.assertTrue(items["items"][0]["url"].startswith("https://news.example.com/")) + def test_symbol_scope_filter_is_case_insensitive_for_legacy_items(self) -> None: + now = datetime.now() + saved = self.service.repo.upsert_items([ + { + "source_name": "legacy-symbol-feed", + "source_type": "rss", + "title": "Mixed-case symbol item", + "summary": "Legacy symbol identity", + "url": "https://news.example.com/mixed-symbol", + "source": "legacy-symbol-feed", + "published_at": now, + "fetched_at": now, + "scope_type": "symbol", + "scope_value": "AaPl", + "market": "us", + } + ]) + + items = self.service.list_items( + scope_type="symbol", + scope_value="AAPL", + market="us", + ) + + self.assertEqual(saved, 1) + self.assertEqual(items["total"], 1) + self.assertEqual(items["items"][0]["scope_value"], "AaPl") + def test_fetch_http_error_does_not_expose_source_query_secret(self) -> None: secret_url = "https://feeds.example.com/rss.xml?token=super-secret" source = self.service.create_source({ diff --git a/tests/test_name_to_code_resolver.py b/tests/test_name_to_code_resolver.py index 8c8d60cdeea..38ea07eb242 100644 --- a/tests/test_name_to_code_resolver.py +++ b/tests/test_name_to_code_resolver.py @@ -39,8 +39,11 @@ def clean_db(request): fake_map = getattr(request, "param", None) with patch.object(ntc, "_get_akshare_name_to_code", return_value=fake_map): yield + # 恢复用归一后的本地映射(与模块初值同构,见 _normalize_stock_name) ntc.stockDB.clear() - ntc.stockDB.update(STOCK_NAME_MAP) + ntc.stockDB.update( + {c: ntc._normalize_stock_name(n) for c, n in STOCK_NAME_MAP.items()} + ) ntc._names_cache[:] = [None, None, None] ntc._pinyin_cache[:] = [None, None] ntc._akshare_merged = None @@ -311,6 +314,28 @@ def test_local_single_candidate_gets_a_share_candidate_after_akshare_merge(self, Stock("09988", "阿里巴巴", "hk"), ] +class TestCompactLookupInputs: + """查询侧同源压平:带内嵌空格的"源形态"输入(如自 AkShare 数据复制的 + "五 粮 液")与常规无空格拼写同样可解析——入库压平后查询入口若只做 + 首尾 strip,源形态输入会在精确/子串/模糊全部层级落空。""" + + @pytest.mark.parametrize("clean_db", [{"五 粮 液": "000858"}], indirect=True) + def test_spaced_input_resolves_via_list(self, clean_db): + ntc.extend_AkShare() + assert resolver_name_to_code_list("五 粮 液") == [ + Stock("000858", "五粮液", "a") + ] + + @pytest.mark.parametrize("clean_db", [{"五 粮 液": "000858"}], indirect=True) + def test_spaced_input_is_known_name(self, clean_db): + ntc.extend_AkShare() + assert ntc.is_known_stock_name("五 粮 液") is True + + def test_spaced_input_resolves_legacy(self): + # 本地映射已有无空格拼写:legacy 入口对带空格输入同样命中 + assert resolve_name_to_code("五 粮 液") == "000858" + + # --------------------------------------------------------------------------- # US_stock_code_match # --------------------------------------------------------------------------- @@ -364,6 +389,104 @@ def test_rename_existing_code_updates_canonical_name_and_keeps_alias(self, clean # 旧名称作为别名仍然可解析,且展示当前官方名称 assert resolver_name_to_code_list("旧名称") == [Stock("600000", "新名称", "a")] + +class TestCompactStockNameMerge: + """AkShare 名称内嵌空白压平:stockDB 只存无空格拼写。 + + 带空格名称("五 粮 液")与本地无空格拼写("五粮液")语义相同: + 压平后比较相等 → 不触发假性改名/别名;全名精确匹配对常规输入可见。 + """ + + @pytest.mark.parametrize("clean_db", [{"五 粮 液": "600000"}], indirect=True) + def test_spaced_akshare_name_compacted(self, clean_db): + # 600000 不在本地映射:新条目以压平拼写写入(000858 本地已有、 + # 压平后相等属"无变更"路径,见下一条用例) + assert ntc.extend_AkShare() is True + assert ntc.stockDB["600000"] == "五粮液" + + @pytest.mark.parametrize("clean_db", [{"五 粮 液": "000858"}], indirect=True) + def test_spaced_name_vs_local_no_spurious_alias(self, clean_db): + # 本地已有无空格拼写:压平后相等,不得制造假性别名/假性改名 + ntc.stockDB.clear() + ntc.stockDB.update({"000858": "五粮液"}) + ntc._names_cache[:] = [None, None, None] + ntc._akshare_merged = None + ntc.stockAliases.clear() + assert ntc.extend_AkShare() is False + assert ntc.stockDB["000858"] == "五粮液" + assert "000858" not in ntc.stockAliases + + @pytest.mark.parametrize("clean_db", [{"五 粮 液": "000858"}], indirect=True) + def test_spaced_name_exact_match_after_merge(self, clean_db): + # 压平后的规范名对常规无空格输入整名可见(含 Step 3 精确匹配口径) + ntc.extend_AkShare() + assert ntc.is_known_stock_name("五粮液") is True + assert resolver_name_to_code_list("五粮液") == [Stock("000858", "五粮液", "a")] + + @pytest.mark.parametrize( + "clean_db", [{" ": "600000", "万 科A": "000002"}], indirect=True + ) + def test_whitespace_only_name_skipped(self, clean_db): + # 压平后为空的名称条目跳过,不写入空串;"万 科A" 归一后为 + # "万科A"(NFKC 宽度归一 + 去空白) + assert ntc.extend_AkShare() is True + assert ntc.stockDB["000002"] == "万科A" + assert "600000" not in ntc.stockDB or ntc.stockDB["600000"] != "" + + +class TestStockNameWidthNormalization: + """库名宽度归一(_normalize_stock_name = NFKC + 去空白):源数据的 + 全角拼写(AkShare "京东方A"、磁盘缓存历史数据)与 NFKC 归一后的 + 用户输入("京东方A")必须同源同变换——否则全名精确匹配落空,且会被 + 更短的库内名误切("京东")。""" + + @pytest.mark.parametrize("clean_db", [{"京东方A": "000725"}], indirect=True) + def test_akshare_fullwidth_name_normalized_on_merge(self, clean_db): + # 合并入口归一:全角A名称以半角拼写写入 stockDB + assert ntc.extend_AkShare() is True + assert ntc.stockDB["000725"] == "京东方A" + + @pytest.mark.parametrize("clean_db", [{"京东方A": "000725"}], indirect=True) + def test_fullwidth_and_halfwidth_queries_both_resolve(self, clean_db): + ntc.extend_AkShare() + # 查询入口同源归一:全角/半角输入皆可解析,展示名统一为归一拼写 + assert ntc.resolver_name_to_code_list("京东方A") == [ + Stock("000725", "京东方A", "a") + ] + assert ntc.resolver_name_to_code_list("京东方A") == [ + Stock("000725", "京东方A", "a") + ] + assert ntc.is_known_stock_name("京东方A") is True + + @pytest.mark.parametrize("clean_db", [{"京东方A": "000725"}], indirect=True) + def test_legacy_fullwidth_input_resolves(self, clean_db): + # legacy 入口查询归一(生产缓存侧名称经 _build_name_map_from_df + # 已归一,mock 按生产形态给出半角键) + assert ntc.resolve_name_to_code("京东方A") == "000725" + + def test_local_name_indexes_normalized(self): + # 构建器内部归一:全角拼写输入的索引键为半角 + unique, ambiguous = ntc._build_local_name_indexes({"000725": "京东方A"}) + assert unique == {"京东方A": "000725"} + assert ambiguous == set() + + @pytest.mark.usefixtures("real_akshare_path") + def test_disk_cache_names_normalized_on_load(self): + # 磁盘缓存里的历史未归一名称:加载即归一(零网络,落盘时间戳新鲜) + import json + import time as time_mod + + ntc._akshare_disk_checked = False + ntc._AKSHARE_DISK_CACHE_PATH.parent.mkdir(parents=True, exist_ok=True) + ntc._AKSHARE_DISK_CACHE_PATH.write_text( + json.dumps( + {"ts": time_mod.time(), "map": {"京东方A": "000725"}}, + ensure_ascii=False, + ), + encoding="utf-8", + ) + assert ntc._get_akshare_name_to_code() == {"京东方A": "000725"} + # --------------------------------------------------------------------------- # AkShare 单飞并发:真实 _get_akshare_name_to_code + _fetch_akshare_df 假拉取 # --------------------------------------------------------------------------- @@ -422,7 +545,9 @@ def real_akshare_path(monkeypatch, tmp_path): ntc._akshare_cache, ntc._akshare_failure_cache, ntc._akshare_merged = saved[:3] ntc._akshare_inflight, ntc._akshare_disk_checked = saved[3:] ntc.stockDB.clear() - ntc.stockDB.update(STOCK_NAME_MAP) + ntc.stockDB.update( + {c: ntc._normalize_stock_name(n) for c, n in STOCK_NAME_MAP.items()} + ) ntc._names_cache[:] = [None, None, None] ntc._pinyin_cache[:] = [None, None] ntc.stockAliases.clear() diff --git a/tests/test_searxng_env_docs.py b/tests/test_searxng_env_docs.py index 4ed8dbbfc82..25942cd3f81 100644 --- a/tests/test_searxng_env_docs.py +++ b/tests/test_searxng_env_docs.py @@ -26,6 +26,16 @@ def test_env_example_defaults_public_searxng_instances_off() -> None: assert "SEARXNG_PUBLIC_INSTANCES_ENABLED=true" not in env_example +def test_searxng_timeout_env_contract() -> None: + from src.config import parse_env_int + + env_example = (ROOT_DIR / ".env.example").read_text(encoding="utf-8") + assert "SEARXNG_TIMEOUT_SECONDS=10" in env_example + assert parse_env_int(None, 10, field_name="SEARXNG_TIMEOUT_SECONDS", minimum=1) == 10 + assert parse_env_int("25", 10, field_name="SEARXNG_TIMEOUT_SECONDS", minimum=1) == 25 + assert parse_env_int("0", 10, field_name="SEARXNG_TIMEOUT_SECONDS", minimum=1) == 1 + + def test_daily_analysis_workflow_matches_documented_searxng_variable_mapping() -> None: workflow = ( ROOT_DIR / ".github" / "workflows" / "00-daily-analysis.yml" @@ -131,3 +141,31 @@ def test_docs_describe_public_searxng_discovery_as_opt_in() -> None: for line in english_base_url_lines ) assert all("default `false`" in line for line in english_public_toggle_lines) + + +def test_constructor_kwargs_carry_searxng_timeout_for_subprocess_rebuild() -> None: + """bounded 题材搜索在子进程中重建 SearchService 时必须带上超时配置(PR #2249 blocker)。""" + from src.search_service import SearchService + + service = SearchService( + searxng_base_urls=["http://searxng.local:8080"], + searxng_timeout_seconds=25, + ) + kwargs = service._constructor_kwargs + assert kwargs["searxng_timeout_seconds"] == 25 + assert kwargs["searxng_base_urls"] == ["http://searxng.local:8080"] + + # 子进程按同一 kwargs 重建后,provider 应拿到相同超时 + rebuilt = SearchService(**kwargs) + searxng = next(p for p in rebuilt._providers if p.name == "SearXNG") + assert searxng._self_hosted_timeout_seconds == 25 + + +def test_daily_analysis_workflow_maps_searxng_timeout_variable() -> None: + workflow = ( + ROOT_DIR / ".github" / "workflows" / "00-daily-analysis.yml" + ).read_text(encoding="utf-8") + assert ( + "SEARXNG_TIMEOUT_SECONDS: ${{ vars.SEARXNG_TIMEOUT_SECONDS || secrets.SEARXNG_TIMEOUT_SECONDS }}" + in workflow + ) diff --git a/tests/test_stock_code_utils.py b/tests/test_stock_code_utils.py index 7f0623103d8..af51990a038 100644 --- a/tests/test_stock_code_utils.py +++ b/tests/test_stock_code_utils.py @@ -94,8 +94,14 @@ def test_kr_suffix_adds_only_its_legacy_bare_candidate(self): assert identity.market == "kr" assert identity.code_candidates == ("005930.KS", "005930") - def test_bare_code_with_unsupported_market_hint_fails_closed(self): - assert resolve_daily_stock_identity("005930", market_hint="tw") is None + def test_bare_taiwan_code_uses_explicit_market_hint(self): + identity = resolve_daily_stock_identity("005930", market_hint="tw") + + assert identity is not None + assert identity.normalized_code == "005930" + assert identity.market == "tw" + assert identity.refill_code == "" + assert identity.code_candidates == ("005930",) def test_cross_market_bare_code_without_hint_fails_closed(self): assert resolve_daily_stock_identity("8035") is None diff --git a/tests/test_stock_profile_api.py b/tests/test_stock_profile_api.py new file mode 100644 index 00000000000..6f541d8ad6b --- /dev/null +++ b/tests/test_stock_profile_api.py @@ -0,0 +1,708 @@ +# -*- coding: utf-8 -*- +"""Contract tests for the stock profile aggregate endpoint.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import tempfile +from pathlib import Path +from unittest.mock import MagicMock, patch + +from fastapi.testclient import TestClient +import pytest + +import src.auth as auth +from api.app import create_app +from src.config import Config +from src.services.stock_profile_service import InvalidStockProfileCode, StockProfileService +from src.storage import DatabaseManager + + +def test_stock_profile_service_import_is_independent_of_api_bootstrap() -> None: + result = subprocess.run( + [ + sys.executable, + "-c", + "from src.services.stock_profile_service import StockProfileService; " + "assert StockProfileService.__name__ == 'StockProfileService'", + ], + cwd=Path(__file__).resolve().parents[1], + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode == 0, result.stderr + + +def _quote(code: str = "AAPL") -> dict: + return { + "stock_code": code, + "stock_name": "Apple", + "current_price": 200.0, + "change": 1.0, + "change_percent": 0.5, + "update_time": "2026-08-29T10:00:00+08:00", + } + + +def _history() -> dict: + return { + "data": [ + { + "date": "2026-08-28", + "open": 198.0, + "high": 202.0, + "low": 197.0, + "close": 200.0, + "volume": 1000.0, + } + ] + } + + +def _report_list() -> dict: + return { + "items": [ + { + "id": 12, + "query_id": "query-12", + "stock_code": "AAPL", + "stock_name": "Apple", + "analysis_summary": "Demand remains resilient", + "sentiment_score": 70, + "created_at": "2026-08-28T12:00:00+08:00", + } + ], + "total": 1, + } + + +def _report_detail() -> dict: + return { + "id": 12, + "query_id": "query-12", + "stock_code": "AAPL", + "stock_name": "Apple", + "analysis_summary": "Demand remains resilient", + "operation_advice": "Watch", + "action": "watch", + "action_label": "Watch", + "trend_prediction": "Neutral", + "sentiment_score": 70, + "stop_loss": "180", + "created_at": "2026-08-28T12:00:00+08:00", + "context_snapshot": None, + } + + +def _intelligence(code: str = "AAPL", market: str = "us") -> dict: + return { + "items": [ + { + "id": 5, + "source_type": "rss", + "title": "Company update", + "url": "https://example.com/update", + "scope_type": "symbol", + "scope_value": code, + "market": market, + } + ], + "total": 1, + } + + +def _service(**overrides: object) -> tuple[StockProfileService, dict[str, MagicMock]]: + dependencies = { + "stock_service": MagicMock(), + "history_service": MagicMock(), + "intelligence_service": MagicMock(), + "portfolio_repository": MagicMock(), + "alert_service": MagicMock(), + } + dependencies.update(overrides) + dependencies["stock_service"].get_realtime_quote.return_value = _quote() + dependencies["stock_service"].get_history_data.return_value = _history() + dependencies["history_service"].get_history_list.return_value = _report_list() + dependencies["history_service"].get_history_detail_by_id.return_value = _report_detail() + dependencies["history_service"].get_latest_fundamental_snapshot.return_value = None + dependencies["intelligence_service"].list_items.return_value = _intelligence() + dependencies["portfolio_repository"].list_cached_position_identities.return_value = [("us", "aapl")] + dependencies["alert_service"].list_rules.return_value = { + "items": [{"id": 8, "enabled": True}, {"id": 9, "enabled": False}], + "total": 2, + } + return StockProfileService(**dependencies), dependencies + + +def test_profile_uses_one_canonical_code_and_returns_structured_research() -> None: + service, dependencies = _service() + + payload = service.get_profile("aapl", history_days=45) + + assert payload["canonical_code"] == "AAPL" + assert payload["market"] == "us" + assert payload["quote"]["status"] == "fresh" + assert payload["history"]["status"] == "fresh" + assert payload["research"]["status"] == "fresh" + assert payload["research"]["data"]["structured_report"]["artifact_id"] == "report:12" + assert payload["portfolio"]["data"] == {"held": True, "matched_markets": ["us"]} + assert payload["monitors"]["data"] == { + "total_rule_count": 2, + "enabled_rule_count": 1, + "rule_ids": [8, 9], + } + assert payload["evidence_quality"]["status"] == "partial" + dependencies["stock_service"].get_realtime_quote.assert_called_once_with("AAPL") + dependencies["stock_service"].get_history_data.assert_called_once_with( + "AAPL", period="daily", days=45 + ) + dependencies["history_service"].get_history_list.assert_called_once_with( + stock_code="AAPL", page=1, limit=5, market_hint="us" + ) + assert {call.kwargs["scope_value"] for call in dependencies["intelligence_service"].list_items.call_args_list} == { + "AAPL", + "AAPL.US", + } + assert {call.kwargs["target"] for call in dependencies["alert_service"].list_rules.call_args_list} == { + "AAPL", + "AAPL.US", + } + assert dependencies["intelligence_service"].list_items.call_count == 4 + assert dependencies["alert_service"].list_rules.call_count == 2 + + +def test_profile_alias_queries_are_unique_by_casefolded_identity() -> None: + aliases = StockProfileService._code_aliases("600519", market_hint="cn") + + assert len(aliases) == len({alias.casefold() for alias in aliases}) + + +@pytest.mark.parametrize("code", ["600519.SZ", "000001.SH", "920748.SH"]) +def test_profile_rejects_exchange_conflicts_before_downstream_queries(code: str) -> None: + service, dependencies = _service() + + with pytest.raises(InvalidStockProfileCode): + service.get_profile(code) + + dependencies["stock_service"].get_realtime_quote.assert_not_called() + dependencies["history_service"].get_history_list.assert_not_called() + + +def test_profile_research_preserves_specialized_report_evidence() -> None: + service, dependencies = _service() + detail = _report_detail() + detail["context_snapshot"] = { + "fundamental_context": { + "earnings": { + "data": { + "financial_report": {"report_date": "2026-06-30"}, + "dividend": {"ttm_cash_dividend_per_share": 1.2}, + } + } + } + } + detail["raw_result"] = { + "market_structure_context": { + "schema_version": "market-structure-v1", + "status": "available", + "market_theme_context": {"schema_version": "market-theme-v1"}, + "stock_market_position": {"schema_version": "stock-market-position-v1"}, + } + } + dependencies["history_service"].get_history_detail_by_id.return_value = detail + + payload = service.get_profile("AAPL") + + artifact = payload["research"]["data"]["structured_report"] + evidence_ids = {item["id"] for item in artifact["evidence"]} + assert { + "fundamental:financial_report", + "fundamental:dividend_metrics", + "market:structure", + } <= evidence_ids + assert artifact["data_quality"]["source_count"] == len(artifact["evidence"]) + + +def test_profile_research_reads_independent_fundamental_snapshot() -> None: + service, dependencies = _service() + detail = _report_detail() + detail["storage_stock_code"] = "AAPL.US" + dependencies["history_service"].get_history_detail_by_id.return_value = detail + dependencies["history_service"].get_latest_fundamental_snapshot.return_value = { + "earnings": { + "data": { + "financial_report": {"report_date": "2026-06-30"}, + "dividend": {"ttm_cash_dividend_per_share": 1.2}, + } + } + } + + payload = service.get_profile("AAPL") + + artifact = payload["research"]["data"]["structured_report"] + evidence_ids = {item["id"] for item in artifact["evidence"]} + assert { + "fundamental:financial_report", + "fundamental:dividend_metrics", + } <= evidence_ids + dependencies["history_service"].get_latest_fundamental_snapshot.assert_called_once_with( + query_id="query-12", + stock_code="AAPL.US", + ) + + +def test_hk_alias_is_canonicalized_before_every_downstream_query() -> None: + service, dependencies = _service() + dependencies["stock_service"].get_realtime_quote.return_value = _quote("HK00700") + dependencies["history_service"].get_history_list.return_value = {"items": [], "total": 0} + dependencies["intelligence_service"].list_items.return_value = _intelligence("HK00700", "hk") + + payload = service.get_profile("00700.HK") + + assert payload["canonical_code"] == "HK00700" + assert payload["market"] == "hk" + dependencies["stock_service"].get_realtime_quote.assert_called_once_with("HK00700") + dependencies["history_service"].get_history_list.assert_called_once_with( + stock_code="HK00700", page=1, limit=5, market_hint="hk" + ) + assert "00700.HK" in { + call.kwargs["scope_value"] + for call in dependencies["intelligence_service"].list_items.call_args_list + } + assert "00700.HK" in { + call.kwargs["target"] for call in dependencies["alert_service"].list_rules.call_args_list + } + + +def test_jp_and_kr_codes_preserve_shared_market_identity() -> None: + jp_service, _ = _service() + kr_service, kr_dependencies = _service() + + jp_payload = jp_service.get_profile("7203.T") + kr_payload = kr_service.get_profile("005930") + + assert jp_payload["canonical_code"] == "7203.T" + assert jp_payload["market"] == "jp" + assert kr_payload["canonical_code"] == "005930.KS" + assert kr_payload["market"] == "kr" + assert {call.kwargs["market"] for call in kr_dependencies["intelligence_service"].list_items.call_args_list} == { + "kr", + "global", + } + + +def test_portfolio_identity_uses_cached_market_hint_and_requires_same_market() -> None: + jp_service, jp_dependencies = _service() + jp_dependencies["portfolio_repository"].list_cached_position_identities.return_value = [ + ("jp", "8035"), + ] + kr_service, kr_dependencies = _service() + kr_dependencies["portfolio_repository"].list_cached_position_identities.return_value = [ + ("cn", "005930"), + ] + + jp_payload = jp_service.get_profile("8035.T") + kr_payload = kr_service.get_profile("005930.KS") + + assert jp_payload["portfolio"]["data"] == {"held": True, "matched_markets": ["jp"]} + assert kr_payload["portfolio"]["data"] == {"held": False, "matched_markets": []} + + +def test_legacy_bare_korean_position_keeps_market_hint_during_profile_match() -> None: + service, dependencies = _service() + dependencies["portfolio_repository"].list_cached_position_identities.return_value = [ + ("kr", "123456"), + ] + + payload = service.get_profile("123456.KS") + + assert payload["portfolio"]["data"] == {"held": True, "matched_markets": ["kr"]} + + +def test_short_hk_cached_position_uses_its_market_hint() -> None: + service, dependencies = _service() + dependencies["portfolio_repository"].list_cached_position_identities.return_value = [ + ("hk", "700"), + ] + + payload = service.get_profile("HK00700") + + assert payload["portfolio"]["data"] == {"held": True, "matched_markets": ["hk"]} + + +def test_bare_taiwan_cached_position_uses_its_market_hint() -> None: + service, dependencies = _service() + dependencies["portfolio_repository"].list_cached_position_identities.return_value = [ + ("tw", "2330"), + ] + + payload = service.get_profile("2330.TW") + + assert payload["portfolio"]["data"] == {"held": True, "matched_markets": ["tw"]} + + +def test_taiwan_intelligence_reads_bare_alias_only_with_market_scope() -> None: + service, dependencies = _service() + + def intelligence_by_alias(**kwargs: object) -> dict: + if kwargs.get("scope_value") == "2330" and kwargs.get("market") == "tw": + return _intelligence("2330", "tw") + return {"items": [], "total": 0} + + dependencies["intelligence_service"].list_items.side_effect = intelligence_by_alias + + payload = service.get_profile("2330.TW") + + calls = { + (call.kwargs["scope_value"], call.kwargs["market"]) + for call in dependencies["intelligence_service"].list_items.call_args_list + } + assert ("2330", "tw") in calls + assert ("2330", "global") not in calls + assert payload["intelligence"]["items"][0]["scope_value"] == "2330" + + +def test_japan_intelligence_reads_bare_alias_only_with_market_scope() -> None: + service, dependencies = _service() + + def intelligence_by_alias(**kwargs: object) -> dict: + if kwargs.get("scope_value") == "8035" and kwargs.get("market") == "jp": + return _intelligence("8035", "jp") + return {"items": [], "total": 0} + + dependencies["intelligence_service"].list_items.side_effect = intelligence_by_alias + + payload = service.get_profile("8035.T") + + calls = { + (call.kwargs["scope_value"], call.kwargs["market"]) + for call in dependencies["intelligence_service"].list_items.call_args_list + } + assert ("8035", "jp") in calls + assert ("8035", "global") not in calls + assert payload["intelligence"]["items"][0]["scope_value"] == "8035" + + +def test_offshore_research_lookup_excludes_cross_market_bare_numeric_aliases() -> None: + service, dependencies = _service() + dependencies["history_service"].get_history_list.return_value = {"items": [], "total": 0} + + payload = service.get_profile("8035.T") + + assert payload["research"]["status"] == "unavailable" + dependencies["history_service"].get_history_list.assert_called_once_with( + stock_code="8035.T", + page=1, + limit=5, + market_hint="jp", + include_ambiguous_numeric_aliases=False, + ) + + +def test_offshore_monitor_lookup_keeps_market_unique_bare_numeric_alias() -> None: + service, dependencies = _service() + + def rules_by_alias(**kwargs: object) -> dict: + if kwargs.get("target") == "005930": + return {"items": [{"id": 99, "enabled": True}], "total": 1} + return {"items": [], "total": 0} + + dependencies["alert_service"].list_rules.side_effect = rules_by_alias + + payload = service.get_profile("005930.KS") + + queried_targets = { + call.kwargs["target"] for call in dependencies["alert_service"].list_rules.call_args_list + } + assert "005930" in queried_targets + assert "005930.KS" in queried_targets + assert payload["monitors"]["data"]["total_rule_count"] == 1 + + +def test_hk_monitor_lookup_keeps_unpadded_legacy_target() -> None: + service, dependencies = _service() + + def rules_by_alias(**kwargs: object) -> dict: + if kwargs.get("target") == "700": + return {"items": [{"id": 77, "enabled": True}], "total": 1} + return {"items": [], "total": 0} + + dependencies["alert_service"].list_rules.side_effect = rules_by_alias + + payload = service.get_profile("HK00700") + + queried_targets = { + call.kwargs["target"] for call in dependencies["alert_service"].list_rules.call_args_list + } + assert "700" in queried_targets + assert payload["monitors"]["data"]["rule_ids"] == [77] + + +def test_profile_collects_intelligence_and_monitors_saved_under_legacy_aliases() -> None: + service, dependencies = _service() + + def intelligence_by_alias(**kwargs: object) -> dict: + if kwargs.get("scope_value") == "600519.SH": + return _intelligence("600519.SH", "cn") + return {"items": [], "total": 0} + + def rules_by_alias(**kwargs: object) -> dict: + if kwargs.get("target") == "SH600519": + return {"items": [{"id": 88, "enabled": True}], "total": 1} + return {"items": [], "total": 0} + + dependencies["intelligence_service"].list_items.side_effect = intelligence_by_alias + dependencies["alert_service"].list_rules.side_effect = rules_by_alias + + payload = service.get_profile("600519") + + assert payload["intelligence"]["status"] == "fresh" + assert payload["intelligence"]["items"][0]["scope_value"] == "600519.SH" + assert payload["monitors"]["data"] == { + "total_rule_count": 1, + "enabled_rule_count": 1, + "rule_ids": [88], + } + + +def test_explicit_cn_identity_never_reexpands_through_a_colliding_kr_alias() -> None: + service, dependencies = _service() + dependencies["history_service"].get_history_list.return_value = {"items": [], "total": 0} + + payload = service.get_profile("SZ000660") + + assert payload["canonical_code"] == "000660" + assert payload["market"] == "cn" + dependencies["history_service"].get_history_list.assert_called_once_with( + stock_code="000660", + page=1, + limit=5, + market_hint="cn", + ) + intelligence_aliases = { + call.kwargs["scope_value"] + for call in dependencies["intelligence_service"].list_items.call_args_list + } + monitor_aliases = { + call.kwargs["target"] for call in dependencies["alert_service"].list_rules.call_args_list + } + intelligence_calls = { + (call.kwargs["scope_value"], call.kwargs["market"]) + for call in dependencies["intelligence_service"].list_items.call_args_list + } + assert "000660.KS" not in intelligence_aliases + assert "000660.KS" not in monitor_aliases + assert ("000660", "cn") in intelligence_calls + assert ("000660", "global") not in intelligence_calls + assert {"SZ000660", "000660.SZ"} <= intelligence_aliases + assert {"SZ000660", "000660.SZ"} <= monitor_aliases + + +def test_unambiguous_cn_bare_code_remains_available_to_global_and_monitor_queries() -> None: + service, dependencies = _service() + + service.get_profile("600519") + + intelligence_calls = { + (call.kwargs["scope_value"], call.kwargs["market"]) + for call in dependencies["intelligence_service"].list_items.call_args_list + } + monitor_targets = { + call.kwargs["target"] for call in dependencies["alert_service"].list_rules.call_args_list + } + assert ("600519", "global") in intelligence_calls + assert "600519" in monitor_targets + + +def test_us_suffix_converges_to_bare_ticker_and_queries_legacy_aliases() -> None: + service, dependencies = _service() + + payload = service.get_profile("AAPL.US") + + assert payload["canonical_code"] == "AAPL" + assert payload["market"] == "us" + assert payload["portfolio"]["data"]["held"] is True + dependencies["stock_service"].get_realtime_quote.assert_called_once_with("AAPL") + dependencies["history_service"].get_history_list.assert_called_once_with( + stock_code="AAPL", page=1, limit=5, market_hint="us" + ) + assert {"AAPL", "AAPL.US"} <= { + call.kwargs["scope_value"] + for call in dependencies["intelligence_service"].list_items.call_args_list + } + assert {"AAPL", "AAPL.US"} <= { + call.kwargs["target"] for call in dependencies["alert_service"].list_rules.call_args_list + } + + +def test_profile_includes_global_symbol_intelligence() -> None: + service, dependencies = _service() + + def intelligence_by_market(**kwargs: object) -> dict: + if kwargs.get("scope_value") == "AAPL" and kwargs.get("market") == "global": + return _intelligence("AAPL", "global") + return {"items": [], "total": 0} + + dependencies["intelligence_service"].list_items.side_effect = intelligence_by_market + + payload = service.get_profile("AAPL") + + assert payload["intelligence"]["status"] == "fresh" + assert payload["intelligence"]["items"][0]["market"] == "global" + + +def test_empty_intelligence_keeps_partial_status_when_any_alias_query_fails() -> None: + service, dependencies = _service() + + def partially_failing_query(**kwargs: object) -> dict: + if kwargs.get("scope_value") == "AAPL.US" and kwargs.get("market") == "us": + raise RuntimeError("transient query failure") + return {"items": [], "total": 0} + + dependencies["intelligence_service"].list_items.side_effect = partially_failing_query + + payload = service.get_profile("AAPL") + + assert payload["intelligence"] == { + "status": "partial", + "items": [], + "limitations": ["intelligence_alias_query_partial"], + } + + +def test_optional_block_failures_remain_partial_and_do_not_hide_monitor_data() -> None: + service, dependencies = _service() + dependencies["stock_service"].get_realtime_quote.side_effect = RuntimeError("quote failed") + dependencies["stock_service"].get_history_data.return_value = {"data": []} + dependencies["history_service"].get_history_detail_by_id.return_value = None + dependencies["intelligence_service"].list_items.side_effect = RuntimeError("intel failed") + dependencies["portfolio_repository"].list_cached_position_identities.side_effect = RuntimeError("db failed") + + payload = service.get_profile("AAPL") + + assert payload["quote"]["status"] == "unavailable" + assert payload["history"]["status"] == "unavailable" + assert payload["research"]["status"] == "partial" + assert payload["research"]["data"]["recent_reports"][0]["id"] == 12 + assert payload["intelligence"]["status"] == "unavailable" + assert payload["portfolio"]["status"] == "unavailable" + assert payload["monitors"]["status"] == "fresh" + assert payload["evidence_quality"]["status"] == "partial" + assert "latest_report_detail_unavailable" in payload["evidence_quality"]["limitations"] + + +def test_all_dependency_failures_return_unavailable_profile_instead_of_raising() -> None: + service, dependencies = _service() + for dependency, method in ( + ("stock_service", "get_realtime_quote"), + ("stock_service", "get_history_data"), + ("history_service", "get_history_list"), + ("intelligence_service", "list_items"), + ("portfolio_repository", "list_cached_position_identities"), + ("alert_service", "list_rules"), + ): + getattr(dependencies[dependency], method).side_effect = RuntimeError("offline") + + payload = service.get_profile("600519") + + assert payload["market"] == "cn" + assert payload["evidence_quality"]["status"] == "unavailable" + assert set(payload["evidence_quality"]["blocks"].values()) == {"unavailable"} + + +def _reset_auth_globals() -> None: + auth._auth_enabled = None + auth._session_secret = None + auth._password_hash_salt = None + auth._password_hash_stored = None + auth._rate_limit = {} + + +def _endpoint_payload() -> dict: + service, _ = _service() + return service.get_profile("AAPL") + + +def test_profile_endpoint_validates_code_and_exposes_contract() -> None: + _reset_auth_globals() + with tempfile.TemporaryDirectory() as temp_dir: + try: + os.environ["DATABASE_PATH"] = str(Path(temp_dir) / "profile.db") + os.environ["ADMIN_AUTH_ENABLED"] = "false" + Config.reset_instance() + DatabaseManager.reset_instance() + app = create_app(static_dir=Path(temp_dir) / "empty-static") + client = TestClient(app) + with patch( + "api.v1.endpoints.stocks.StockProfileService.get_profile", + return_value=_endpoint_payload(), + ) as get_profile: + response = client.get("/api/v1/stocks/AAPL/profile", params={"history_days": 90}) + jp = client.get("/api/v1/stocks/7203.T/profile") + kr = client.get("/api/v1/stocks/005930.KS/profile") + tw = client.get("/api/v1/stocks/2330.TW/profile") + two = client.get("/api/v1/stocks/6505.TWO/profile") + tw_etf = client.get("/api/v1/stocks/006208.TW/profile") + invalid = client.get("/api/v1/stocks/invalid-code/profile") + conflicts = [ + client.get(f"/api/v1/stocks/{code}/profile") + for code in ("600519.SZ", "000001.SH", "920748.SH") + ] + + assert response.status_code == 200, response.text + assert response.json()["canonical_code"] == "AAPL" + assert [item.args for item in get_profile.call_args_list] == [ + ("AAPL",), + ("7203.T",), + ("005930.KS",), + ("2330.TW",), + ("6505.TWO",), + ("006208.TW",), + ] + assert [item.kwargs for item in get_profile.call_args_list] == [ + {"history_days": 90}, + {"history_days": 60}, + {"history_days": 60}, + {"history_days": 60}, + {"history_days": 60}, + {"history_days": 60}, + ] + assert invalid.status_code == 400 + assert [item.status_code for item in conflicts] == [400, 400, 400] + assert { + item.json()["error"] + for item in conflicts + } == {"invalid_stock_code"} + assert jp.status_code == 200 + assert kr.status_code == 200 + assert tw.status_code == 200 + assert two.status_code == 200 + assert tw_etf.status_code == 200 + finally: + DatabaseManager.reset_instance() + Config.reset_instance() + os.environ.pop("DATABASE_PATH", None) + os.environ.pop("ADMIN_AUTH_ENABLED", None) + _reset_auth_globals() + + +def test_static_openapi_matches_stock_profile_runtime_contract() -> None: + static_spec = json.loads( + (Path(__file__).resolve().parents[1] / "docs" / "architecture" / "api_spec.json").read_text( + encoding="utf-8" + ) + ) + runtime_spec = create_app().openapi() + api_path = "/api/v1/stocks/{stock_code}/profile" + assert static_spec["paths"][api_path] == runtime_spec["paths"][api_path] + schema_names = [ + name for name in runtime_spec["components"]["schemas"] if name.startswith("StockProfile") + ] + assert schema_names + for schema_name in schema_names: + assert static_spec["components"]["schemas"][schema_name] == runtime_spec["components"]["schemas"][schema_name]