概述

爱股数据提供了三种不同的API调用方式,满足不同用户的需求和使用场景。您可以根据自己的技术水平和项目需求选择最适合的调用方式。

  • 新手用户:推荐使用在线调试,无需编程基础
  • Python开发者:推荐使用Python SDK,开发效率最高
  • 其他语言开发者:推荐直接接口调用,灵活性最强

三种调用方式

🌐 在线调试

在网站内直接测试API接口,无需编程基础,适合快速验证和测试。

🐍 Python SDK

官方提供的Python开发包,封装了所有接口,使用简单,开发效率高。

🔗 直接接口调用

直接通过HTTP请求调用API接口,支持所有编程语言,灵活性最强。

方式一:在线调试

在线调试是爱股数据提供的网页版API测试工具,您可以在浏览器中直接测试API接口,无需编写任何代码。

  • 无需编程基础,操作简单
  • 实时查看返回结果
  • 自动生成代码示例
  • 支持参数验证和错误提示

使用步骤

登录账户并获取API密钥
确保您已登录并拥有有效的API密钥
进入在线调试页面
访问 API文档页面 或在线调试工具
选择要测试的接口
从接口列表中选择您需要测试的API接口
填写API密钥和参数
在表单中填入您的API密钥和必要的请求参数
点击发送请求
查看返回结果,系统会自动生成对应的代码示例

示例:获取股票基本信息

1

选择接口

在接口列表中选择"获取股票基本信息"接口

2

填写参数

在表单中填写:

  • API密钥:sk-your-api-key-here
  • 股票代码:sz000001
  • 交易日期:2024-01-15
3

查看结果

系统返回股票的基本信息,包括股票名称、价格、涨跌幅等数据

  • 在线调试会消耗您的API调用次数
  • 请确保API密钥的安全性,不要在公共设备上保存
  • 调试结果仅供参考,实际使用时请根据返回的数据结构进行适配

方式二:Python SDK

Python SDK是爱股数据官方提供的Python开发包,封装了所有API接口,让您可以用最简单的方式调用爱股数据服务。

  • 官方维护,稳定可靠
  • 接口封装完整,使用简单
  • 自动处理认证和错误处理
  • 支持数据缓存和重试机制
  • 详细的文档和示例

安装SDK

# 使用pip安装
pip install agushuju

# 或者从源码安装
pip install git+https://github.com/agukeji/agushuju.git

基本使用

from agushuju

# 初始化客户端
client = agushuju.api("sk-your-api-key-here")

# 获取股票基本信息
stock_info = client.get_stock_basic(stock_code="sz000001")
print(stock_info)

# 获取股票日线数据
daily_data = client.get_daily(stock_code="000001.SZ", start_date="20240101", end_date="20240131")
print(daily_data.head())

详细示例

  • 股票基本信息
  • 日线数据
  • 财务数据
  • 批量查询
from agushuju

# 初始化客户端
client = agushuju.api("sk-your-api-key-here")

# 获取单只股票基本信息
stock_info = client.stock_basic(request={
    "stock_code": "sz000001"  # 查询上市股票
})
from agushuju

client = agushuju.api("sk-your-api-key-here")

# 获取财务数据
financial_data = client.get_fina_indicator(
    stock_code="sz000001",
    start_date="20230101",
    end_date="20231231"
)

# 分析财务指标
for data in financial_data:
    print(f"报告期: {data['end_date']}")
    print(f"营业收入: {data['revenue']:.2f}万元")
    print(f"净利润: {data['n_income']:.2f}万元")
    print(f"ROE: {data['roe']:.2f}%")
    print("-" * 30)
from agushuju
import time

client = agushuju.api("sk-your-api-key-here")

# 批量获取多只股票数据
stock_list = ["sz000001", "sz000002", "sh600000", "sh600036", "sz000858"]
all_data = []

for stock_code in stock_list:
    try:
        # 获取基本信息
        basic_info = client.get_stock_basic(stock_code=stock_code)
        
        # 获取最新日线数据
        daily_data = client.get_daily(
            stock_code=stock_code,
            start_date="20240101",
            end_date="20240131"
        )
        
        if daily_data:
            latest_data = daily_data[0]  # 最新数据
            all_data.append({
                'stock_code': stock_code,
                'name': basic_info['name'],
                'close': latest_data['close'],
                'pct_chg': latest_data['pct_chg'],
                'volume': latest_data['vol']
            })
        
        # 避免请求过于频繁
        time.sleep(0.1)
        
    except Exception as e:
        print(f"获取 {stock_code} 数据失败: {e}")

# 输出结果
for data in all_data:
    print(f"{data['name']}({data['stock_code']}): {data['close']} ({data['pct_chg']:+.2f}%)")

方式三:直接接口调用

直接接口调用是通过HTTP请求直接访问爱股数据API接口,支持所有编程语言,提供最大的灵活性。

  • 支持所有编程语言
  • 完全控制请求和响应
  • 可以自定义错误处理逻辑
  • 适合复杂的业务场景
  • 便于集成到现有系统

