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
104 changes: 80 additions & 24 deletions data_provider/fundamental_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from __future__ import annotations

import logging
import math
import re
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Tuple
Expand Down Expand Up @@ -141,11 +142,15 @@ def _extract_cash_dividend_per_share(row: pd.Series) -> Optional[float]:
return _parse_dividend_plan_to_per_share(plan_text)


def _filter_rows_by_code(df: pd.DataFrame, stock_code: str) -> pd.DataFrame:
def _filter_rows_by_code(
df: pd.DataFrame, stock_code: str, *, require_code: bool = False,
) -> pd.DataFrame:
if df is None or df.empty:
return pd.DataFrame()
code_cols = [c for c in df.columns if any(k in str(c) for k in ("代码", "股票代码", "证券代码", "symbol", "ts_code"))]
if not code_cols:
if require_code:
raise ValueError("Market-wide result is missing a stock code column")
return df

target = _normalize_code(stock_code)
Expand All @@ -160,11 +165,50 @@ def _filter_rows_by_code(df: pd.DataFrame, stock_code: str) -> pd.DataFrame:
return pd.DataFrame()


def _recent_report_dates(now: Optional[datetime] = None) -> List[str]:
"""Bound report-period fallback to the two most recently completed quarters."""
now = now or datetime.now()
quarter_start = datetime(now.year, (now.month - 1) // 3 * 3 + 1, 1)
dates = []
for _ in range(2):
end = quarter_start - timedelta(days=1)
dates.append(end.strftime("%Y%m%d"))
quarter_start = datetime(end.year, (end.month - 1) // 3 * 3 + 1, 1)
return dates


def _normalize_report_date(value: Any) -> Optional[str]:
parsed = _safe_datetime(value)
return parsed.date().isoformat() if parsed else None


def _earnings_forecast_summary(row: pd.Series) -> str:
"""Read disclosure text by exact column, never an announcement date/rate."""
for column in ("业绩变动", "业绩变动原因", "预告类型", "预告", "摘要"):
value = row.get(column)
if isinstance(value, str) and value.strip().lower() not in ("", "-", "nan", "none", "nat", "<na>"):
return value.strip()[:200]
return ""


def _earnings_quick_summary(row: pd.Series) -> str:
"""Summarize AkShare's numeric quick-report columns, excluding metadata."""
fields = (
("营业收入-营业收入", "营业收入", "元"),
("营业收入-同比增长", "营收同比", "%"),
("净利润-净利润", "净利润", "元"),
("净利润-同比增长", "净利润同比", "%"),
("每股收益", "每股收益", "元"),
("净资产收益率", "净资产收益率", "%"),
)
parts = []
for column, label, unit in fields:
value = _safe_float(row.get(column))
if value is not None and math.isfinite(value):
parts.append(f"{label}{value:.12g}{unit}")
return ";".join(parts)[:200]


def _build_dividend_payload(
dividend_df: pd.DataFrame,
stock_code: str,
Expand Down Expand Up @@ -267,6 +311,8 @@ class AkshareFundamentalAdapter:
def _call_df_candidates(
self,
candidates: List[Tuple[str, Dict[str, Any]]],
*,
stock_code: Optional[str] = None,
) -> Tuple[Optional[pd.DataFrame], Optional[str], List[str]]:
errors: List[str] = []
try:
Expand All @@ -282,6 +328,10 @@ def _call_df_candidates(
df = fn(**kwargs)
if isinstance(df, pd.Series):
df = df.to_frame().T
if isinstance(df, pd.DataFrame) and not df.empty and stock_code is not None:
# Market-wide endpoints must contain the requested stock.
# A nonempty table for other stocks must not stop fallback.
df = _filter_rows_by_code(df, stock_code, require_code=True)
if isinstance(df, pd.DataFrame) and not df.empty:
return df, func_name, errors
except Exception as exc:
Expand All @@ -302,6 +352,14 @@ def get_fundamental_bundle(self, stock_code: str) -> Dict[str, Any]:
"errors": [],
}

# Reuse the provider's market mapping after package initialization;
# importing it at module scope would cycle through data_provider.base.
from .akshare_fetcher import _to_sina_tx_symbol

shareholder_symbol = _to_sina_tx_symbol(stock_code)
stock_code = _normalize_code(stock_code)
report_dates = _recent_report_dates()

# Financial indicators
fin_df, fin_source, fin_errors = self._call_df_candidates([
("stock_financial_abstract", {"symbol": stock_code}),
Expand Down Expand Up @@ -341,33 +399,31 @@ def get_fundamental_bundle(self, stock_code: str) -> Dict[str, Any]:

# Earnings forecast
forecast_df, forecast_source, forecast_errors = self._call_df_candidates([
("stock_yjyg_em", {"symbol": stock_code}),
("stock_yjyg_em", {}),
("stock_yjbb_em", {"symbol": stock_code}),
("stock_yjbb_em", {}),
])
("stock_yjyg_em", {"date": report_date})
for report_date in report_dates
], stock_code=stock_code)
result["errors"].extend(forecast_errors)
if forecast_df is not None:
row = _extract_latest_row(forecast_df, stock_code)
if row is not None:
result["earnings"]["forecast_summary"] = _safe_str(
_pick_by_keywords(row, ["预告", "业绩变动", "内容", "摘要", "公告"])
)[:200]
result["source_chain"].append(f"earnings_forecast:{forecast_source}")
summary = _earnings_forecast_summary(row)
if summary:
result["earnings"]["forecast_summary"] = summary
result["source_chain"].append(f"earnings_forecast:{forecast_source}")

# Earnings quick report
quick_df, quick_source, quick_errors = self._call_df_candidates([
("stock_yjkb_em", {"symbol": stock_code}),
("stock_yjkb_em", {}),
])
("stock_yjkb_em", {"date": report_date})
for report_date in report_dates
], stock_code=stock_code)
result["errors"].extend(quick_errors)
if quick_df is not None:
row = _extract_latest_row(quick_df, stock_code)
if row is not None:
result["earnings"]["quick_report_summary"] = _safe_str(
_pick_by_keywords(row, ["快报", "摘要", "公告", "说明"])
)[:200]
result["source_chain"].append(f"earnings_quick:{quick_source}")
summary = _earnings_quick_summary(row)
if summary:
result["earnings"]["quick_report_summary"] = summary
result["source_chain"].append(f"earnings_quick:{quick_source}")

# Dividend details (cash dividend, pre-tax)
dividend_df, dividend_source, dividend_errors = self._call_df_candidates([
Expand All @@ -384,9 +440,11 @@ def get_fundamental_bundle(self, stock_code: str) -> Dict[str, Any]:

# Institution / top shareholders
inst_df, inst_source, inst_errors = self._call_df_candidates([
("stock_institute_hold", {}),
("stock_institute_recommend", {}),
])
("stock_institute_hold", {
"symbol": f"{report_date[:4]}{int(report_date[4:6]) // 3}",
})
for report_date in report_dates
], stock_code=stock_code)
result["errors"].extend(inst_errors)
if inst_df is not None:
row = _extract_latest_row(inst_df, stock_code)
Expand All @@ -396,10 +454,8 @@ def get_fundamental_bundle(self, stock_code: str) -> Dict[str, Any]:
result["source_chain"].append(f"institution:{inst_source}")

top10_df, top10_source, top10_errors = self._call_df_candidates([
("stock_gdfx_top_10_em", {"symbol": stock_code}),
("stock_gdfx_top_10_em", {}),
("stock_zh_a_gdhs_detail_em", {"symbol": stock_code}),
("stock_zh_a_gdhs_detail_em", {}),
("stock_gdfx_top_10_em", {"symbol": shareholder_symbol, "date": report_date})
for report_date in report_dates
])
result["errors"].extend(top10_errors)
if top10_df is not None:
Expand Down
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/).

## [Unreleased]

- [修复] 基本面适配按明确报告期调用 AkShare 业绩预告、快报及机构持股,修正十大股东市场代码并限制结果为目标股票;按真实指标生成快报摘要,避免旧默认日期、公告日期冒充摘要和跨指标错误降级。

- [修复] 桌面后端打包完整收集 MiniRacer 原生运行文件,并在 Windows/macOS 冻结产物中实际执行 JavaScript,防止筹码分布因漏包或版本错配永久失败。

- [新功能] 支持 Multi-Agent 分阶段轨迹评估:保留既有扁平工具指标并增加阶段快照、局部/累计步数、完成/失败/跳过状态与可选期望阶段命中率,单 Agent 输出保持兼容(Refs #2347)。
- [修复] Multi-Agent 各阶段的 `tool_metrics` 仅统计阶段本地调用,不再将样例级工具期望和步数预算错误应用到每个阶段。
- [修复] Multi-Agent 顶层轨迹步数改由阶段快照累计,避免将 orchestrator 阶段数误判为 agent-loop 步数并漏报全局预算超限。
Expand Down
8 changes: 8 additions & 0 deletions docs/data-source-stability.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@

核心原则:先用项目已经接入并验证过的数据源,把失败路径讲清楚;新增外部数据源应放在第二阶段,避免先扩大维护面。

## 基本面报告期与股票范围

AkShare 的业绩预告、快报是按 `date=YYYYMMDD` 查询的全市场表,机构持股按“年份+季度”查询;适配器依次尝试最近两个已结束季度,并在返回前筛选当前股票。表中没有目标股票或缺少代码列时继续尝试前一期,不会用其他股票的首行,也不会退回接口内置的多年以前默认日期。十大股东查询复用现有沪/深/北代码转换,明确传入带市场前缀的股票和报告期。

机构推荐不代表机构持仓变化,普通股东户数也不代表十大股东持仓变化;这些不同含义的数据不会再作为对应字段的备用来源。业绩报表也不再替代业绩预告。未披露、缺数据或上游解析失败时保留局部数据和错误诊断;`partial` 本身不代表全部取数失败。此修复不改变超时预算、普通日 K 数据源优先级、API/报告字段或用户配置,也不保证上游东财返回结构始终可用。

业绩快报摘要只从实际返回的营收、净利润、同比、每股收益和净资产收益率生成,保留零值与负值;公告日期不作为快报内容。业绩预告按明确的披露文本字段提取,不把日期或变动幅度数值当作摘要。只有日期或指标全部缺失时不生成有效摘要,避免缓存及 Agent 输出把元数据误当作业绩信息。

## 一句话答复用户

如果遇到“数据源失败”,通常不是系统只能用一个源,而是免费源被限流、上游接口临时变更、网络抖动或当前市场/标的不支持。DSA 已经内置多数据源 fallback,会按场景自动尝试下一个源;如果你希望更稳定,建议至少配置一个 token 型稳定源:
Expand Down
1 change: 1 addition & 0 deletions docs/desktop-package.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
- Windows 便携/安装模式下,用户配置文件 `.env` 和数据库放在 exe 同级目录;macOS 打包版使用 Electron 用户数据目录保存运行时配置
- 桌面端会自动从本机 `8000-8100` 选择可用端口,并把实际选择的端口同步给内置后端;桌面端不依赖 `.env` 里的 `WEBUI_PORT` 来决定窗口连接地址,避免用户改端口后 Electron 仍等待旧端口导致启动超时
- Desktop backend 默认随 `requirements.txt` 安装并冻结 `futu-api==10.8.6808`;Windows/macOS 构建脚本会在源码环境和 PyInstaller 产物中分别执行 `import futu`,防止发布包只安装但未携带 SDK。
- 筹码分布依赖的 `py_mini_racer` 按构建环境实际安装版本完整收集 Python 模块、原生库和运行数据;不跨版本手工拼接 DLL、ICU 或 snapshot 文件。Windows/macOS 明确要求 `mini-racer>=0.13.2`,避免旧版冻结加载器从 bundle 根目录寻找原生库、与包目录收集布局不一致;Linux 继续沿用 AkShare 原有依赖。Windows/macOS 构建脚本会在源码环境和冻结后的后端中执行 `MiniRacer().eval('1 + 1')`,原生库缺失或版本不匹配会阻断打包。仅成功 `import py_mini_racer` 不足以验收;这一离线检查不代表在线东财接口一定可用。
- 报告“分享”按钮使用 Electron 自带的隐藏 Chromium 窗口渲染本地后端输出的受限 HTML,并保存为 PNG;桌面安装包无需额外携带 `wkhtmltoimage`、`markdown-to-file` 或 Playwright 浏览器。

## 本地开发
Expand Down
15 changes: 13 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,21 @@
import sys

try:
importlib.import_module(_packaged_import_probe)
probe_module = importlib.import_module(_packaged_import_probe)
if _packaged_import_probe == "py_mini_racer":
# Importing the Python wrapper does not load V8 or its data files.
# Exercise the installed runtime to detect missing/mismatched assets.
engine = probe_module.MiniRacer()
try:
if engine.eval("1 + 1") != 2:
raise RuntimeError("MiniRacer JavaScript evaluation failed")
finally:
close = getattr(engine, "close", None)
if callable(close):
close()
except Exception as exc:
print(
f"ERROR: packaged import failed for {_packaged_import_probe}: {exc}",
f"ERROR: packaged runtime probe failed for {_packaged_import_probe}: {exc}",
file=sys.stderr,
)
sys.exit(1)
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ exchange-calendars>=4.13.0 # Trading calendars; 4.5.x is incompatible with pan
# Data source dependencies, ordered by fallback priority
efinance>=0.5.5 # Priority 0: East Money data source https://github.com/Micro-sheep/efinance
akshare>=1.12.0 # Priority 1: East Money crawler data source
# Older mini-racer frozen loaders search the bundle root instead of the package directory.
mini-racer>=0.13.2; platform_system != "Linux" # Desktop V8 runtime; keep Linux's AkShare dependency unchanged
tushare>=1.4.0 # Priority 2: Tushare Pro API
pytdx>=1.72 # Priority 2: Tongdaxin quote servers
baostock>=0.8.0 # Priority 3: Baostock data
Expand Down
6 changes: 5 additions & 1 deletion scripts/build-backend-macos.sh
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ log "Checking Futu SDK availability..."
log "Checking orjson availability..."
"${PYTHON_BIN}" -c "import orjson"

log "Checking MiniRacer JavaScript runtime..."
"${PYTHON_BIN}" -c "from py_mini_racer import MiniRacer; assert MiniRacer().eval('1 + 1') == 2"

if [[ -d "${ROOT_DIR}/dist/backend" ]]; then
rm -rf "${ROOT_DIR}/dist/backend"
fi
Expand Down Expand Up @@ -120,6 +123,7 @@ pushd "${ROOT_DIR}" >/dev/null
cmd=("${PYTHON_BIN}" -m PyInstaller --name stock_analysis --onedir --noconfirm --noconsole --runtime-hook "${SCRIPT_DIR}/pyinstaller_runtime_compat.py" --add-data "static:static" --add-data "strategies:strategies" --add-data "src/assets/share_image:src/assets/share_image" --collect-data litellm --collect-data tiktoken --collect-data akshare)
cmd+=("--collect-all" "src.services.screening")
cmd+=("--collect-all" "futu")
cmd+=("--collect-all" "py_mini_racer")
cmd+=("${hidden_import_args[@]}" "main.py")

echo "Running: ${cmd[*]}"
Expand Down Expand Up @@ -147,7 +151,7 @@ if ! "${packaged_entry}" --help >/tmp/dsa-packaged-help.log 2>&1; then
exit 1
fi

for module in src.services.screening.pipeline futu orjson; do
for module in src.services.screening.pipeline futu orjson py_mini_racer; do
if DSA_PACKAGED_IMPORT_PROBE="${module}" "${packaged_entry}" >/tmp/dsa-packaged-import.log 2>&1; then
cat /tmp/dsa-packaged-import.log
else
Expand Down
10 changes: 8 additions & 2 deletions scripts/build-backend.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ if (-not (Test-PythonCode -Python $pythonBin -Code "import orjson")) {
throw 'orjson is not importable after installing requirements.'
}

Write-Host 'Checking MiniRacer JavaScript runtime...'
if (-not (Test-PythonCode -Python $pythonBin -Code "from py_mini_racer import MiniRacer; assert MiniRacer().eval('1 + 1') == 2")) {
throw 'MiniRacer cannot execute JavaScript in the build environment.'
}

if (Test-Path 'dist\backend') {
Remove-Item -Recurse -Force 'dist\backend'
}
Expand Down Expand Up @@ -139,6 +144,7 @@ $pyInstallerArgs = @(
'--collect-data', 'litellm',
'--collect-data', 'tiktoken',
'--collect-data', 'akshare',
'--collect-all', 'py_mini_racer',
'--collect-all', 'src.services.screening',
'--collect-all', 'futu'
)
Expand All @@ -164,9 +170,9 @@ if (-not (Test-Path $packagedEntry)) {
}
$previousProbe = $env:DSA_PACKAGED_IMPORT_PROBE
try {
foreach ($module in @('src.services.screening.pipeline', 'futu', 'orjson')) {
foreach ($module in @('src.services.screening.pipeline', 'futu', 'orjson', 'py_mini_racer')) {
$env:DSA_PACKAGED_IMPORT_PROBE = $module
$probeProcess = Start-Process -FilePath $packagedEntry -Wait -PassThru
$probeProcess = Start-Process -FilePath $packagedEntry -Wait -PassThru -WindowStyle Hidden
if ($probeProcess.ExitCode -ne 0) {
throw "Packaged backend cannot import $module; probe exited with code $($probeProcess.ExitCode)."
}
Expand Down
4 changes: 2 additions & 2 deletions tests/test_fundamental_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ def test_fundamental_bundle_includes_financial_report_and_dividend_payload(self)
"净利润同比": [9.5],
}
)
forecast_df = pd.DataFrame({"股票代码": ["600519"], "预告": ["预增"]})
quick_df = pd.DataFrame({"股票代码": ["600519"], "快报": ["快报摘要"]})
forecast_df = pd.DataFrame({"股票代码": ["600519"], "业绩变动": ["预增"]})
quick_df = pd.DataFrame({"股票代码": ["600519"], "净利润-净利润": [300.0]})
dividend_df = pd.DataFrame(
{
"股票代码": ["600519", "600519", "600519", "600519"],
Expand Down
Loading
Loading