Metadata-Version: 2.4
Name: aquery-sdk
Version: 1.1.0
Summary: A-Query Open API Python SDK - A股20年全量数据查询服务
Author: superxu520
License: MIT
Project-URL: Homepage, https://huggingface.co/spaces/superxu520/A-query
Project-URL: Documentation, https://huggingface.co/spaces/superxu520/A-query
Project-URL: Repository, https://huggingface.co/spaces/superxu520/A-query
Project-URL: Issues, https://huggingface.co/spaces/superxu520/A-query/discussions
Keywords: aquery,a-share,stock,finance,tushare,quant
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pandas>=1.3.0
Requires-Dist: requests>=2.25.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: black>=22.0.0; extra == "dev"
Requires-Dist: flake8>=4.0.0; extra == "dev"
Dynamic: license-file

# A-Query Python SDK

A股20年全量数据查询服务 - Python SDK

## 安装

```bash
pip install aquery-sdk
```

或者从源码安装：

```bash
git clone <repository-url>
cd sdk
pip install -e .
```

## 快速开始

```python
from aquery import AQueryClient

# 初始化客户端
client = AQueryClient(token="your_token")

# 查询股票基础信息
df = client.stock_basic(market="主板")
print(df.head())

# 查询多只股票日线
df = client.daily(
    ts_code=["000001.SZ", "000002.SZ"],
    start_date=20240101,
    end_date=20241231,
    fields=["trade_date", "open", "close", "vol", "pe"]
)
print(df)

# 查询某日全市场数据
df = client.daily(
    trade_date=20240320,
    fields=["ts_code", "close", "pe", "net_mf_amount"]
)
print(df.head(10))
```

## 特性

- ✅ **统一接口**: 简洁的Python API，自动转换为DataFrame
- ✅ **多代码查询**: 支持同时查询多只股票
- ✅ **多日期查询**: 支持同时查询多个日期/报告期
- ✅ **自适应路由**: `daily` 方法自动选择最优查询路径
- ✅ **分页支持**: 支持limit和offset分页参数

## 支持的API列表

| 方法名 | 说明 | 多代码支持 | 多日期支持 |
|---------|------|------------|------------|
| `daily()` | 日线行情（自适应路由） | ✅ | ✅ |
| `stock_basic()` | 股票基础信息 | ✅ | - |
| `trade_cal()` | 交易日历 | - | ✅ |
| `company_info()` | 公司信息 | ✅ | - |
| `industry_sw()` | 申万行业映射 | ✅ | - |
| `industry_sw_class()` | 申万行业分类 | - | - |
| `fina_indicator()` | 财务指标 | ✅ | ✅ |
| `fina_income()` | 利润表 | ✅ | ✅ |
| `fina_balancesheet()` | 资产负债表 | ✅ | ✅ |
| `fina_cashflow()` | 现金流量表 | ✅ | ✅ |
| `fina_dividend()` | 分红送股 | ✅ | ✅ |

## 详细用法

### 初始化

```python
from aquery import AQueryClient

# 方式1: 直接传入token
client = AQueryClient(token="your_token")

# 方式2: 使用环境变量（推荐）
# export AQUERY_TOKEN=your_token
client = AQueryClient()
```

### 通用查询接口

```python
# 使用query方法进行任意接口查询
df = client.query(
    api_name="daily",
    params={
        "ts_code": ["000001.SZ", "000002.SZ"],
        "start_date": 20240101,
        "end_date": 20241231
    },
    fields=["trade_date", "close", "vol"],
    limit=1000,
    offset=0
)
```

### 日线行情 (daily)

**自适应路由说明**

`daily` 方法会根据您的入参自动选择最优的数据集进行查询：

| 您的入参 | 自动路由到 | 原因 |
|----------|------------|------|
| `ts_code` + `start_date`/`end_date` | A_by_code | 避免扫描多个日期文件，速度最快 |
| `trade_date` | A_by_date | 单日文件更小，查询更快 |
| 无参数 | A_by_date | 默认返回最新日期数据 |