接口规范

项目 说明
基础URL https://www.agushuju.com
请求方法 GET / POST
数据格式 JSON
字符编码 UTF-8
认证方式 API Key (Header / 参数)

多语言示例

  • Python
  • JavaScript
  • PHP
  • Java
  • cURL
import requests
import json

# 设置API密钥和基础URL
api_key = "sk-your-api-key-here"
base_url = "https://www.agushuju.com"

# 方法1:使用Authorization Header
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

# 获取股票基本信息
response = requests.get(
    f"{base_url}/api/stock/basic",
    headers=headers,
    params={"stock_code": "sz000001"}
)

if response.status_code == 200:
    data = response.json()
    print(json.dumps(data, indent=2, ensure_ascii=False))
else:
    print(f"请求失败: {response.status_code}")
    print(response.text)

# 方法2:使用X-API-KEY Header
headers = {
    "X-API-KEY": api_key,
    "Content-Type": "application/json"
}

response = requests.get(
    f"{base_url}/api/stock/basic",
    headers=headers,
    params={"stock_code": "sz000001"}
)

# 方法3:使用URL参数
response = requests.get(
    f"{base_url}/api/stock/basic",
    params={
        "token": api_key,
        "stock_code": "sz000001"
    }
)

# POST请求示例
post_data = {
    "stock_code": "sz000001",
    "start_date": "20240101",
    "end_date": "20240131"
}

response = requests.post(
    f"{base_url}/api/stock/daily",
    headers=headers,
    json=post_data
)
// 使用fetch API
const apiKey = "sk-your-api-key-here";
const baseUrl = "https://www.agushuju.com";

// 方法1:使用Authorization Header
async function getStockBasic() {
    try {
        const response = await fetch(`${baseUrl}/api/stock/basic?stock_code=sz000001`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });
        
        if (response.ok) {
            const data = await response.json();
            console.log(data);
        } else {
            console.error('请求失败:', response.status);
        }
    } catch (error) {
        console.error('网络错误:', error);
    }
}

// 方法2:使用X-API-KEY Header
async function getStockDaily() {
    const response = await fetch(`${baseUrl}/api/stock/daily`, {
        method: 'POST',
        headers: {
            'X-API-KEY': apiKey,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            stock_code: "sz000001",
            start_date: "20240101",
            end_date: "20240131"
        })
    });
    
    const data = await response.json();
    return data;
}

// 使用axios
const axios = require('axios');

const client = axios.create({
    baseURL: baseUrl,
    headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
    }
});

client.get('/api/stock/basic', {
    params: { stock_code: "sz000001" }
}).then(response => {
    console.log(response.data);
}).catch(error => {
    console.error('请求失败:', error);
});
 $stockCode,
        'start_date' => $startDate,
        'end_date' => $endDate
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $baseUrl . "/api/stock/daily");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "X-API-KEY: " . $apiKey,
        "Content-Type: application/json"
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

// 使用示例
try {
    $stockInfo = getStockBasic("000001.SZ");
    print_r($stockInfo);
    
    $dailyData = getStockDaily("000001.SZ", "20240101", "20240131");
    print_r($dailyData);
} catch (Exception $e) {
    echo "错误: " . $e->getMessage();
}

// 使用Guzzle HTTP客户端
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => $baseUrl,
    'headers' => [
        'Authorization' => 'Bearer ' . $apiKey,
        'Content-Type' => 'application/json'
    ]
]);

$response = $client->get('/api/stock/basic', [
    'query' => ['stock_code' => 'sz000001']
]);

$data = json_decode($response->getBody(), true);
print_r($data);
?>
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

public class AgushujuClient {
    private static final String API_KEY = "sk-your-api-key-here";
    private static final String BASE_URL = "https://www.agushuju.com";
    private final HttpClient client;
    private final ObjectMapper objectMapper;
    
    public AgushujuClient() {
        this.client = HttpClient.newHttpClient();
        this.objectMapper = new ObjectMapper();
    }
    
    // 获取股票基本信息
    public String getStockBasic(String tsCode) throws IOException, InterruptedException {
        String url = BASE_URL + "/api/stock/basic?stock_code=" + stockCode;
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .GET()
            .build();
        
        HttpResponse response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
        
        if (response.statusCode() == 200) {
            return response.body();
        } else {
            throw new RuntimeException("请求失败: " + response.statusCode());
        }
    }
    
    // 获取股票日线数据
    public String getStockDaily(String tsCode, String startDate, String endDate) 
            throws IOException, InterruptedException {
        String url = BASE_URL + "/api/stock/daily";
        
        // 构建请求体
        String requestBody = String.format(
            "{\"stock_code\":\"%s\",\"start_date\":\"%s\",\"end_date\":\"%s\"}",
            tsCode, startDate, endDate
        );
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(requestBody))
            .build();
        
        HttpResponse response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
        
