使用API获取新加坡股票数据的完整指南
在金融科技开发和量化交易领域,获取准确、实时的股票数据是构建分析系统和交易策略的基础。新加坡作为亚洲重要的金融中心,其股票市场数据对于开发者和投资者具有重要价值。本文将详细介绍如何通过API接口获取新加坡股票数据,并提供完整的实现示例。
一、数据源选择与准备工作
在开始之前,我们需要选择一个可靠的数据源(仅供参考,不构成任何投资建议)。
1.1 获取访问凭证
要使用该数据服务,首先需要获取API密钥。
1.2 安装必要依赖
对于Python开发者,建议安装以下库:
pip install requests pandas matplotlib
二、核心接口详解
2.1 获取新加坡股票列表
要获取新加坡交易所(SGX)的股票列表,可以使用以下接口:
import requests
def get_singapore_stocks(api_key, page_size=20, page=1):
"""获取新加坡股票列表"""
url = "https://api.stocktv.top/stock/stocks"
params = {
"key": api_key,
"countryId": 43, # 新加坡国家ID
"pageSize": page_size,
"page": page
}
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
else:
print(f"请求失败: {response.status_code}")
return None
# 使用示例
api_key = "您的API密钥"
stocks_data = get_singapore_stocks(api_key)
if stocks_data and stocks_data.get("code") == 200:
for stock in stocks_data.get("data", {}).get("records", []):
print(f"代码: {stock['symbol']}, 名称: {stock['name']}, 最新价: {stock['last']}")
该接口返回的数据包含股票代码、名称、最新价格、涨跌幅、成交量等关键信息。
2.2 获取历史K线数据
对于技术分析和策略回测,历史K线数据至关重要:
def get_historical_kline(api_key, pid, interval="P1D", limit=100):
"""获取股票历史K线数据
参数:
- pid: 股票产品ID
- interval: 时间间隔
PT5M: 5分钟
PT15M: 15分钟
PT1H: 1小时
P1D: 日线
P1W: 周线
P1M: 月线
- limit: 数据条数
"""
url = "https://api.stocktv.top/stock/kline"
params = {
"pid": pid,
"interval": interval,
"limit": limit,
"key": api_key
}
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
else:
print(f"请求失败: {response.status_code}")
return None
# 使用示例
kline_data = get_historical_kline(api_key, pid=60231, interval="P1D", limit=50)
if kline_data and kline_data.get("code") == 200:
for candle in kline_data.get("data", []):
print(f"时间: {candle['time']}, 开盘: {candle['open']}, 最高: {candle['high']}, 最低: {candle['low']}, 收盘: {candle['close']}")
2.3 获取新加坡海峡时报指数(STI)
海峡时报指数是衡量新加坡市场表现的核心指标:
def get_singapore_indices(api_key):
"""获取新加坡指数数据"""
url = "https://api.stocktv.top/stock/indices"
params = {
"countryId": 15, # 新加坡指数标识
"key": api_key
}
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
else:
print(f"请求失败: {response.status_code}")
return None
三、实战应用场景
3.1 构建个股监控系统
通过简单的API调用,可以实时监控特定股票的价位变动和成交量异常:
import time
from datetime import datetime
class StockMonitor:
def __init__(self, api_key, stock_pid, alert_threshold=0.05):
self.api_key = api_key
self.stock_pid = stock_pid
self.alert_threshold = alert_threshold
self.last_price = None
def monitor_price(self):
"""监控股票价格变动"""
while True:
current_data = self.get_current_price()
if current_data:
current_price = current_data['last']
if self.last_price is not None:
price_change = (current_price - self.last_price) / self.last_price
if abs(price_change) > self.alert_threshold:
self.send_alert(f"价格异常波动: {price_change*100:.2f}%")
self.last_price = current_price
print(f"{datetime.now()}: 当前价格: {current_price}")
time.sleep(60) # 每分钟检查一次
def get_current_price(self):
"""获取当前价格"""
url = "https://api.stocktv.top/stock/queryStocks"
params = {
"id": self.stock_pid,
"key": self.api_key
}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
if data.get("code") == 200:
return data.get("data", [{}])[0]
return None
def send_alert(self, message):
"""发送警报"""
print(f"警报: {message}")
# 这里可以集成邮件、短信或推送通知
3.2 开发量化交易策略
获取历史数据后,可以进行策略回测分析:
import pandas as pd
import numpy as np
class StrategyBacktester:
def __init__(self, api_key):
self.api_key = api_key
def backtest_moving_average(self, pid, short_window=10, long_window=30):
"""移动平均线策略回测"""
# 获取历史数据
kline_data = get_historical_kline(self.api_key, pid, interval="P1D", limit=200)
if not kline_data or kline_data.get("code") != 200:
return None
# 转换为DataFrame
df = pd.DataFrame(kline_data.get("data", []))
df['time'] = pd.to_datetime(df['time'], unit='ms')
df.set_index('time', inplace=True)
# 计算移动平均线
df['short_ma'] = df['close'].rolling(window=short_window).mean()
df['long_ma'] = df['close'].rolling(window=long_window).mean()
# 生成交易信号
df['signal'] = 0
df['signal'][short_window:] = np.where(
df['short_ma'][short_window:] > df['long_ma'][short_window:], 1, 0
)
df['positions'] = df['signal'].diff()
# 计算收益率
df['returns'] = df['close'].pct_change()
df['strategy_returns'] = df['returns'] * df['signal'].shift(1)
return df
四、开发注意事项
4.1 交易时间处理
新加坡股市交易时间通常为北京时间09:00-17:00(含午休),在非交易时段,价格数据将保持为收盘价。开发时需要考虑这一特性。
4.2 错误处理与频率限制
建议在代码中增加完善的错误处理机制:
def safe_api_call(func, max_retries=3):
"""安全的API调用装饰器"""
def wrapper(*args, **kwargs):
for attempt in range(max_retries):
try:
result = func(*args, **kwargs)
if result and result.get("code") == 200:
return result
elif result and result.get("code") != 200:
print(f"API返回错误: {result.get('message')}")
time.sleep(2 ** attempt) # 指数退避
except Exception as e:
print(f"第{attempt+1}次尝试失败: {e}")
time.sleep(2 ** attempt)
return None
return wrapper
4.3 数据单位与货币
SGX股票通常以新加坡元(SGD)计价,处理跨境投资应用时需要注意汇率转换。
五、性能优化建议
5.1 使用WebSocket实时数据
对于需要实时数据的应用场景,建议使用WebSocket协议:
import websocket
import json
class RealTimeDataClient:
def __init__(self, api_key):
self.api_key = api_key
self.ws = None
def connect(self):
"""连接WebSocket服务器"""
ws_url = f"wss://api.stocktv.top/ws?key={self.api_key}"
self.ws = websocket.WebSocketApp(
ws_url,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close
)
self.ws.on_open = self.on_open
self.ws.run_forever()
def subscribe_stock(self, symbol):
"""订阅股票实时数据"""
if self.ws:
subscribe_msg = {
"action": "subscribe",
"symbol": symbol,
"channel": "stock"
}
self.ws.send(json.dumps(subscribe_msg))
def on_message(self, ws, message):
"""处理接收到的消息"""
data = json.loads(message)
print(f"实时数据: {data}")
def on_error(self, ws, error):
print(f"WebSocket错误: {error}")
def on_close(self, ws, close_status_code, close_msg):
print("WebSocket连接关闭")
def on_open(self, ws):
print("WebSocket连接已建立")
5.2 数据缓存策略
对于频繁访问的数据,建议实现缓存机制以减少API调用:
from functools import lru_cache
import time
class CachedDataFetcher:
def __init__(self, api_key, cache_ttl=300):
self.api_key = api_key
self.cache_ttl = cache_ttl
self.cache = {}
@lru_cache(maxsize=128)
def get_cached_data(self, endpoint, params):
"""带缓存的数据获取"""
cache_key = f"{endpoint}_{hash(frozenset(params.items()))}"
if cache_key in self.cache:
cached_data, timestamp = self.cache[cache_key]
if time.time() - timestamp < self.cache_ttl:
return cached_data
# 调用API获取新数据
url = f"https://api.stocktv.top/{endpoint}"
params['key'] = self.api_key
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
self.cache[cache_key] = (data, time.time())
return data
return None
六、总结
通过本文介绍的API接口,开发者可以轻松获取新加坡股票市场的实时行情、历史数据和指数信息。这些数据接口设计合理,支持RESTful API和WebSocket两种协议,能够满足不同场景下的数据需求。
无论是构建个股监控系统、开发量化交易策略,还是进行市场分析研究,这些接口都提供了可靠的数据支持。在实际开发过程中,建议关注错误处理、频率限制和数据缓存等关键点,以确保应用的稳定性和性能。