**示例**

```python
# 查询单只股票历史数据
df = client.daily(
    ts_code="000001.SZ",
    start_date=20240101,
    end_date=20241231
)

# 查询多只股票
df = client.daily(
    ts_code=["000001.SZ", "000002.SZ", "600000.SH"],
    start_date=20240101,
    end_date=20240131
)

# 查询某日全市场数据
df = client.daily(trade_date=20240320)

# 查询多个日期
df = client.daily(
    ts_code="000001.SZ",
    trade_date=[20240320, 20240321, 20240322]
)

# 查询特定字段
df = client.daily(
    ts_code="000001.SZ",
    start_date=20240101,
    fields=["trade_date", "open", "high", "low", "close", "vol", "pe"]
)
```

### 财务数据查询

```python
# 查询单只股票财务指标
df = client.fina_indicator(
    ts_code="000001.SZ",
    end_date=20241231
)

# 查询多只股票多个报告期
df = client.fina_indicator(
    ts_code=["000001.SZ", "600000.SH"],
    end_date=[20240331, 20240630, 20240930]
)

# 查询利润表
df = client.fina_income(
    ts_code="000001.SZ",
    start_date=20240101,
    end_date=20241231
)

# 查询资产负债表
df = client.fina_balancesheet(
    ts_code="000001.SZ",
    end_date=20241231
)

# 查询现金流量表
df = client.fina_cashflow(
    ts_code="000001.SZ",
    end_date=20241231
)

# 查询分红送股
df = client.fina_dividend(ts_code="000001.SZ")
```

### 股票基础信息

```python
# 查询所有股票
df = client.stock_basic()

# 查询特定市场
df = client.stock_basic(market="主板")

# 查询多只股票详细信息
df = client.stock_basic(ts_code=["000001.SZ", "000002.SZ"])
```

### 公司信息

```python
# 查询单个公司详细信息
df = client.company_info(ts_code="000001.SZ")

# 查询多个公司
df = client.company_info(ts_code=["000001.SZ", "000002.SZ"])
```

### 行业分类

```python
# 查询申万行业映射
df = client.industry_sw(ts_code="000001.SZ")

# 查询特定级别行业
df = client.industry_sw_class(level="L1")
```

### 交易日历

```python
# 查询日历范围
df = client.trade_cal(
    start_date=20240101,
    end_date=20241231
)

# 查询特定日期是否交易
df = client.trade_cal(trade_date=[20240320, 20240321])

# 只查询交易日
df = client.trade_cal(
    start_date=20240101,
    end_date=20241231,
    is_open=1
)
```

### 获取API信息

```python
# 获取所有支持的API列表
apis = client.list_apis()
print(apis)

# 获取指定API的字段列表
fields = client.get_fields("daily")
print(fields)
```

## 响应格式

所有查询方法都返回 `pandas.DataFrame`，并附加以下元数据：

```python
df = client.daily(ts_code="000001.SZ", trade_date=20240320)

# 查看元数据
print(df.attrs["count"])      # 返回数据条数
print(df.attrs["has_more"])   # 是否有更多数据
print(df.attrs["request_id"]) # 请求ID（用于追踪）
```

## 错误处理

```python
from aquery import AQueryClient, AQueryError

client = AQueryClient(token="your_token")

try:
    df = client.daily(ts_code="000001.SZ", trade_date=20240320)
except AQueryError as e:
    print(f"查询失败: {e}")
except Exception as e:
    print(f"未知错误: {e}")
```

## 完整示例

### 示例1: 条件选股

```python
# 查询某日全市场数据，筛选PE<20且净流入>1亿的股票
df = client.daily(
    trade_date=20240320,
    fields=["ts_code", "close", "pe", "net_mf_amount", "total_mv"]
)

# 在DataFrame中过滤
selected = df[(df["pe"] < 20) & (df["net_mf_amount"] > 1e8)]
print(selected[["ts_code", "close", "pe", "net_mf_amount"]])
```

