一、韩国金融市场特色与数据价值

韩国作为亚洲第四大经济体,其金融市场具有以下显著特点:

  • 高波动性:KOSPI指数日均波动率1.5%左右
  • 科技股主导:三星电子、SK海力士等科技巨头占比超40%
  • 独特交易机制:上午9:00-15:30(KST),午间不休市
  • 活跃IPO市场:2023年韩国IPO融资额位居亚洲前列
  • 外资占比高:外资持股比例平均达30-40%

二、环境配置与基础对接

1. API密钥与基础配置

# 基础配置
API_KEY = "your_korea_api_key"  # 通过官网申请
BASE_URL = "https://api.stocktv.top"
KOREA_ID = 17  # 韩国国家代码
KOSPI_EXCHANGE = "KRX"  # 韩国交易所代码

# 时区设置
import pytz
kst = pytz.timezone('Asia/Seoul')

2. 安装必要库

pip install requests websocket-client pandas plotly python-dotenv

三、K线数据专业对接方案

1. 多周期K线获取接口

def get_korea_kline(stock_code, interval="1d", market="KOSPI"):
    """
    获取韩国股票K线数据
    :param stock_code: 股票代码(如005930)
    :param interval: 时间间隔(1m/5m/15m/1h/1d)
    :param market: 市场类型(KOSPI/KOSDAQ)
    """
    url = f"{BASE_URL}/stock/kline"
    params = {
        "symbol": stock_code,
        "market": market,
        "interval": interval,
        "countryId": KOREA_ID,
        "key": API_KEY
    }
    response = requests.get(url, params=params)
    data = response.json()
    
    # 转换为DataFrame并处理时区
    df = pd.DataFrame(data['data'])
    df['time'] = pd.to_datetime(df['time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert(kst)
    return df

# 获取三星电子(005930)日K数据
samsung_kline = get_korea_kline("005930", interval="1d")

2. 专业K线可视化(支持韩国特色指标)

import plotly.graph_objects as go
from plotly.subplots import make_subplots

def plot_korean_stock(df, title):
    # 创建带成交量的子图
    fig = make_subplots(rows=2, cols=1, shared_xaxes=True, 
                       vertical_spacing=0.05,
                       row_heights=[0.7, 0.3])
    
    # K线主图
    fig.add_trace(go.Candlestick(
        x=df['time'],
        open=df['open'],
        high=df['high'],
        low=df['low'],
        close=df['close'],
        name='K线',
        increasing_line_color='red',  # 韩国市场通常用红色表示上涨
        decreasing_line_color='blue'  # 蓝色表示下跌
    ), row=1, col=1)
    
    # 添加韩国常用的5/20/60日均线
    for period in [5, 20, 60]:
        df[f'MA{period}'] = df['close'].rolling(period).mean()
        fig.add_trace(go.Scatter(
            x=df['time'],
            y=df[f'MA{period}'],
            name=f'MA{period}',
            line=dict(width=1)
        ), row=1, col=1)
    
    # 成交量柱状图
    fig.add_trace(go.Bar(
        x=df['time'],
        y=df['volume'],
        name='成交量',
        marker_color='grey'
    ), row=2, col=1)
    
    fig.update_layout(
        title=f'{title} - 韩国市场',
        xaxis_title='首尔时间(KST)',
        yaxis_title='价格(KRW)',
        template="plotly_white",
        hovermode="x unified"
    )
    
    fig.update_xaxes(
        rangeslider_visible=False,
        rangebreaks=[{'bounds': ['sat', 'mon']}]  # 隐藏周末
    )
    
    fig.show()

plot_korean_stock(samsung_kline, "三星电子(005930)")

四、实时行情数据对接

1. WebSocket实时数据订阅

class KoreaRealtimeData:
    def __init__(self):
        self.symbol_map = {
            "005930": "三星电子",
            "000660": "SK海力士",
            "035420": "NAVER"
        }
    
    def on_message(self, ws, message):
        data = json.loads(message)
        
        # 处理股票行情
        if data.get('type') == 'stock':
            symbol = data['symbol']
            name = self.symbol_map.get(symbol, symbol)
            change = data.get('chgPct', 0)
            
            # 韩国市场特殊颜色表示
            color = "🔴" if change >= 0 else "🔵"
            print(f"{color} {name}({symbol}): {data['last']:,} KRW "
                  f"({change:+.2f}%) 成交量: {data['volume']:,}")
        
        # 处理指数行情
        elif data.get('type') == 'index':
            print(f"📊 {data['name']}: {data['last']} "
                  f"({data.get('chgPct', 0):+.2f}%)")
    
    def start(self):
        ws = websocket.WebSocketApp(
            f"wss://ws-api.stocktv.top/connect?key={API_KEY}",
            on_message=self.on_message,
            on_open=self.on_open
        )
        
        # 启动独立线程
        self.ws_thread = threading.Thread(target=ws.run_forever)
        self.ws_thread.daemon = True
        self.ws_thread.start()
    
    def on_open(self, ws):
        # 订阅韩国龙头股和KOSPI指数
        subscribe_msg = {
            "action": "subscribe",
            "countryId": KOREA_ID,
            "symbols": list(self.symbol_map.keys()),
            "indices": ["KS11"]  # KOSPI指数代码
        }
        ws.send(json.dumps(subscribe_msg))

# 启动实时服务
kr_realtime = KoreaRealtimeData()
kr_realtime.start()

2. 实时数据存储方案(适配韩国市场)

from sqlalchemy import create_engine, Column, Integer, String, Numeric, DateTime
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class KoreaRealtime(Base):
    __tablename__ = 'korea_realtime'
    
    id = Column(Integer, primary_key=True)
    symbol = Column(String(10))
    name = Column(String(50))
    price = Column(Numeric(12, 2))
    volume = Column(Integer)
    change_pct = Column(Numeric(5, 2))
    timestamp = Column(DateTime)
    created_at = Column(DateTime, server_default='CURRENT_TIMESTAMP')

# 初始化数据库
engine = create_engine('mysql+pymysql://user:password@localhost/korea_market')
Base.metadata.create_all(engine)

def save_korea_realtime(data):
    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind=engine)
    session = Session()
    
    try:
        record = KoreaRealtime(
            symbol=data['symbol'],
            name=kr_realtime.symbol_map.get(data['symbol']),
            price=data['last'],
            volume=data.get('volume', 0),
            change_pct=data.get('chgPct', 0),
            timestamp=datetime.fromtimestamp(data['timestamp'], kst)
        )
        session.add(record)
        session.commit()
    except Exception as e:
        print(f"存储失败: {e}")
        session.rollback()
    finally:
        session.close()

五、韩国IPO新股数据对接

1. 获取IPO日历与详情

def get_korea_ipo_list(status="upcoming"):
    """
    获取韩国IPO列表
    :param status: upcoming(即将上市)/recent(近期上市)
    """
    url = f"{BASE_URL}/stock/getIpo"
    params = {
        "countryId": KOREA_ID,
        "status": status,
        "key": API_KEY
    }
    response = requests.get(url, params=params)
    return response.json()

# 获取即将上市的IPO
upcoming_ipos = get_korea_ipo_list()
print("韩国即将上市IPO:")
for ipo in upcoming_ipos['data'][:3]:
    print(f"- {ipo['company']} ({ipo['symbol']})")
    print(f"  行业: {ipo.get('sector', 'N/A')}")
    print(f"  发行价: {ipo['ipoPrice']:,} KRW")
    print(f"  上市日期: {ipo['date']}")

# 获取近期IPO表现
recent_ipos = get_korea_ipo_list("recent")
print("\n近期IPO首日表现:")
for ipo in recent_ipos['data'][:3]:
    change = (ipo['last'] - ipo['ipoPrice']) / ipo['ipoPrice'] * 100
    print(f"- {ipo['company']}: {ipo['ipoPrice']:,} → {ipo['last']:,} KRW "
          f"({change:+.2f}%)")

2. IPO数据分析可视化

def analyze_korea_ipos():
    ipos = get_korea_ipo_list("recent")['data']
    df = pd.DataFrame(ipos)
    
    # 计算收益率
    df['return_pct'] = (df['last'] - df['ipoPrice']) / df['ipoPrice'] * 100
    
    # 按行业分析
    sector_analysis = df.groupby('sector')['return_pct'].agg(['mean', 'count'])
    print("\n分行业IPO平均表现:")
    print(sector_analysis.sort_values('mean', ascending=False))
    
    # 可视化
    fig = px.scatter(df, x='ipoValue', y='return_pct', color='sector',
                     hover_data=['company', 'symbol'],
                     title="韩国IPO表现分析",
                     labels={'ipoValue':'发行规模(十亿KRW)', 
                            'return_pct':'收益率(%)',
                            'sector':'行业'})
    fig.update_traces(marker_size=10)
    fig.show()
    
    return df

ipo_analysis = analyze_korea_ipos()

六、生产环境最佳实践

1. 韩国市场特殊处理

# 韩国市场假期处理
KR_HOLIDAYS = [
    '2024-01-01', '2024-02-09', '2024-02-12',  # 示例日期
    '2024-03-01', '2024-05-06', '2024-06-06'
]

def is_korea_trading_day(date):
    """检查是否为韩国交易日"""
    date_str = date.strftime('%Y-%m-%d')
    weekday = date.weekday()
    return date_str not in KR_HOLIDAYS and weekday < 5

# 时区敏感的时间处理
def get_korea_time():
    return datetime.now(kst).strftime('%Y-%m-%d %H:%M:%S')

2. 性能优化与缓存

from functools import lru_cache
import redis

# 初始化Redis
redis_client = redis.StrictRedis(host='localhost', port=6379, db=1)

@lru_cache(maxsize=100)
def get_korea_stock_info(symbol):
    """带缓存的股票信息查询"""
    cache_key = f"kr:stock:{symbol}:info"
    cached = redis_client.get(cache_key)
    if cached:
        return json.loads(cached)
    
    url = f"{BASE_URL}/stock/queryStocks"
    params = {
        "symbol": symbol,
        "countryId": KOREA_ID,
        "key": API_KEY
    }
    data = safe_api_call(url, params)
    redis_client.setex(cache_key, 3600, json.dumps(data))  # 缓存1小时
    return data

七、总结与资源

核心要点回顾

  1. K线数据:支持韩国特色技术指标和可视化方式
  2. 实时行情:适配韩国交易机制的颜色和数据显示
  3. IPO数据:包含韩国特色的行业分类和表现分析

扩展资源

韩国市场特别注意

  1. 价格波动限制:分15%→30%两档熔断
  2. 外资持股限制:部分股票有外资持股比例限制
  3. 股息税:与韩国签订税收协定的国家适用优惠税率
  4. 关注韩国特有的"股票分割"文化(如1:5分割常见)

CryptoRzz
17 声望0 粉丝