调用接口获取新加坡股票数据:技术实现指南
概述
本文将介绍如何通过API接口获取新加坡股票市场的实时数据、历史行情和相关信息。新加坡作为亚洲重要的金融中心之一,其股票市场数据对于投资者和开发者具有重要价值。下面将详细讲解如何使用RESTful API获取这些数据。
接口基础信息
所有API请求均基于HTTPS协议,基本URL为:https://api.stocktv.top
注意:使用前需要获取有效的API密钥(key),所有请求都需要包含此参数。
核心接口详解
1. 获取新加坡股票列表
接口地址:GET /stock/stocks
请求参数:
countryId: 国家ID(新加坡对应的ID需要从文档中确认)pageSize: 每页数量,默认10page: 页码,默认1key: API密钥
示例代码(Python):
import requests
import json
def get_singapore_stocks(page_size=50, page=1):
url = "https://api.stocktv.top/stock/stocks"
params = {
"countryId": 65, # 假设新加坡的countryId为65,实际需要确认
"pageSize": page_size,
"page": page,
"key": "YOUR_API_KEY_HERE"
}
try:
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
if data["code"] == 200:
return data["data"]["records"]
else:
print(f"Error: {data['message']}")
return None
except Exception as e:
print(f"Request failed: {str(e)}")
return None
# 使用示例
stocks = get_singapore_stocks(page_size=10, page=1)
if stocks:
for stock in stocks:
print(f"{stock['symbol']}: {stock['name']} - ${stock['last']}")
响应数据结构:
id: 股票唯一标识symbol: 股票代码name: 公司名称last: 最新价格chg: 涨跌额chgPct: 涨跌幅百分比high: 当日最高价low: 当日最低价volume: 成交量open: 是否在交易中
2. 获取新加坡指数数据
接口地址:GET /stock/indices
请求参数:
countryId: 国家IDkey: API密钥
def get_singapore_indices():
url = "https://api.stocktv.top/stock/indices"
params = {
"countryId": 65, # 新加坡国家ID
"key": "YOUR_API_KEY_HERE"
}
response = requests.get(url, params=params)
data = response.json()
if data["code"] == 200:
return data["data"]
else:
print(f"Error: {data['message']}")
return None
# 使用示例
indices = get_singapore_indices()
if indices:
for index in indices:
print(f"{index['name']} ({index['symbol']}): {index['last']}")
3. 获取历史K线数据
接口地址:GET /stock/kline
请求参数:
pid: 股票产品IDinterval: 时间间隔(PT5M, PT15M, PT1H, P1D, P1W, P1M)key: API密钥
def get_stock_kline(pid, interval="P1D"):
url = "https://api.stocktv.top/stock/kline"
params = {
"pid": pid,
"interval": interval,
"key": "YOUR_API_KEY_HERE"
}
response = requests.get(url, params=params)
data = response.json()
if data["code"] == 200:
return data["data"]
else:
print(f"Error: {data['message']}")
return None
# 使用示例
kline_data = get_stock_kline(7310, "P1D") # 日线数据
if kline_data:
for item in kline_data:
print(f"Time: {item['time']}, Open: {item['open']}, Close: {item['close']}")
4. 查询特定股票信息
接口地址:GET /stock/queryStocks
请求参数:
id: 股票PID(可选)name: 股票名称(可选)symbol: 股票代码(可选)key: API密钥
def query_stock_by_symbol(symbol):
url = "https://api.stocktv.top/stock/queryStocks"
params = {
"symbol": symbol,
"key": "YOUR_API_KEY_HERE"
}
response = requests.get(url, params=params)
data = response.json()
if data["code"] == 200:
return data["data"]
else:
print(f"Error: {data['message']}")
return None
# 使用示例
stock_info = query_stock_by_symbol("DBS") # 星展银行
if stock_info:
print(json.dumps(stock_info, indent=2))
数据处理与存储建议
1. 数据缓存策略
由于股票数据更新频繁但某些数据变化不大,建议实现缓存机制:
import time
from functools import lru_cache
class SingaporeStockAPI:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.stocktv.top"
@lru_cache(maxsize=100)
def get_stock_info_cached(self, symbol, cache_time=300):
"""带缓存的股票信息查询"""
current_time = time.time()
# 检查缓存逻辑 here
return self.query_stock_by_symbol(symbol)
2. 错误处理与重试机制
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def create_session_with_retries():
session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=0.5,
status_forcelist=[429, 500, 502, 503, 504],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)
return session
实际应用场景
1. 实时监控系统
class StockMonitor:
def __init__(self, api_key, watch_list):
self.api_key = api_key
self.watch_list = watch_list
def monitor_stocks(self):
while True:
for symbol in self.watch_list:
stock_data = query_stock_by_symbol(symbol)
if stock_data and self._check_alert_conditions(stock_data):
self._send_alert(stock_data)
time.sleep(60) # 每分钟检查一次
2. 数据分析和可视化
import pandas as pd
import matplotlib.pyplot as plt
def analyze_stock_trend(pid, days=30):
kline_data = get_stock_kline(pid, "P1D")
if not kline_data:
return
df = pd.DataFrame(kline_data)
df['time'] = pd.to_datetime(df['time'], unit='ms')
df.set_index('time', inplace=True)
plt.figure(figsize=(12, 6))
plt.plot(df.index, df['close'])
plt.title('Stock Price Trend')
plt.xlabel('Date')
plt.ylabel('Price')
plt.grid(True)
plt.show()
注意事项
- API限制:注意查看API的请求频率限制,避免过度请求
- 错误处理:妥善处理网络错误和API返回的错误信息
- 数据准确性:重要决策前应验证数据的准确性和时效性
- 密钥安全:妥善保管API密钥,不要在前端代码中暴露
总结
通过本文介绍的API接口,开发者可以方便地获取新加坡股票市场的各类数据,从而构建股票监控、分析和交易系统。在实际使用中,建议:
- 合理设置请求频率,遵守API限制
- 实现适当的数据缓存机制
- 添加完善的错误处理和日志记录
- 对敏感数据进行安全存储和处理
希望本文对您获取和利用新加坡股票数据有所帮助!
846

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



