一、期貨數據接口概述
StockTV提供全球主要期貨市場的實時行情與歷史數據接口,覆蓋以下品種:
- 商品期貨:原油、黃金、白銀、銅、天然氣、農產品等
- 金融期貨:股指期貨、國債期貨
- 特色品種:馬棕油、鐵礦石等區域特色期貨
二、環境準備與配置
1. API密鑰獲取
API_KEY = "your_futures_api_key" # 通過官網申請
BASE_URL = "https://api.stocktv.top"
2. 安裝必要庫
pip install requests pandas matplotlib websocket-client
三、期貨行情數據對接
1. 獲取期貨合約列表
def get_futures_list():"""獲取可交易期貨合約列表"""url = f"{BASE_URL}/futures/list"params = {"key": API_KEY}response = requests.get(url, params=params)return response.json()# 示例調用
futures_list = get_futures_list()
print("可用期貨合約:", [f"{x['symbol']} ({x['name']})" for x in futures_list['data'][:5]])
2. 查詢特定合約行情
def get_futures_quote(symbol):"""獲取期貨合約實時行情"""url = f"{BASE_URL}/futures/quote"params = {"symbol": symbol,"key": API_KEY}response = requests.get(url, params=params)return response.json()# 獲取原油期貨行情
crude_oil = get_futures_quote("CL1!")
print(f"WTI原油最新價: {crude_oil['data']['last']} 漲跌: {crude_oil['data']['change']}")
四、期貨K線數據獲取
1. 歷史K線數據接口
def get_futures_kline(symbol, interval="1d", limit=100):"""獲取期貨K線數據:param symbol: 合約代碼:param interval: 時間間隔(1m/5m/15m/1h/1d):param limit: 數據條數"""url = f"{BASE_URL}/futures/kline"params = {"symbol": symbol,"interval": interval,"limit": limit,"key": API_KEY}response = requests.get(url, params=params)data = response.json()# 轉換為DataFramedf = pd.DataFrame(data['data'])df['time'] = pd.to_datetime(df['time'], unit='ms')return df# 獲取黃金期貨15分鐘K線
gold_kline = get_futures_kline("GC1!", "15m")
2. K線數據可視化
import matplotlib.pyplot as pltdef plot_futures_kline(df, title):plt.figure(figsize=(12,6))plt.title(title)# 繪制蠟燭圖for i, row in df.iterrows():color = 'red' if row['close'] > row['open'] else 'green'plt.plot([i, i], [row['low'], row['high']], color=color)plt.plot([i-0.2, i+0.2], [row['open'], row['open']], color=color)plt.plot([i-0.2, i+0.2], [row['close'], row['close']], color=color)plt.xlabel('時間')plt.ylabel('價格')plt.grid()plt.show()plot_futures_kline(gold_kline, "COMEX黃金期貨15分鐘K線")
五、期貨交易數據存儲方案
1. 數據庫設計(SQL示例)
import sqlite3def init_db():conn = sqlite3.connect('futures_data.db')c = conn.cursor()c.execute('''CREATE TABLE IF NOT EXISTS futures_quotes(symbol text, last real, volume integer, time timestamp, PRIMARY KEY (symbol, time))''')c.execute('''CREATE TABLE IF NOT EXISTS futures_kline(symbol text, open real, high real, low real, close real, volume integer, time timestamp,PRIMARY KEY (symbol, time))''')conn.commit()conn.close()init_db()
2. 數據存儲實現
def save_futures_quote(data):conn = sqlite3.connect('futures_data.db')c = conn.cursor()c.execute('''INSERT INTO futures_quotes VALUES (?, ?, ?, ?)''',(data['symbol'], data['last'], data['volume'], data['time']))conn.commit()conn.close()def save_futures_kline(symbol, kline_data):conn = sqlite3.connect('futures_data.db')c = conn.cursor()for row in kline_data:c.execute('''INSERT INTO futures_kline VALUES (?, ?, ?, ?, ?, ?, ?)''',(symbol, row['open'], row['high'], row['low'],row['close'], row['volume'], row['time']))conn.commit()conn.close()
六、生產環境注意事項
- 錯誤處理與重試機制
from tenacity import retry, stop_after_attempt, wait_exponential@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def safe_futures_api_call(url, params):try:response = requests.get(url, params=params, timeout=5)response.raise_for_status()return response.json()except Exception as e:print(f"API調用失敗: {e}")raise
- 性能優化建議
- 使用Redis緩存高頻訪問的合約信息
- 批量獲取多個合約數據減少API調用次數
- 對歷史K線數據實現本地存儲
七、完整示例:期貨監控系統
import schedule
import timeclass FuturesMonitor:def __init__(self):self.tracked_symbols = ["CL1!", "GC1!"]def update_data(self):for symbol in self.tracked_symbols:# 獲取實時行情quote = get_futures_quote(symbol)print(f"{symbol} 最新價: {quote['data']['last']}")# 獲取K線數據kline = get_futures_kline(symbol, "15m")print(f"最近3根K線: {kline.tail(3)}")# 存儲數據save_futures_quote(quote['data'])def run(self):# 每15秒更新一次數據schedule.every(15).seconds.do(self.update_data)while True:schedule.run_pending()time.sleep(1)# 啟動監控
monitor = FuturesMonitor()
monitor.run()
八、總結與資源
核心功能總結
- 實時行情:獲取期貨合約的最新價格、成交量等數據
- 歷史數據:獲取不同時間周期的K線數據
- 實時推送:通過WebSocket接收實時行情更新
擴展資源
- StockTV期貨API文檔
- 示例代碼倉庫
- 全球主要期貨交易所列表
注意事項:
- 期貨合約存在到期日,注意合約切換
- 不同品種的交易時間不同
- 實時行情需處理網絡中斷等異常情況