feat(financial): 实现资产负债表和现金流量表同步接口

- 新增 BalanceQuarterSync 类,封装 balancesheet_vip 接口(157个字段)
- 新增 CashflowQuarterSync 类,封装 cashflow_vip 接口(95个字段)
- 在财务数据调度中心注册资产负债表和现金流量表
- 更新规范文档,标记接口为已实现
This commit is contained in:
2026-03-08 10:57:39 +08:00
parent 0aec87281e
commit eb76cbbd52
5 changed files with 933 additions and 47 deletions

View File

@@ -1,8 +1,8 @@
# 财务数据 API 封装规范
> **文档版本**: v1.0
> **文档版本**: v1.3
> **适用范围**: 所有财务数据 API利润表、资产负债表、现金流量表等
> **更新日期**: 2026-03-07
> **更新日期**: 2026-03-08
---
@@ -94,8 +94,8 @@ class IncomeQuarterSync(QuarterBasedSync):
src/data/api_wrappers/financial_data/
├── __init__.py # 可选:导出公共接口
├── api_income.py # 利润表接口(已实现)
├── api_balance.py # 资产负债表接口(预留
├── api_cashflow.py # 现金流量表接口(预留
├── api_balance.py # 资产负债表接口(已实现
├── api_cashflow.py # 现金流量表接口(已实现
└── api_financial_sync.py # 调度中心(只保留调度逻辑)
```
@@ -107,6 +107,35 @@ src/data/api_wrappers/
└── base_financial_sync.py # QuarterBasedSync本规范核心
```
### 快速开始
已实现的财务数据接口可以直接使用:
```python
# 同步所有财务数据(利润表 + 资产负债表 + 现金流量表)
from src.data.api_wrappers.financial_data.api_financial_sync import sync_financial
sync_financial()
# 只同步利润表
from src.data.api_wrappers.financial_data.api_income import sync_income
sync_income()
# 只同步资产负债表
from src.data.api_wrappers.financial_data.api_balance import sync_balance
sync_balance()
# 只同步现金流量表
from src.data.api_wrappers.financial_data.api_cashflow import sync_cashflow
sync_cashflow()
# 全量同步
sync_cashflow(force_full=True)
# 预览同步
from src.data.api_wrappers.financial_data.api_cashflow import preview_cashflow_sync
preview_cashflow_sync()
```
### 文件内容结构
每个 API 文件必须包含以下部分(按顺序):
@@ -905,60 +934,158 @@ def get_income(period: str, fields: Optional[str] = None) -> pd.DataFrame:
return client.query("income_vip", period=period, fields=fields)
```
### 预留接口示例
### 完整实现示例:资产负债表接口
```python
"""资产负债表数据接口 (VIP 版本) - 预留
"""资产负债表数据接口 (VIP 版本)
使用 Tushare VIP 接口 (balancesheet_vip) 获取资产负债表数据。
按季度同步,一次请求获取一个季度的全部上市公司数据。
使用方式:
from src.data.api_wrappers.financial_data.api_balance import (
BalanceQuarterSync,
sync_balance,
preview_balance_sync
)
# 方式1: 使用类
syncer = BalanceQuarterSync()
syncer.sync_incremental() # 增量同步
syncer.sync_full() # 全量同步
# 方式2: 使用便捷函数
sync_balance() # 增量同步
sync_balance(force_full=True) # 全量同步
"""
from typing import Optional
from typing import Any, override
import pandas as pd
from src.data.client import TushareClient
from src.data.api_wrappers.base_financial_sync import (
QuarterBasedSync,
sync_financial_data,
preview_financial_sync
preview_financial_sync,
)
class BalanceQuarterSync(QuarterBasedSync):
"""资产负债表季度同步实现(预留)。"""
table_name = "financial_balance"
api_name = "balancesheet_vip"
TARGET_REPORT_TYPE = "1"
TABLE_SCHEMA = {
"""资产负债表季度同步实现
使用 balancesheet_vip 接口按季度获取全部上市公司资产负债表数据。
表结构: financial_balance
注意: 不设置主键和唯一索引,支持财务数据多次修正
"""
table_name: str = "financial_balance"
api_name: str = "balancesheet_vip"
# 只同步合并报表
TARGET_REPORT_TYPE: str | None = "1"
# 表结构定义 - 完整的资产负债表字段
TABLE_SCHEMA: dict[str, str] = {
"ts_code": "VARCHAR(16) NOT NULL",
"ann_date": "DATE",
"f_ann_date": "DATE",
"end_date": "DATE NOT NULL",
"report_type": "INTEGER",
# TODO: 补充完整字段定义
"comp_type": "INTEGER",
"end_type": "VARCHAR(10)",
"total_share": "DOUBLE",
"cap_rese": "DOUBLE",
"undistr_porfit": "DOUBLE",
"surplus_rese": "DOUBLE",
"special_rese": "DOUBLE",
"money_cap": "DOUBLE",
"trad_asset": "DOUBLE",
"notes_receiv": "DOUBLE",
"accounts_receiv": "DOUBLE",
# ... 其他150+个字段(完整字段列表见 api_balance.py
}
TABLE_INDEXES = [
# 普通索引(不要创建唯一索引)
TABLE_INDEXES: list[tuple[str, list[str]]] = [
("idx_financial_balance_ts_code", ["ts_code"]),
("idx_financial_balance_end_date", ["end_date"]),
("idx_financial_balance_ts_period", ["ts_code", "end_date", "report_type"]),
]
def __init__(self):
"""初始化资产负债表同步器。"""
super().__init__()
self._fields: str | None = None # 默认返回全部字段
@override
def fetch_single_quarter(self, period: str) -> pd.DataFrame:
"""预留方法,尚未实现。"""
raise NotImplementedError(
"资产负债表同步尚未实现。需要 Tushare 5000 积分调用 balancesheet_vip 接口。"
"""获取单季度的全部上市公司资产负债表数据。
Args:
period: 报告期,季度最后一天日期(如 '20231231'
Returns:
包含该季度全部上市公司资产负债表数据的 DataFrame
"""
params = {"period": period}
if self._fields:
params["fields"] = self._fields
return self.client.query(self.api_name, **params)
# =============================================================================
# 便捷函数
# =============================================================================
def sync_balance(
force_full: bool = False,
dry_run: bool = False,
) -> list[dict[str, Any]]:
"""同步资产负债表数据(便捷函数)。
Args:
force_full: 若为 True强制全量同步
dry_run: 若为 True仅预览不写入
Returns:
同步结果列表
"""
return sync_financial_data(BalanceQuarterSync, force_full, dry_run)
def preview_balance_sync() -> dict[str, Any]:
"""预览资产负债表同步信息。
Returns:
预览信息字典
"""
return preview_financial_sync(BalanceQuarterSync)
def get_balance(period: str, fields: str | None = None) -> pd.DataFrame:
"""获取资产负债表数据(原始接口,单季度)。
Args:
period: 报告期,季度最后一天日期(如 '20231231'
fields: 指定返回字段,默认返回全部字段
Returns:
包含资产负债表数据的 DataFrame
"""
client = TushareClient()
if fields is None:
fields = (
"ts_code,ann_date,f_ann_date,end_date,report_type,comp_type,end_type,"
"total_share,cap_rese,undistr_porfit,surplus_rese,special_rese,"
"money_cap,trad_asset,notes_receiv,accounts_receiv,..."
)
def sync_balance(force_full: bool = False, dry_run: bool = False) -> list:
"""预留函数。"""
raise NotImplementedError("资产负债表同步尚未实现")
def preview_balance_sync() -> dict:
"""预留函数。"""
raise NotImplementedError("资产负债表同步尚未实现")
return client.query("balancesheet_vip", period=period, fields=fields)
```
---
@@ -1149,12 +1276,16 @@ self.storage.flush()
- `src/data/api_wrappers/base_financial_sync.py` - QuarterBasedSync 基类
- `src/data/api_wrappers/financial_data/api_income.py` - 利润表示例实现
- `src/data/api_wrappers/financial_data/api_balance.py` - 资产负债表实现
- `src/data/api_wrappers/financial_data/api_cashflow.py` - 现金流量表实现
- `src/data/api_wrappers/financial_data/api_financial_sync.py` - 调度中心
### 变更历史
| 日期 | 版本 | 变更内容 |
|------|------|----------|
| 2026-03-08 | v1.3 | 现金流量表接口实现:<br>- 完成 `api_cashflow.py` 封装<br>- 添加 95 个现金流量表完整字段<br>- 更新调度中心注册<br>- 更新文档标记现金流为已实现 |
| 2026-03-08 | v1.2 | 资产负债表接口实现:<br>- 完成 `api_balance.py` 封装<br>- 添加 157 个资产负债表完整字段<br>- 更新调度中心注册<br>- 更新文档中的资产负债表示例为完整实现 |
| 2026-03-08 | v1.1 | 完善实际编码细节:<br>- 添加首次同步优化说明<br>- 添加日期格式转换规范<br>- 添加存储层 UPSERT 禁用说明<br>- 添加删除计数处理说明<br>- 扩充常见问题Q7-Q9 |
| 2026-03-07 | v1.0 | 初始版本,规范财务数据 API 封装要求 |