Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/00-daily-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}

# ==========================================
# 通知渠道(可同时配置多个,全部推送)
Expand Down
12 changes: 10 additions & 2 deletions api/v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
40 changes: 40 additions & 0 deletions api/v1/endpoints/stocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
ExtractItem,
KLineData,
StockHistoryResponse,
StockProfileResponse,
StockQuote,
)
from api.v1.schemas.history import WatchlistRequest, WatchlistResponse
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions api/v1/schemas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
StockQuote,
StockHistoryResponse,
KLineData,
StockProfileResponse,
)
from api.v1.schemas.backtest import (
BacktestRunRequest,
Expand Down Expand Up @@ -184,6 +185,7 @@
"StockQuote",
"StockHistoryResponse",
"KLineData",
"StockProfileResponse",
# backtest
"BacktestRunRequest",
"BacktestRunResponse",
Expand Down
82 changes: 81 additions & 1 deletion api/v1/schemas/stocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""股票实时行情"""
Expand Down Expand Up @@ -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
16 changes: 13 additions & 3 deletions apps/dsa-desktop/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion apps/dsa-desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
}
},
"overrides": {
"builder-util-runtime": "9.7.0"
"builder-util-runtime": "9.7.0",
"js-yaml": "4.3.1"
}
}
6 changes: 6 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 继续保留。
Expand All @@ -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 个分词单元测试。
<!-- 新条目格式:- [类型] 描述(类型取值:新功能/改进/修复/文档/测试/chore)-->
<!-- 每条独立一行追加到本段末尾,无需分类标题,合并时冲突最小 -->
Expand Down
1 change: 1 addition & 0 deletions docs/INDEX.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 合规资讯源配置、测试、拉取、去重、存储、查询与安全边界 |
Expand Down
1 change: 1 addition & 0 deletions docs/INDEX_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/) <sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> (Chinese-only) | Feishu, DingTalk, Discord, and related Bot configuration screenshots and notes |
| [Real-Time Alert Center](alerts.md) <sub><sub>![P4 Badge](https://img.shields.io/badge/P4-yellow?style=flat)</sub></sub> (Chinese-only) | EventMonitor baseline, Web rule management, notification attempts, cooldown state, and phase boundaries |
| [Stock Profile API](stock-profile-api.md) <sub><sub>![P1 Badge](https://img.shields.io/badge/P1-yellow?style=flat)</sub></sub> (Chinese-only) | Single stock-profile contract, per-block quality status, code normalization, and Web phase boundaries |
| [DecisionSignal Topic](decision-signals.md) <sub><sub>![P7 Badge](https://img.shields.io/badge/P7-orange?style=flat)</sub></sub> (Chinese-only) | AI signal fields, API, Web display, alert/notification/portfolio-risk linkage, outcome evaluation, redaction, migration, and rollback |
| [ResearchArtifact Contract](research-artifact.md) <sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> (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) <sub><sub>![P6 Badge](https://img.shields.io/badge/P6-orange?style=flat)</sub></sub> (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 |
Expand Down
Loading
Loading