        return response.body();
    }
    
    // 使用示例
    public static void main(String[] args) {
        try {
            AgushujuClient client = new AgushujuClient();
            
            // 获取股票基本信息
            String stockInfo = client.getStockBasic("000001.SZ");
            System.out.println("股票信息: " + stockInfo);
            
            // 获取日线数据
            String dailyData = client.getStockDaily("000001.SZ", "20240101", "20240131");
            System.out.println("日线数据: " + dailyData);
            
        } catch (Exception e) {
            System.err.println("错误: " + e.getMessage());
        }
    }
}
# 方法1:使用Authorization Header
curl -X GET "https://www.agushuju.com/api/stock/basic?stock_code=sz000001" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json"

# 方法2:使用X-API-KEY Header
curl -X GET "https://www.agushuju.com/api/stock/basic?stock_code=sz000001" \
  -H "X-API-KEY: sk-your-api-key-here" \
  -H "Content-Type: application/json"

# 方法3:使用URL参数
curl -X GET "https://www.agushuju.com/api/stock/basic?token=sk-your-api-key-here&stock_code=sz000001"

# POST请求示例 - 获取日线数据
curl -X POST "https://www.agushuju.com/api/stock/daily" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "stock_code": "sz000001",
    "start_date": "20240101",
    "end_date": "20240131"
  }'

# 获取财务数据
curl -X POST "https://www.agushuju.com/api/stock/fina_indicator" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "stock_code": "sz000001",
    "start_date": "20230101",
    "end_date": "20231231"
  }'

# 批量查询示例
curl -X POST "https://www.agushuju.com/api/stock/batch" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "requests": [
      {
        "endpoint": "/api/stock/basic",
        "params": {"stock_code": "sz000001"}
      },
      {
        "endpoint": "/api/stock/basic", 
        "params": {"stock_code": "sz000002"}
      }
    ]
  }'

响应格式

{
  "code": 0,
  "msg": "success",
  "data": {
    "stock_code": "sz000001",
    "name": "平安银行",
    "close": 12.50,
    "pct_chg": 2.45,
    "vol": 12345678,
    "amount": 154320000.00
  },
  "time": "2024-01-15 15:00:00"
}

错误处理

{
  "code": 400,
  "msg": "参数错误:stock_code不能为空",
  "data": null,
  "time": "2024-01-15 15:00:00"
}
  • 请确保API密钥的安全性,不要在代码中硬编码
  • 注意请求频率限制,避免过于频繁的请求
  • 建议实现重试机制和错误处理
  • 对于大量数据请求,考虑使用分页或批量接口

三种方式对比

特性 在线调试 Python SDK 直接接口调用
使用难度 ⭐ 最简单 ⭐⭐ 简单 ⭐⭐⭐ 中等
开发效率 ⭐⭐ 中等 ⭐⭐⭐ 最高 ⭐⭐ 中等
灵活性 ⭐ 最低 ⭐⭐ 中等 ⭐⭐⭐ 最高
语言支持 无限制 仅Python 所有语言
错误处理 自动 自动 手动
适用场景 测试验证 Python项目 生产环境

选择建议

🌐 选择在线调试

  • 快速测试API接口
  • 验证参数和返回结果
  • 生成代码示例
  • 学习和探索API功能

🐍 选择Python SDK

  • Python项目开发
  • 数据分析和研究
  • 快速原型开发
  • 自动化脚本

🔗 选择直接调用

  • 非Python语言项目
  • 生产环境集成
  • 自定义业务逻辑
  • 高性能要求

常见问题

Q: 如何选择合适的调用方式?

A: 根据您的需求选择:

  • 测试阶段:使用在线调试快速验证
  • Python开发:使用Python SDK提高效率
  • 其他语言:使用直接接口调用
  • 生产环境:建议使用直接接口调用,便于控制

Q: Python SDK和直接调用有什么区别?

A: 主要区别:

  • SDK:封装了接口调用,使用更简单,但只支持Python
  • 直接调用:需要自己处理HTTP请求,但支持所有语言
  • 性能:直接调用通常性能更好,SDK有额外的封装开销
  • 维护:SDK由官方维护,直接调用需要自己处理更新

Q: 如何处理API调用失败?

A: 建议的处理方式:

  • 检查错误码:根据返回的错误码判断失败原因
  • 重试机制:对于网络错误,实现指数退避重试
  • 日志记录:记录详细的错误信息便于调试
  • 降级处理:在关键业务中实现降级方案

Q: 如何提高API调用性能?

A: 性能优化建议:

  • 批量请求:使用批量接口减少请求次数
  • 数据缓存:缓存不经常变化的数据
  • 并发控制:合理控制并发请求数量
  • 连接复用:使用HTTP连接池

Q: 在线调试会消耗API调用次数吗?

A: 是的,在线调试会正常消耗您的API调用次数。建议:

  • 在测试阶段合理使用在线调试
  • 确认参数正确后再进行大量测试
  • 可以联系客服申请测试额度

需要帮助?

如果您在使用过程中遇到问题,可以通过以下方式获取帮助: