欢迎光临
我们一直在努力

Python实现题材库API调用:获取股票题材数据

一、功能概述

本文介绍如何使用Python调用题材库API,实现股票题材数据的获取。通过简单的HTTP请求,我们可以获取题材库列表以及指定题材下的个股信息,为量化分析和投资研究提供数据支持。

二、技术要点

2.1 核心依赖

  • requests:Python HTTP请求库,用于发送POST请求
  • json:JSON数据处理,用于解析API响应

2.2 API接口说明

接口类型请求参数功能描述
kpl_theme 获取题材库完整列表
kpl_theme_stock theme_id 获取指定题材的个股列表

三、完整代码实现

python

import requests
import json

# API基础配置
BASE_URL = "http://ddnsapi.top:18080/api/v1/request"

def send_request(data: dict) -> str:
"""
发送POST请求到指定API接口

Args:
data: 请求参数字典,包含req_type等关键字段

Returns:
API响应的文本内容

Raises:
requests.exceptions.RequestException: 请求超时或网络异常时抛出
"""
try:
response = requests.post(BASE_URL, data=data, timeout=10)
response.raise_for_status() # 检查HTTP状态码
return response.text
except requests.exceptions.RequestException as e:
print(f"请求异常: {e}")
return ""

def get_theme_list() -> str:
"""获取题材库列表"""
data = {'req_type': 'kpl_theme'}
return send_request(data)

def get_theme_stocks(theme_id: str) -> str:
"""
获取指定题材下的个股列表

Args:
theme_id: 题材ID,用于筛选特定题材的股票

Returns:
包含个股信息的JSON字符串
"""
data = {'req_type': 'kpl_theme_stock', 'theme_id': theme_id}
return send_request(data)

if __name__ == "__main__":
# 获取题材库数据(展示前1000字符)
print("=" * 60)
print("📊 题材库数据:")
print("=" * 60)
theme_data = get_theme_list()
print(f"{theme_data[:1000]}…\\n" if len(theme_data) > 1000 else theme_data)

# 获取指定题材的个股列表(展示前1000字符)
print("\\n" + "=" * 60)
print("📈 题材ID:25 个股列表:")
print("=" * 60)
stock_data = get_theme_stocks('25')
print(f"{stock_data[:1000]}…\\n" if len(stock_data) > 1000 else stock_data)

四、代码解析

4.1 核心函数说明

  • send_request():封装HTTP请求逻辑

    • 统一处理请求超时和异常捕获
    • 使用raise_for_status()检查HTTP错误
  • get_theme_list():获取题材库列表

    • 构造kpl_theme类型请求
    • 返回题材库JSON数据
  • get_theme_stocks():获取个股列表

    • 接收theme_id参数
    • 构造kpl_theme_stock类型请求

  • 🔔 注意:本文提供的API仅供学习参考,请遵守相关平台的使用规范和数据使用条款。

    赞(0)
    未经允许不得转载:171主机测评 » Python实现题材库API调用:获取股票题材数据
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址