调用接口获取新加坡股票数据:技术实现指南

【投稿赢 iPhone 17】「我的第一个开源项目」故事征集:用代码换C位出道! 10w+人浏览 1.7k人参与

部署运行你感兴趣的模型镜像

调用接口获取新加坡股票数据:技术实现指南

概述

本文将介绍如何通过API接口获取新加坡股票市场的实时数据、历史行情和相关信息。新加坡作为亚洲重要的金融中心之一,其股票市场数据对于投资者和开发者具有重要价值。下面将详细讲解如何使用RESTful API获取这些数据。

接口基础信息

所有API请求均基于HTTPS协议,基本URL为:https://api.stocktv.top

注意:使用前需要获取有效的API密钥(key),所有请求都需要包含此参数。

核心接口详解

1. 获取新加坡股票列表

接口地址GET /stock/stocks

请求参数

  • countryId: 国家ID(新加坡对应的ID需要从文档中确认)
  • pageSize: 每页数量,默认10
  • page: 页码,默认1
  • key: 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: 国家ID
  • key: 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: 股票产品ID
  • interval: 时间间隔(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()

注意事项

  1. API限制:注意查看API的请求频率限制,避免过度请求
  2. 错误处理:妥善处理网络错误和API返回的错误信息
  3. 数据准确性:重要决策前应验证数据的准确性和时效性
  4. 密钥安全:妥善保管API密钥,不要在前端代码中暴露

总结

通过本文介绍的API接口,开发者可以方便地获取新加坡股票市场的各类数据,从而构建股票监控、分析和交易系统。在实际使用中,建议:

  1. 合理设置请求频率,遵守API限制
  2. 实现适当的数据缓存机制
  3. 添加完善的错误处理和日志记录
  4. 对敏感数据进行安全存储和处理

希望本文对您获取和利用新加坡股票数据有所帮助!

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值