对接哥伦比亚股票指数API指南
哥伦比亚作为拉丁美洲重要新兴市场,其股票市场受到越来越多国际投资者的关注。本文将详细介绍如何通过API对接哥伦比亚主要股票指数(如MSCI Colcap),提供实用的技术方案和代码示例。
一、哥伦比亚股票市场概述
哥伦比亚证券市场由哥伦比亚证券交易所(BVC) 运营,核心指数包括MSCI Colcap指数(由20家流动性最强的股票组成)和COLCAP指数。2024年Colcap指数回报率达15.4%,表现优于秘鲁、智利和巴西等拉美市场。 主要交易时段为哥伦比亚时间(COT)周一至周五9:00-16:00(北京时间22:00-次日5:00,夏令时有1小时差异)。哥伦比亚国家ID为16,交易所ID为47。
二、API接入准备工作
1. 获取API密钥
首先从数据服务商(如StockTV)获取API密钥:
- 联系官方获取密钥(格式如:
MY4b781f618e3f43c4b055f25fa61941ad) - 所有请求需携带此密钥参数
2. 基础参数配置
# 关键参数常量
API_KEY = "YOUR_API_KEY" # 替换为实际密钥
BASE_URL = "https://api.stocktv.top"
COUNTRY_ID = 16 # 哥伦比亚国家ID
EXCHANGE_ID = 47 # 哥伦比亚交易所ID
三、核心API接口详解
1. 获取指数实时数据
接口地址:GET /stock/indices 请求参数:
| 参数 | 必选 | 说明 | 示例值 |
|---|---|---|---|
| countryId | 是 | 国家ID(哥伦比亚为16) | 16 |
| key | 是 | API密钥 | YOUR_KEY |
Python示例代码:
import requests
def get_colombia_indices():
"""获取哥伦比亚股票指数实时数据"""
url = f"{BASE_URL}/stock/indices"
params = {
"countryId": COUNTRY_ID,
"key": API_KEY
}
try:
response = requests.get(url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
if data["code"] == 200:
return data["data"]
else:
print(f"API返回错误: {data.get('message', '未知错误')}")
return None
else:
print(f"请求失败,状态码:{response.status_code}")
return None
except Exception as e:
print(f"请求异常: {str(e)}")
return None
# 调用示例
indices = get_colombia_indices()
if indices:
for index in indices:
print(f"{index['name']}({index['symbol']}): {index['last']} {index.get('chgPct', 0)}%")
响应示例:
{
"code": 200,
"data": [
{
"id": 17950,
"name": "MSCI Colcap",
"symbol": "COLCAP",
"last": 1380.90,
"chgPct": 1.5,
"change": 20.35,
"high": 1390.25,
"low": 1350.75,
"prevClose": 1360.55,
"time": 1725008213
}
]
}
2. 获取个股实时行情
接口地址:GET /stock/queryStocks 请求参数:
params = {
"id": "股票ID", # 如PF Bancolombia的ID
"key": API_KEY
}
3. 获取历史K线数据
接口地址:GET /stock/kline 请求参数:
| 参数 | 必选 | 说明 | 示例值 |
|---|---|---|---|
| pid | 是 | 指数或股票ID | 17950(MSCI Colcap) |
| interval | 是 | 时间间隔 | PT15M(15分钟) |
| key | 是 | API密钥 | YOUR_KEY |
支持的时间间隔:
PT5M:5分钟PT15M:15分钟PT1H:1小时P1D:日线
Java示例代码:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;
public class ColombiaIndexAPI {
private static final String API_KEY = "YOUR_API_KEY";
public JSONObject getKLineData(String pid, String interval) {
OkHttpClient client = new OkHttpClient();
String url = String.format("https://api.stocktv.top/stock/kline?pid=%s&interval=%s&key=%s",
pid, interval, API_KEY);
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String responseData = response.body().string();
return new JSONObject(responseData);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
4. WebSocket实时数据推送
对于需要实时行情的情景,建议使用WebSocket接口: JavaScript示例:
class ColombiaStockWebSocket {
constructor(apiKey) {
this.apiKey = apiKey;
this.ws = null;
this.reconnectInterval = 5000;
this.isConnected = false;
}
connect() {
try {
this.ws = new WebSocket(`wss://ws-api.stocktv.top/connect?key=${this.apiKey}`);
this.ws.onopen = () => {
console.log('WebSocket连接已建立');
this.isConnected = true;
// 订阅哥伦比亚指数
this.subscribe(['17950']); // MSCI Colcap ID
};
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
this.handleMessage(data);
};
this.ws.onclose = () => {
console.log('WebSocket连接已关闭');
this.isConnected = false;
this.handleReconnect();
};
this.ws.onerror = (error) => {
console.error('WebSocket错误:', error);
};
} catch (error) {
console.error('连接建立失败:', error);
}
}
subscribe(pids) {
if (this.ws && this.isConnected) {
const subscribeMsg = {
action: "subscribe",
pids: pids
};
this.ws.send(JSON.stringify(subscribeMsg));
}
}
handleMessage(data) {
if (data.pid === "17950") { // MSCI Colcap
console.log(`MSCI Colcap: ${data.last_numeric} ${data.pcp}%`);
// 处理实时数据逻辑
}
}
handleReconnect() {
setTimeout(() => {
console.log('尝试重新连接...');
this.connect();
}, this.reconnectInterval);
}
}
// 使用示例
const wsClient = new ColombiaStockWebSocket('YOUR_API_KEY');
wsClient.connect();
四、哥伦比亚市场特色数据
1. 主要成分股信息
MSCI Colcap指数主要成分股包括:
- PF Bancolombia:权重最大的成分股,受外资重点关注
- Grupo Aval:金融集团,在欧美市场也有表现
- ECOPETROL:国家石油公司,受油价影响大
2. 市场动态关注点
- 外资流向:外国投资者是市场重要参与者,1月份净买入875.96亿比索
- 政治因素:2026年政府换届可能影响市场估值
- 汇率波动:哥伦比亚比索兑美元汇率影响外资收益
五、实战案例:哥伦比亚指数监控系统
import requests
import time
import json
from datetime import datetime
import pytz
class ColombiaIndexMonitor:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.stocktv.top"
self.indices = {
"colcap": {"name": "MSCI Colcap", "id": "17950", "threshold": 2.0}
}
def get_index_data(self, index_id):
"""获取指数详细数据"""
url = f"{self.base_url}/stock/queryStocks"
params = {"id": index_id, "key": self.api_key}
try:
response = requests.get(url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
if data.get("code") == 200 and data.get("data"):
return data["data"][0]
return None
except Exception as e:
print(f"获取指数数据失败: {str(e)}")
return None
def check_alert_conditions(self, index_data):
"""检查预警条件"""
alerts = []
for index_key, index_info in self.indices.items():
if str(index_data["id"]) == index_info["id"]:
change_percent = abs(float(index_data.get("chgPct", 0)))
if change_percent > index_info["threshold"]:
alert = {
"name": index_info["name"],
"current_price": index_data.get("last", 0),
"change_percent": change_percent,
"timestamp": datetime.now().isoformat()
}
alerts.append(alert)
return alerts
def send_alert(self, alert):
"""发送预警通知"""
message = (f"【哥伦比亚指数预警】{alert['name']} "
f涨跌幅{alert['change_percent']}%,"
f"当前价格{alert['current_price']}")
print(f"[ALERT] {message}")
# 可集成邮件、短信等通知方式
def start_monitoring(self, interval=300):
"""启动监控"""
print("哥伦比亚指数监控系统启动...")
while True:
for index_key, index_info in self.indices.items():
data = self.get_index_data(index_info["id"])
if data:
alerts = self.check_alert_conditions(data)
for alert in alerts:
self.send_alert(alert)
time.sleep(1) # 请求间隔
time.sleep(interval)
# 使用示例
if __name__ == "__main__":
monitor = ColombiaIndexMonitor("YOUR_API_KEY")
monitor.start_monitoring(interval=300) # 5分钟检查一次
六、最佳实践与注意事项
1. 频率限制与性能优化
- 请求频率:免费版API通常限制为10次请求/秒
- 缓存机制:对指数信息等不常变化的数据实施本地缓存
- 错误重试:实现指数退避重试策略
import time
import math
def request_with_retry(url, params, max_retries=3):
"""带重试机制的请求函数"""
for i in range(max_retries):
try:
response = requests.get(url, params=params, timeout=10)
if response.status_code == 200:
return response.json()
except Exception as e:
wait_time = math.pow(2, i) # 指数退避
print(f"请求失败,{wait_time}秒后重试: {e}")
time.sleep(wait_time)
return None
2. 时区处理
哥伦比亚使用COT时区(UTC-5),需注意时间转换:
def convert_to_cot(utc_timestamp):
"""将UTC时间戳转换为哥伦比亚时间"""
utc_time = datetime.utcfromtimestamp(utc_timestamp)
cot_timezone = pytz.timezone('America/Bogota')
cot_time = utc_time.replace(tzinfo=pytz.utc).astimezone(cot_timezone)
return cot_time
3. 数据验证与错误处理
def validate_index_data(data):
"""验证指数数据完整性"""
required_fields = ['id', 'name', 'symbol', 'last', 'time']
if not data or not isinstance(data, dict):
return False
for field in required_fields:
if field not in data:
return False
return True
七、总结
通过本文介绍的API接口,您可以快速构建哥伦比亚股票指数监控分析系统。重点包括:
- 获取API密钥并配置基础参数(哥伦比亚国家ID=16)
- 选择合适接口:实时数据用WebSocket,历史数据用REST API
- 关注市场特色:外资流向、政治因素、汇率波动等影响因素
- 实现稳健架构:错误处理、频率控制、数据验证
哥伦比亚股市作为拉美重要市场,为投资者提供了多样化投资机会。通过程序化接入市场数据,可以更加高效地把握这个新兴市场的投资机遇。