一、前言:金融数据接口的价值
在量化交易、金融分析应用开发中,获取准确的K线、实时行情和IPO新股数据是基础需求。本文将详细介绍如何使用StockTV API对接这三类核心金融数据,并提供完整的代码实现方案。
二、环境准备与API密钥获取
1. 申请API密钥
访问StockTV官网注册账号并申请API Key,或通过Telegram联系客服获取测试密钥。- # 配置示例
- API_KEY = "your_api_key_here" # 替换为实际API密钥
- BASE_URL = "https://api.stocktv.top"
复制代码 2. 安装必要库
- pip install requests websocket-client pandas matplotlib
复制代码 三、K线数据对接实战
1. 获取K线数据接口
- import requests
- import pandas as pd
- def get_kline_data(symbol, interval="1d", limit=100):
- """
- 获取K线数据
- :param symbol: 股票/期货代码
- :param interval: 时间间隔(1m/5m/15m/1h/1d等)
- :param limit: 数据条数
- """
- url = f"{BASE_URL}/stock/kline"
- params = {
- "symbol": symbol,
- "interval": interval,
- "limit": limit,
- "key": API_KEY
- }
- response = requests.get(url, params=params)
- return response.json()
- # 示例:获取腾讯控股日K数据
- data = get_kline_data("00700.HK", interval="1d")
- df = pd.DataFrame(data['data'])
- df['time'] = pd.to_datetime(df['time'], unit='ms') # 转换时间戳
- print(df.head())
复制代码 2. K线数据可视化
- import matplotlib.pyplot as plt
- def plot_kline(df):
- plt.figure(figsize=(12,6))
- plt.title('K线图')
- plt.xlabel('日期')
- plt.ylabel('价格')
-
- # 绘制蜡烛图
- for idx, row in df.iterrows():
- color = 'red' if row['close'] > row['open'] else 'green'
- plt.plot([idx, idx], [row['low'], row['high']], color=color)
- plt.plot([idx-0.2, idx+0.2], [row['open'], row['open']], color=color)
- plt.plot([idx-0.2, idx+0.2], [row['close'], row['close']], color=color)
-
- plt.xticks(rotation=45)
- plt.grid()
- plt.show()
- plot_kline(df)
复制代码 四、实时行情数据对接方案
1. WebSocket实时数据订阅
- import websocket
- import json
- import threading
- class RealTimeData:
- def __init__(self):
- self.ws = None
-
- def on_message(self, ws, message):
- data = json.loads(message)
- print(f"实时数据更新: {data}")
-
- def on_error(self, ws, error):
- print(f"连接错误: {error}")
-
- def on_close(self, ws):
- print("连接关闭")
-
- def on_open(self, ws):
- print("连接建立")
- # 订阅腾讯控股和阿里巴巴股票
- subscribe_msg = {
- "action": "subscribe",
- "symbols": ["00700.HK", "09988.HK"]
- }
- ws.send(json.dumps(subscribe_msg))
-
- def start(self):
- websocket.enableTrace(True)
- self.ws = websocket.WebSocketApp(
- f"wss://ws-api.stocktv.top/connect?key={API_KEY}",
- on_message=self.on_message,
- on_error=self.on_error,
- on_close=self.on_close,
- on_open=self.on_open
- )
- self.ws.run_forever()
- # 启动实时数据连接
- rtd = RealTimeData()
- thread = threading.Thread(target=rtd.start)
- thread.start()
复制代码 2. 实时数据处理示例
- import sqlite3
- class DataProcessor:
- def __init__(self):
- self.conn = sqlite3.connect('market_data.db')
- self.create_table()
-
- def create_table(self):
- cursor = self.conn.cursor()
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS realtime_data (
- symbol TEXT,
- price REAL,
- volume INTEGER,
- timestamp INTEGER,
- PRIMARY KEY (symbol, timestamp)
- )
- ''')
- self.conn.commit()
-
- def process_message(self, data):
- cursor = self.conn.cursor()
- cursor.execute('''
- INSERT OR REPLACE INTO realtime_data
- VALUES (?, ?, ?, ?)
- ''', (data['symbol'], data['price'], data['volume'], data['timestamp']))
- self.conn.commit()
- # 使用示例
- processor = DataProcessor()
- # 在on_message回调中调用
- # processor.process_message(data)
复制代码 五、IPO新股数据对接
1. 获取IPO新股日历
- def get_ipo_calendar(country_id=44, limit=10):
- """
- 获取IPO新股日历
- :param country_id: 国家ID(44为印尼)
- :param limit: 返回数量
- """
- url = f"{BASE_URL}/stock/getIpo"
- params = {
- "countryId": country_id,
- "limit": limit,
- "key": API_KEY
- }
- response = requests.get(url, params=params)
- return response.json()
- # 示例:获取近期IPO新股
- ipo_data = get_ipo_calendar()
- for ipo in ipo_data['data']:
- print(f"{ipo['company']} ({ipo['symbol']}) - 发行价: {ipo['ipoPrice']}")
复制代码 2. IPO数据分析示例
- import matplotlib.pyplot as plt
- def analyze_ipo_data():
- data = get_ipo_calendar(limit=50)
- df = pd.DataFrame(data['data'])
-
- # 计算首日涨跌幅
- df['first_day_change'] = (df['last'] - df['ipoPrice']) / df['ipoPrice'] * 100
-
- # 绘制分布图
- plt.figure(figsize=(10,6))
- plt.hist(df['first_day_change'], bins=20, edgecolor='black')
- plt.title('IPO首日涨跌幅分布')
- plt.xlabel('涨跌幅(%)')
- plt.ylabel('数量')
- plt.grid(True)
- plt.show()
-
- return df
- ipo_stats = analyze_ipo_data()
复制代码 六、系统集成与优化建议
1. 系统架构设计
graph TD A[客户端] -->|HTTP API| B[K线/IPO数据] A -->|WebSocket| C[实时行情] B --> D[数据存储] C --> D D --> E[数据分析] E --> F[可视化/交易信号]2. 性能优化建议
- import redis
- r = redis.Redis(host='localhost', port=6379, db=0)
- def get_cached_kline(symbol, interval):
- cache_key = f"kline:{symbol}:{interval}"
- cached = r.get(cache_key)
- if cached:
- return json.loads(cached)
- else:
- data = get_kline_data(symbol, interval)
- r.setex(cache_key, 300, json.dumps(data)) # 缓存5分钟
- return data
复制代码- def batch_get_symbols(symbols):
- url = f"{BASE_URL}/stock/batch"
- params = {
- "symbols": ",".join(symbols),
- "key": API_KEY
- }
- return requests.get(url, params=params).json()
复制代码- from tenacity import retry, stop_after_attempt, wait_exponential
- @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
- def safe_api_call(url, params):
- response = requests.get(url, params=params, timeout=5)
- response.raise_for_status()
- return response.json()
复制代码 七、总结与资源
本文详细介绍了金融数据API的三个核心应用场景:
- K线数据 - 用于技术分析和策略回测
- 实时行情 - 构建实时监控和交易系统
- IPO新股 - 打新策略和上市表现分析
扩展资源:
- 完整API文档
- GitHub示例仓库
- 金融数据可视化技巧
提示:在实际生产环境中,建议添加速率限制、故障转移等机制确保系统稳定性。对于高频交易场景,可考虑使用专门的金融数据供应商获取更低延迟的数据服务。
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |