日本股票K线图生成实战:基于API的完整对接方案
引言
随着巴菲特增持日本五大商社以及日经225指数的强势表现,日本股市已成为全球投资者不可忽视的市场。对于开发者而言,如何快速、稳定地接入日本股票数据并生成专业的K线图,是构建量化系统或行情应用的关键需求。
本文将详细介绍如何通过金融API对接日本股票市场,获取实时行情数据,并使用Python的mplfinance库生成专业级K线图。整个过程将涵盖从API接入到数据可视化的完整流程。
环境准备
1. 获取API密钥
获取专属的API Key。这个密钥是访问所有数据接口的凭证,需妥善保管。
2. 安装必要依赖
pip install requests pandas numpy matplotlib mplfinance
3. 基础配置
import requests
import pandas as pd
import numpy as np
import mplfinance as mpf
API_KEY = "your_api_key_here" # 替换为实际API密钥
BASE_URL = "https://api.stocktv.top"
JAPAN_COUNTRY_ID = 35 # 日本市场专有ID
核心接口对接
1. 获取日本股票列表
通过指定countryId=35,可以获取日本交易所的全部股票清单及其最新成交价。
def get_japan_stocks(page=1, page_size=20):
"""获取日本股票列表"""
url = f"{BASE_URL}/stock/stocks"
params = {
"countryId": JAPAN_COUNTRY_ID,
"pageSize": page_size,
"page": page,
"key": API_KEY
}
response = requests.get(url, params=params)
result = response.json()
if result.get("code") == 200:
stocks = result["data"]["records"]
df = pd.DataFrame(stocks)
return df
else:
print("请求失败:", result.get("message"))
return None
# 示例:获取前20只日本股票
japan_stocks = get_japan_stocks()
print(japan_stocks[['symbol', 'name', 'last', 'chgPct']].head())
2. 精准查询特定日股实时行情
如果已知股票代码,可以使用查询接口获取更详细的实时快照。
def get_stock_realtime(symbol):
"""获取特定股票实时行情"""
url = f"{BASE_URL}/stock/queryStocks"
params = {
"symbol": symbol,
"key": API_KEY
}
response = requests.get(url, params=params)
result = response.json()
if result.get("code") == 200:
data = result["data"][0]
print(f"股票: {data['name']} ({data['symbol']})")
print(f"最新价: {data['last']}")
print(f"涨跌幅: {data['chgPct']}%")
print(f"更新时间戳: {data['time']}")
return data
else:
print("请求失败:", result.get("message"))
return None
# 示例:查询丰田汽车(7203)
toyota_data = get_stock_realtime("7203")
3. 获取K线数据
StockTV提供多种时间维度的K线数据,支持从5分钟到月线的实时计算更新。
def get_kline_data(pid, interval="P1D", limit=100):
"""获取K线数据"""
url = f"{BASE_URL}/stock/kline"
params = {
"pid": pid, # 股票的唯一标识
"interval": interval, # K线周期
"key": API_KEY
}
response = requests.get(url, params=params)
result = response.json()
if result.get("code") == 200:
kline_data = result["data"]
df = pd.DataFrame(kline_data)
# 转换时间戳为datetime
df['datetime'] = pd.to_datetime(df['time'], unit='ms')
df.set_index('datetime', inplace=True)
# 重命名列以符合mplfinance要求
df.rename(columns={
'open': 'Open',
'high': 'High',
'low': 'Low',
'close': 'Close',
'volume': 'Volume'
}, inplace=True)
return df[['Open', 'High', 'Low', 'Close', 'Volume']]
else:
print("请求失败:", result.get("message"))
return None
# 周期参数说明:
# PT1M (1分钟), PT5M (5分钟), PT15M (15分钟)
# PT1H (1小时), P1D (日K), P1W (周K), P1M (月K)
K线图生成
1. 基础K线图
使用mplfinance库可以轻松生成专业的K线图。
def plot_basic_kline(df, title="日本股票K线图"):
"""绘制基础K线图"""
# 自定义颜色方案(红涨绿跌)
mc = mpf.make_marketcolors(
up='red', # 上涨颜色
down='green', # 下跌颜色
volume={'up': 'red', 'down': 'green'}
)
style = mpf.make_mpf_style(
marketcolors=mc,
gridstyle='--',
gridcolor='gray',
facecolor='white'
)
# 绘制K线图
mpf.plot(
df,
type='candle',
style=style,
title=title,
ylabel='价格(日元)',
volume=True,
mav=(5, 10, 20), # 添加5、10、20日均线
figratio=(12, 6),
figscale=1.2
)
2. 高级K线图(添加技术指标)
def plot_advanced_kline(df, title="日本股票K线图(含技术指标)"):
"""绘制带技术指标的K线图"""
# 计算技术指标
df['MA5'] = df['Close'].rolling(window=5).mean()
df['MA10'] = df['Close'].rolling(window=10).mean()
df['MA20'] = df['Close'].rolling(window=20).mean()
# 计算RSI
delta = df['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
df['RSI'] = 100 - (100 / (1 + rs))
# 创建附加绘图对象
ap = [
mpf.make_addplot(df['MA5'], color='blue', width=1),
mpf.make_addplot(df['MA10'], color='orange', width=1),
mpf.make_addplot(df['MA20'], color='red', width=1),
mpf.make_addplot(df['RSI'], panel=1, color='purple', ylabel='RSI')
]
# 自定义样式
mc = mpf.make_marketcolors(
up='red',
down='green',
edge='inherit',
volume='in'
)
style = mpf.make_mpf_style(
marketcolors=mc,
gridstyle='--',
gridcolor='lightgray',
y_on_right=True
)
# 绘制图表
mpf.plot(
df,
type='candle',
style=style,
title=title,
ylabel='价格(日元)',
volume=True,
addplot=ap,
panel_ratios=(3, 1), # 主图和RSI图的比例
figratio=(14, 8),
figscale=1.5
)
完整实战示例
下面是一个完整的示例,展示如何从获取数据到生成K线图的完整流程:
import requests
import pandas as pd
import numpy as np
import mplfinance as mpf
from datetime import datetime, timedelta
class JapanStockKlineGenerator:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.stocktv.top"
self.japan_country_id = 35
def get_stock_pid(self, symbol):
"""根据股票代码获取PID"""
url = f"{self.base_url}/stock/queryStocks"
params = {"symbol": symbol, "key": self.api_key}
response = requests.get(url, params=params)
result = response.json()
if result.get("code") == 200:
return result["data"][0]["pid"]
else:
raise Exception(f"获取PID失败: {result.get('message')}")
def fetch_kline_data(self, symbol, interval="P1D", days=30):
"""获取K线数据"""
pid = self.get_stock_pid(symbol)
url = f"{self.base_url}/stock/kline"
params = {
"pid": pid,
"interval": interval,
"key": self.api_key
}
response = requests.get(url, params=params)
result = response.json()
if result.get("code") == 200:
kline_data = result["data"]
df = pd.DataFrame(kline_data)
# 数据处理
df['datetime'] = pd.to_datetime(df['time'], unit='ms')
df.set_index('datetime', inplace=True)
df.sort_index(inplace=True)
# 重命名列
df.rename(columns={
'open': 'Open',
'high': 'High',
'low': 'Low',
'close': 'Close',
'volume': 'Volume'
}, inplace=True)
return df[['Open', 'High', 'Low', 'Close', 'Volume']]
else:
raise Exception(f"获取K线数据失败: {result.get('message')}")
def generate_kline_chart(self, df, symbol, save_path=None):
"""生成K线图"""
# 自定义样式
mc = mpf.make_marketcolors(
up='red',
down='green',
edge='inherit',
volume='in',
wick={'up': 'red', 'down': 'green'}
)
style = mpf.make_mpf_style(
marketcolors=mc,
gridstyle='--',
gridcolor='lightgray',
facecolor='white',
edgecolor='black',
figcolor='white',
rc={'font.size': 10}
)
# 计算移动平均线
df['MA5'] = df['Close'].rolling(window=5).mean()
df['MA10'] = df['Close'].rolling(window=10).mean()
df['MA20'] = df['Close'].rolling(window=20).mean()
# 创建附加绘图
ap = [
mpf.make_addplot(df['MA5'], color='blue', width=1),
mpf.make_addplot(df['MA10'], color='orange', width=1),
mpf.make_addplot(df['MA20'], color='red', width=1)
]
# 绘制图表
fig, axes = mpf.plot(
df,
type='candle',
style=style,
title=f'{symbol} - 日本股票K线图',
ylabel='价格(日元)',
volume=True,
addplot=ap,
returnfig=True,
figratio=(12, 6),
figscale=1.2
)
if save_path:
fig.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"图表已保存至: {save_path}")
return fig
# 使用示例
if __name__ == "__main__":
# 初始化生成器(请替换为您的实际API Key)
generator = JapanStockKlineGenerator(api_key="YOUR_API_KEY_HERE")
try:
# 获取丰田汽车(7203)的K线数据
print("正在获取丰田汽车(7203)的K线数据...")
kline_data = generator.fetch_kline_data("7203", interval="P1D", days=60)
print(f"获取到 {len(kline_data)} 条K线数据")
print(kline_data.head())
# 生成K线图
print("正在生成K线图...")
fig = generator.generate_kline_chart(
kline_data,
symbol="7203(丰田汽车)",
save_path="toyota_kline.png"
)
print("K线图生成完成!")
except Exception as e:
print(f"发生错误: {e}")
实时性优化建议
对于需要更高实时性的应用场景,文档还提供了WebSocket接入方式:
- HTTP API:适合列表展示、基础行情、离线分析,定时轮询获取
- WebSocket:适合交易终端、高频监控、实时图表,毫秒级推送
如果需要开发高频交易系统或需要实时跳动价格的App,建议联系官方开启WebSocket接入权限。
总结
通过本文的介绍,我们了解了如何通过StockTV API对接日本股票市场,并生成专业的K线图。主要步骤包括:
- 获取API密钥:访问官网注册获取
- 环境配置:安装必要的Python库
- 数据获取:使用
countryId=35参数获取日本股票数据 - K线图生成:使用mplfinance库进行数据可视化
API的优势在于其低延迟、数据全面以及易于集成的特点,特别适合需要跨市场数据整合的中小型团队。
注意:本文代码示例仅供参考,实际使用时请根据官方最新文档进行调整。API密钥需妥善保管,避免泄露。