对接【股票】IPO新股日历API完全指南
本文详细介绍了如何通过API接口获取全球主要市场的IPO新股日历数据,包括接口调用方法、参数说明、返回数据解析,以及完整的代码实现示例。
一、接口概述
IPO新股日历接口提供了全球主要证券交易所的新股上市信息,包括即将上市和已上市的新股数据。通过该接口,开发者可以获取新股的详细信息,如公司名称、上市时间、发行价格、发行市值等关键数据。
接口基本信息
- 接口地址:
GET /stock/getIpo - 请求方式: GET
- 数据格式: JSON
- 认证方式: API Key
二、接口调用详解
2.1 请求参数
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| key | 是 | string | API访问密钥 |
| countryId | 否 | int | 国家ID,例如14代表印度 |
| pageSize | 否 | int | 每页显示数量,默认值根据API设定 |
| page | 否 | int | 页码,默认值为1 |
2.2 请求示例
基本请求:
GET https://api.stocktv.top/stock/getIpo?key=您的API_KEY
按国家筛选:
GET https://api.stocktv.top/stock/getIpo?key=您的API_KEY&countryId=14
分页请求:
GET https://api.stocktv.top/stock/getIpo?key=您的API_KEY&countryId=14&pageSize=20&page=1
三、返回数据解析
3.1 成功响应示例
{
"code": 200,
"message": "操作成功",
"data": [
{
"id": 19,
"ipoListing": 1724112000,
"country": "India",
"company": "Saraswati Saree Depot Ltd(SARW)",
"exchange": "NSE",
"ipoValue": "1.6B",
"ipoPrice": "160.00",
"last": "158.23",
"symbol": "SARW",
"url": "/equities/saraswati-saree-depot",
"date": "2024-08-20"
},
{
"id": 20,
"ipoListing": 1724112000,
"country": "India",
"company": "Saraswati Saree Depo t Ltd(SARW)",
"exchange": "BSE",
"ipoValue": "1.6B",
"ipoPrice": "160.00",
"last": "158.25",
"symbol": "SARW",
"url": "/equities/saraswati-saree-depot?cid=1218992",
"date": "2024-08-20"
}
]
}
3.2 响应字段说明
| 字段名 | 类型 | 说明 |
|---|---|---|
| id | int | 新股唯一标识 |
| ipoListing | int | 上市时间戳(秒) |
| country | string | 所属国家 |
| company | string | 公司名称及股票代码 |
| exchange | string | 交易所代码(NSE、BSE等) |
| ipoValue | string | 发行市值 |
| ipoPrice | string | 发行价格 |
| last | string | 最新价格 |
| symbol | string | 股票代码 |
| url | string | 详情页链接 |
| date | string | 上市日期(YYYY-MM-DD) |
四、代码实现示例
4.1 Python实现
import requests
import json
from datetime import datetime
class IPODataAPI:
def __init__(self, api_key):
self.base_url = "https://api.stocktv.top"
self.api_key = api_key
self.headers = {
'Content-Type': 'application/json'
}
def get_ipo_data(self, country_id=None, page_size=10, page=1):
"""
获取IPO新股日历数据
Args:
country_id (int, optional): 国家ID. Defaults to None.
page_size (int, optional): 每页数量. Defaults to 10.
page (int, optional): 页码. Defaults to 1.
Returns:
dict: IPO数据
"""
params = {
'key': self.api_key,
'pageSize': page_size,
'page': page
}
if country_id:
params['countryId'] = country_id
try:
response = requests.get(
f"{self.base_url}/stock/getIpo",
params=params,
headers=self.headers,
timeout=30
)
if response.status_code == 200:
data = response.json()
if data['code'] == 200:
return data['data']
else:
print(f"API返回错误: {data['message']}")
return None
else:
print(f"请求失败,状态码: {response.status_code}")
return None
except requests.exceptions.RequestException as e:
print(f"网络请求异常: {e}")
return None
except json.JSONDecodeError as e:
print(f"JSON解析错误: {e}")
return None
def format_ipo_data(self, ipo_data):
"""
格式化IPO数据为更易读的格式
Args:
ipo_data (list): IPO数据列表
Returns:
list: 格式化后的数据
"""
formatted_data = []
for item in ipo_data:
# 转换时间戳为可读格式
listing_date = datetime.fromtimestamp(item['ipoListing']).strftime('%Y-%m-%d %H:%M:%S')
formatted_item = {
'ID': item['id'],
'公司名称': item['company'],
'股票代码': item['symbol'],
'交易所': item['exchange'],
'国家': item['country'],
'发行价格': item['ipoPrice'],
'发行市值': item['ipoValue'],
'最新价格': item.get('last', 'N/A'),
'上市时间': listing_date,
'详情链接': f"{self.base_url}{item['url']}"
}
formatted_data.append(formatted_item)
return formatted_data
# 使用示例
if __name__ == "__main__":
# 初始化API(请替换为您的实际API密钥)
api = IPODataAPI("您的API_KEY")
# 获取印度市场的IPO数据
ipo_data = api.get_ipo_data(country_id=14, page_size=10, page=1)
if ipo_data:
formatted_data = api.format_ipo_data(ipo_data)
# 打印结果
print("印度市场IPO新股日历:")
print("=" * 80)
for item in formatted_data:
print(f"公司: {item['公司名称']}")
print(f"代码: {item['股票代码']} | 交易所: {item['交易所']}")
print(f"发行价: {item['发行价格']} | 市值: {item['发行市值']}")
print(f"上市时间: {item['上市时间']}")
print(f"详情: {item['详情链接']}")
print("-" * 80)
4.2 JavaScript实现
// IPO数据获取类
class IPODataFetcher {
constructor(apiKey) {
this.baseUrl = 'https://api.stocktv.top';
this.apiKey = apiKey;
}
/**
* 获取IPO数据
* @param {number} countryId - 国家ID
* @param {number} pageSize - 每页数量
* @param {number} page - 页码
* @returns {Promise<Array>} IPO数据数组
*/
async fetchIPOData(countryId = null, pageSize = 10, page = 1) {
const params = new URLSearchParams({
key: this.apiKey,
pageSize: pageSize.toString(),
page: page.toString()
});
if (countryId) {
params.append('countryId', countryId.toString());
}
try {
const response = await fetch(`${this.baseUrl}/stock/getIpo?${params}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
const data = await response.json();
if (data.code === 200) {
return data.data;
} else {
console.error('API返回错误:', data.message);
return [];
}
} catch (error) {
console.error('获取IPO数据失败:', error);
return [];
}
}
/**
* 格式化IPO数据
* @param {Array} ipoData - IPO数据数组
* @returns {Array} 格式化后的数据
*/
formatIPOData(ipoData) {
return ipoData.map(item => {
const listingDate = new Date(item.ipoListing * 1000).toLocaleString();
return {
id: item.id,
company: item.company,
symbol: item.symbol,
exchange: item.exchange,
country: item.country,
ipoPrice: item.ipoPrice,
ipoValue: item.ipoValue,
lastPrice: item.last || 'N/A',
listingDate: listingDate,
detailUrl: `${this.baseUrl}${item.url}`
};
});
}
/**
* 在页面中显示IPO数据
* @param {Array} ipoData - IPO数据数组
* @param {string} containerId - 容器元素ID
*/
displayIPOData(ipoData, containerId) {
const container = document.getElementById(containerId);
if (!container) return;
const formattedData = this.formatIPOData(ipoData);
let html = `
<div class="ipo-header">
<h2>IPO新股日历</h2>
<div class="summary">共 ${formattedData.length} 只新股</div>
</div>
`;
formattedData.forEach(item => {
html += `
<div class="ipo-item">
<div class="ipo-company">
<h3>${item.company}</h3>
<span class="ipo-symbol">${item.symbol}</span>
</div>
<div class="ipo-details">
<div class="detail-row">
<span class="label">交易所:</span>
<span class="value">${item.exchange}</span>
</div>
<div class="detail-row">
<span class="label">发行价:</span>
<span class="value">${item.ipoPrice}</span>
</div>
<div class="detail-row">
<span class="label">市值:</span>
<span class="value">${item.ipoValue}</span>
</div>
<div class="detail-row">
<span class="label">上市时间:</span>
<span class="value">${item.listingDate}</span>
</div>
</div>
<div class="ipo-actions">
<a href="${item.detailUrl}" target="_blank" class="detail-link">查看详情</a>
</div>
</div>
`;
});
container.innerHTML = html;
}
}
// 使用示例
document.addEventListener('DOMContentLoaded', async function() {
const ipoFetcher = new IPODataFetcher('您的API_KEY');
// 获取印度市场IPO数据
const ipoData = await ipoFetcher.fetchIPOData(14, 10, 1);
// 在页面中显示
if (ipoData.length > 0) {
ipoFetcher.displayIPOData(ipoData, 'ipo-container');
}
});
4.3 对应的HTML结构
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IPO新股日历</title>
<style>
.ipo-container {
max-width: 1000px;
margin: 0 auto;
padding: 20px;
font-family: Arial, sans-serif;
}
.ipo-header {
text-align: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 2px solid #eee;
}
.ipo-header h2 {
color: #333;
margin-bottom: 10px;
}
.summary {
color: #666;
font-size: 14px;
}
.ipo-item {
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
background: #fff;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.ipo-company {
margin-bottom: 15px;
}
.ipo-company h3 {
margin: 0 0 5px 0;
color: #1a73e8;
}
.ipo-symbol {
background: #f1f8ff;
color: #0366d6;
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
font-weight: bold;
}
.ipo-details {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
margin-bottom: 15px;
}
.detail-row {
display: flex;
justify-content: space-between;
padding: 5px 0;
}
.label {
font-weight: bold;
color: #555;
}
.value {
color: #333;
}
.ipo-actions {
text-align: right;
}
.detail-link {
display: inline-block;
padding: 8px 16px;
background: #1a73e8;
color: white;
text-decoration: none;
border-radius: 4px;
font-size: 14px;
transition: background 0.3s;
}
.detail-link:hover {
background: #1557b0;
}
@media (max-width: 768px) {
.ipo-details {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="ipo-container" id="ipo-container">
<div class="loading">正在加载IPO数据...</div>
</div>
<script src="ipo-data.js"></script>
</body>
</html>
五、高级功能实现
5.1 实时IPO监控系统
import time
import schedule
from datetime import datetime, timedelta
class IPOMonitor:
def __init__(self, api_key, check_interval=3600): # 默认每小时检查一次
self.api = IPODataAPI(api_key)
self.check_interval = check_interval
self.last_check_time = None
self.previous_ipos = set()
def check_new_ipos(self, country_id=None):
"""检查新上市的IPO"""
current_time = datetime.now()
print(f"[{current_time.strftime('%Y-%m-%d %H:%M:%S')}] 检查IPO数据...")
# 获取最近3天的IPO数据
ipo_data = self.api.get_ipo_data(country_id=country_id, page_size=50, page=1)
if not ipo_data:
print("未获取到IPO数据")
return
current_ipos = {ipo['id'] for ipo in ipo_data}
# 找出新上市的IPO
new_ipos = current_ipos - self.previous_ipos
if new_ipos:
new_ipo_list = [ipo for ipo in ipo_data if ipo['id'] in new_ipos]
self.notify_new_ipos(new_ipo_list)
self.previous_ipos = current_ipos
self.last_check_time = current_time
def notify_new_ipos(self, new_ipos):
"""通知新IPO上市"""
print(f"发现 {len(new_ipos)} 只新IPO:")
for ipo in new_ipos:
listing_time = datetime.fromtimestamp(ipo['ipoListing'])
print(f" - {ipo['company']} ({ipo['symbol']})")
print(f" 交易所: {ipo['exchange']}")
print(f" 发行价: {ipo['ipoPrice']}")
print(f" 上市时间: {listing_time.strftime('%Y-%m-%d %H:%M:%S')}")
print()
def start_monitoring(self, country_id=None):
"""开始监控"""
print("启动IPO监控系统...")
print(f"检查间隔: {self.check_interval}秒")
# 立即执行一次检查
self.check_new_ipos(country_id)
# 设置定时任务
schedule.every(self.check_interval).seconds.do(
self.check_new_ipos, country_id=country_id
)
try:
while True:
schedule.run_pending()
time.sleep(1)
except KeyboardInterrupt:
print("监控已停止")
# 使用示例
if __name__ == "__main__":
monitor = IPOMonitor("您的API_KEY", check_interval=1800) # 每30分钟检查一次
monitor.start_monitoring(country_id=14) # 监控印度市场
5.2 IPO数据分析和可视化
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
class IPOAnalyzer:
def __init__(self, api_key):
self.api = IPODataAPI(api_key)
def analyze_ipo_trends(self, country_id=None, days=30):
"""分析IPO趋势"""
ipo_data = self.api.get_ipo_data(country_id=country_id, page_size=100, page=1)
if not ipo_data:
print("未获取到IPO数据")
return
# 转换为DataFrame
df = pd.DataFrame(ipo_data)
# 转换时间戳为日期
df['listing_date'] = pd.to_datetime(df['ipoListing'], unit='s')
df['ipoValue_num'] = df['ipoValue'].str.replace('B', '').str.replace('M', '').astype(float)
df['ipoValue_unit'] = df['ipoValue'].str.extract('([BM])')
# 转换为统一单位(百万)
df['ipo_value_millions'] = df.apply(
lambda x: x['ipoValue_num'] * 1000 if x['ipoValue_unit'] == 'B' else x['ipoValue_num'],
axis=1
)
return df
def plot_ipo_trends(self, df, country_name):
"""绘制IPO趋势图"""
plt.figure(figsize=(12, 8))
# 按日期分组统计
daily_ipos = df.groupby('listing_date').agg({
'id': 'count',
'ipo_value_millions': 'sum'
}).reset_index()
# 创建子图
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
# 绘制IPO数量趋势
ax1.plot(daily_ipos['listing_date'], daily_ipos['id'], marker='o', linewidth=2)
ax1.set_title(f'{country_name}市场IPO数量趋势')
ax1.set_xlabel('日期')
ax1.set_ylabel('IPO数量')
ax1.grid(True, alpha=0.3)
# 绘制IPO市值趋势
ax2.bar(daily_ipos['listing_date'], daily_ipos['ipo_value_millions'], alpha=0.7)
ax2.set_title(f'{country_name}市场IPO市值趋势')
ax2.set_xlabel('日期')
ax2.set_ylabel('总市值(百万)')
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(f'ipo_trends_{country_name}.png', dpi=300, bbox_inches='tight')
plt.show()
return daily_ipos
# 使用示例
if __name__ == "__main__":
analyzer = IPOAnalyzer("您的API_KEY")
# 分析印度市场IPO趋势
df = analyzer.analyze_ipo_trends(country_id=14)
if df is not None:
trends = analyzer.plot_ipo_trends(df, "印度")
print("IPO分析完成,图表已保存")
六、注意事项和最佳实践
6.1 API使用注意事项
- 频率限制: 遵守API的调用频率限制,避免频繁请求
- 错误处理: 完善错误处理机制,处理网络异常和API限制
- 数据缓存: 对不经常变化的数据实施缓存策略,减少API调用
- 密钥安全: 不要在前端代码中硬编码API密钥,建议通过后端代理调用
6.2 数据更新策略
def get_ipo_data_with_cache(api_key, country_id=None, cache_time=3600):
"""
带缓存的IPO数据获取函数
Args:
api_key: API密钥
country_id: 国家ID
cache_time: 缓存时间(秒)
Returns:
IPO数据
"""
cache_key = f"ipo_data_{country_id}"
# 检查缓存是否存在且未过期
if cache.exists(cache_key):
cached_data = cache.get(cache_key)
if time.time() - cached_data['timestamp'] < cache_time:
return cached_data['data']
# 缓存不存在或已过期,从API获取新数据
api = IPODataAPI(api_key)
new_data = api.get_ipo_data(country_id)
if new_data:
# 更新缓存
cache.set(cache_key, {
'data': new_data,
'timestamp': time.time()
})
return new_data
6.3 性能优化建议
- 批量处理: 尽量减少API调用次数,使用合适的pageSize参数
- 异步处理: 对于大量数据请求,使用异步方式提高效率
- 数据压缩: 如果传输数据量大,考虑使用压缩格式
- 连接池: 使用HTTP连接池减少连接建立开销
七、总结
通过本文介绍的IPO新股日历API,开发者可以轻松获取全球主要市场的IPO信息,构建功能丰富的新股监控和分析系统。该接口提供了完整的新股数据,包括公司信息、发行详情、上市时间等关键数据。
在实际应用中,建议:
- 合理使用缓存机制减少API调用
- 实现错误重试机制提高稳定性
- 添加监控告警功能及时获取新股信息
- 结合其他API接口构建完整的金融数据平台
IPO数据对于投资者、金融机构和研究人员都具有重要价值,通过API接口获取这些数据可以为投资决策和市场研究提供有力支持。
提示:本文示例代码仅供参考,实际使用时请替换为有效的API密钥,并遵守API提供商的使用条款。
1423

被折叠的 条评论
为什么被折叠?