### 示例2: 获取多只股票历史数据

```python
# 定义股票池
stocks = ["000001.SZ", "000002.SZ", "600000.SH", "600519.SH"]

# 一次查询所有股票的历史数据
df = client.daily(
    ts_code=stocks,
    start_date=20240101,
    end_date=20241231,
    fields=["ts_code", "trade_date", "close", "vol"]
)

# 按股票代码分组分析
for code, group in df.groupby("ts_code"):
    print(f"\n{code}:")
    print(f"  年初价格: {group.iloc[0]['close']}")
    print(f"  年末价格: {group.iloc[-1]['close']}")
    print(f"  年润率: {(group.iloc[-1]['close'] / group.iloc[0]['close'] - 1) * 100:.2f}%")
```

### 示例3: 财务数据分析

```python
# 查询多只股票的财务指标
df = client.fina_indicator(
    ts_code=["000001.SZ", "600000.SH"],
    end_date=[20240331, 20240630, 20240930, 20241231],
    fields=["ts_code", "end_date", "roe", "eps", "grossprofit_margin"]
)

# 查看ROE趋势
pivot_df = df.pivot(index="end_date", columns="ts_code", values="roe")
print(pivot_df)
```

### 示例4: 分页查询大量数据

```python
all_data = []
offset = 0
limit = 10000

while True:
    df = client.daily(
        trade_date=20240320,
        fields=["ts_code", "close", "pe"],
        limit=limit,
        offset=offset
    )
    all_data.append(df)
    
    if not df.attrs["has_more"]:
        break
    
    offset += limit
    print(f"已获取 {offset} 条数据...")

# 合并所有数据
import pandas as pd
full_df = pd.concat(all_data, ignore_index=True)
print(f"总共 {len(full_df)} 条数据")
```

## API参考

### AQueryClient

#### 初始化参数

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| token | str | None | API认证Token，优先使用环境变量AQUERY_TOKEN |

#### 通用方法

**query(api_name, params, fields, limit, offset, order_by)**

**便捷方法**

| 方法 | 说明 | 主要参数 |
|------|------|----------|
| daily() | 日线行情 | ts_code, trade_date, start_date, end_date |
| stock_basic() | 股票基础信息 | ts_code, market, exchange |
| trade_cal() | 交易日历 | start_date, end_date, trade_date, is_open |
| company_info() | 公司信息 | ts_code |
| industry_sw() | 申万行业映射 | ts_code, industry_level |
| industry_sw_class() | 申万行业分类 | level |
| fina_indicator() | 财务指标 | ts_code, end_date, ann_date |
| fina_income() | 利润表 | ts_code, end_date, ann_date |
| fina_balancesheet() | 资产负债表 | ts_code, end_date, ann_date |
| fina_cashflow() | 现金流量表 | ts_code, end_date, ann_date |
| fina_dividend() | 分红送股 | ts_code, end_date |
| list_apis() | 获取API列表 | - |
| get_fields() | 获取字段列表 | api_name |

## 版本历史

### v1.1.0 (2026-03-21)
- ✅ 新增多代码查询支持（ts_code支持传入列表）
- ✅ 新增多日期查询支持（trade_date/end_date支持传入列表）
- ✅ 移除已废弃的daily_history和daily_all方法
- ✅ 新增company_info, fina_income, fina_balancesheet, fina_cashflow, fina_dividend方法
- ✅ 新增分页参数支持(limit, offset)
- ✅ 新增get_fields方法

### v1.0.0 (2026-03-01)
- ✅ 首个正式版本
- ✅ 支持基本查询接口
- ✅ 自动DataFrame转换

## 许可证

MIT License

## 联系方式

- **数据集**: https://huggingface.co/datasets/superxu520/
- **问题反馈**: 请提交GitHub Issue
