调用接口获取韩国股票数据

67 阅读5分钟

调用接口获取韩国股票数据

前言

在全球化投资背景下,韩国作为亚洲重要经济体,其股市数据对投资者和开发者具有重要意义。本文将详细介绍如何通过API接口获取韩国股票市场的实时行情、历史数据及相关信息。

接口基础配置

基础信息

  • ​基础URL​​: https://api.stocktv.top
  • ​协议​​: HTTPS
  • ​认证方式​​: API Key认证

环境准备

import requests
import pandas as pd
import json
from datetime import datetime

class KoreaStockAPI:
    def __init__(self, api_key):
        self.base_url = "https://api.stocktv.top"
        self.api_key = api_key
        self.session = requests.Session()
        
    def _make_request(self, endpoint, params):
        """统一的请求方法"""
        url = f"{self.base_url}{endpoint}"
        params['key'] = self.api_key
        
        try:
            response = self.session.get(url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()
            
            if data.get('code') == 200:
                return data['data']
            else:
                print(f"API Error: {data.get('message', 'Unknown error')}")
                return None
                
        except requests.exceptions.RequestException as e:
            print(f"Request failed: {e}")
            return None

核心接口详解

1. 获取韩国股票列表

def get_korea_stock_list(self, page_size=100, page=1):
    """
    获取韩国股票市场列表
    countryId: 韩国对应的国家ID需要确认(假设为16)
    """
    endpoint = "/stock/stocks"
    params = {
        'countryId': 16,  # 韩国国家ID,需确认具体数值
        'pageSize': page_size,
        'page': page
    }
    
    return self._make_request(endpoint, params)

# 使用示例
api = KoreaStockAPI("your_api_key")
stocks = api.get_korea_stock_list(page_size=50)

if stocks:
    for stock in stocks['records']:
        print(f"{stock['symbol']} - {stock['name']}: {stock['last']}")

​返回字段说明​​:

  • symbol: 股票代码(如:005930)
  • name: 公司名称(韩文或英文)
  • last: 最新价格
  • chgPct: 涨跌幅
  • volume: 成交量
  • high/low: 当日最高/低价
  • open: 是否在交易中

2. 查询特定韩国股票

def search_korea_stock(self, symbol=None, name=None, pid=None):
    """通过代码、名称或PID查询特定股票"""
    endpoint = "/stock/queryStocks"
    params = {}
    
    if symbol:
        params['symbol'] = symbol
    elif name:
        params['name'] = name
    elif pid:
        params['id'] = pid
        
    return self._make_request(endpoint, params)

# 查询三星电子
samsung = api.search_korea_stock(symbol="005930")

3. 获取韩国主要指数

def get_korea_indices(self):
    """获取韩国主要指数(KOSPI, KOSDAQ等)"""
    endpoint = "/stock/indices"
    params = {'countryId': 16}
    
    return self._make_request(endpoint, params)

# 使用示例
indices = api.get_korea_indices()
if indices:
    for index in indices:
        print(f"{index['name']}: {index['last']} ({index['chgPct']}%)")

4. 获取历史K线数据

def get_stock_kline(self, pid, interval="P1D", limit=100):
    """
    获取股票历史K线数据
    interval: PT5M(5分钟), PT1H(1小时), P1D(日线), P1W(周线)
    """
    endpoint = "/stock/kline"
    params = {
        'pid': pid,
        'interval': interval
    }
    
    data = self._make_request(endpoint, params)
    if data:
        return self._process_kline_data(data)
    return None

def _process_kline_data(self, kline_data):
    """处理K线数据为DataFrame格式"""
    df = pd.DataFrame(kline_data)
    df['time'] = pd.to_datetime(df['time'], unit='ms')
    df.set_index('time', inplace=True)
    return df

高级功能实现

1. 实时数据监控类

class KoreaStockMonitor:
    def __init__(self, api_key, watch_list):
        self.api = KoreaStockAPI(api_key)
        self.watch_list = watch_list
        self.price_alerts = {}
        
    def add_price_alert(self, symbol, target_price, direction='above'):
        """添加价格预警"""
        self.price_alerts[symbol] = {
            'target_price': target_price,
            'direction': direction,
            'triggered': False
        }
    
    def check_alerts(self, current_price, symbol):
        """检查价格预警条件"""
        if symbol in self.price_alerts:
            alert = self.price_alerts[symbol]
            if not alert['triggered']:
                if (alert['direction'] == 'above' and current_price >= alert['target_price']) or \
                   (alert['direction'] == 'below' and current_price <= alert['target_price']):
                    alert['triggered'] = True
                    return True
        return False
    
    def start_monitoring(self, interval=60):
        """开始监控"""
        import time
        
        while True:
            for symbol in self.watch_list:
                stock_data = self.api.search_korea_stock(symbol=symbol)
                if stock_data and len(stock_data) > 0:
                    current_price = stock_data[0]['last']
                    
                    if self.check_alerts(current_price, symbol):
                        self._send_alert(symbol, current_price)
            
            time.sleep(interval)
    
    def _send_alert(self, symbol, price):
        """发送预警通知"""
        print(f"Alert: {symbol} reached {price}")
        # 这里可以集成邮件、短信等通知方式

2. 数据分析工具

class KoreaStockAnalyzer:
    def __init__(self, api_key):
        self.api = KoreaStockAPI(api_key)
    
    def calculate_technical_indicators(self, pid, period=20):
        """计算技术指标"""
        kline_data = self.api.get_stock_kline(pid, "P1D", 100)
        if kline_data is None:
            return None
            
        # 计算移动平均线
        kline_data['MA20'] = kline_data['close'].rolling(window=period).mean()
        
        # 计算RSI
        delta = kline_data['close'].diff()
        gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
        loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
        rs = gain / loss
        kline_data['RSI'] = 100 - (100 / (1 + rs))
        
        return kline_data
    
    def get_market_overview(self):
        """获取市场概览"""
        stocks = self.api.get_korea_stock_list(page_size=200)
        if not stocks:
            return None
            
        advancing = 0
        declining = 0
        total_volume = 0
        
        for stock in stocks['records']:
            if stock.get('chgPct', 0) > 0:
                advancing += 1
            elif stock.get('chgPct', 0) < 0:
                declining += 1
            total_volume += stock.get('volume', 0)
        
        return {
            'total_stocks': len(stocks['records']),
            'advancing': advancing,
            'declining': declining,
            'total_volume': total_volume
        }

实际应用示例

1. 构建简单的股票看板

def create_stock_dashboard(api_key, symbols):
    """创建股票数据看板"""
    api = KoreaStockAPI(api_key)
    
    dashboard_data = []
    for symbol in symbols:
        stock_data = api.search_korea_stock(symbol=symbol)
        if stock_data and len(stock_data) > 0:
            stock = stock_data[0]
            dashboard_data.append({
                'Symbol': symbol,
                'Name': stock.get('name', 'N/A'),
                'Price': stock.get('last', 0),
                'Change %': stock.get('chgPct', 0),
                'Volume': stock.get('volume', 0)
            })
    
    df = pd.DataFrame(dashboard_data)
    return df

# 使用示例
symbols = ["005930", "000660", "035420"]  # 三星, SK海力士, Naver
dashboard = create_stock_dashboard("your_api_key", symbols)
print(dashboard)

2. 数据可视化

import matplotlib.pyplot as plt
import seaborn as sns

def plot_stock_trend(api_key, symbol, days=30):
    """绘制股票趋势图"""
    api = KoreaStockAPI(api_key)
    stock_data = api.search_korea_stock(symbol=symbol)
    
    if stock_data and len(stock_data) > 0:
        pid = stock_data[0]['id']
        kline_data = api.get_stock_kline(pid, "P1D", days)
        
        if kline_data is not None:
            plt.figure(figsize=(12, 6))
            plt.plot(kline_data.index, kline_data['close'], label='Close Price')
            plt.title(f'{symbol} Price Trend ({days} Days)')
            plt.xlabel('Date')
            plt.ylabel('Price')
            plt.legend()
            plt.grid(True)
            plt.xticks(rotation=45)
            plt.tight_layout()
            plt.show()

# 绘制三星电子近期走势
plot_stock_trend("your_api_key", "005930", 60)

注意事项和最佳实践

1. 错误处理增强

def robust_api_call(api_func, max_retries=3, delay=1):
    """带重试机制的API调用"""
    import time
    
    for attempt in range(max_retries):
        try:
            result = api_func()
            if result is not None:
                return result
        except Exception as e:
            print(f"Attempt {attempt + 1} failed: {e}")
            if attempt < max_retries - 1:
                time.sleep(delay * (2 ** attempt))  # 指数退避
    
    print("All retry attempts failed")
    return None

2. 数据缓存策略

from functools import lru_cache
import time

class CachedKoreaStockAPI(KoreaStockAPI):
    @lru_cache(maxsize=100)
    def get_korea_stock_list(self, page_size=100, page=1):
        # 基础方法已有缓存,这里可以添加时间戳验证
        return super().get_korea_stock_list(page_size, page)

3. 性能优化建议

  1. ​批量请求​​: 避免频繁的单次请求,合理设置请求间隔
  2. ​数据缓存​​: 对不常变的数据进行本地缓存
  3. ​异步处理​​: 对于大量数据请求使用异步方式
  4. ​连接复用​​: 使用Session保持HTTP连接

总结

通过本文介绍的API接口,开发者可以方便地获取韩国股票市场的各类数据。在实际应用中,建议:

  1. 合理控制请求频率,遵守API使用限制
  2. 实现完善的数据验证和错误处理机制
  3. 对敏感数据进行安全存储和处理
  4. 根据实际需求选择合适的数据更新策略

这些接口为构建韩国股票分析工具、投资决策系统和市场监控平台提供了坚实的数据基础。 ​​重要提示​​: 实际使用时请确认韩国的正确countryId,并确保遵守相关数据使用协议和法律法规。