对接API库 获取印度股票历史数据
引言:印度股市的数据价值
印度作为全球增长最快的主要经济体之一,其金融市场吸引了众多国际投资者的目光。印度股市采用双交易所体系,包括国家证券交易所(NSE)和孟买证券交易所(BSE),其中NSE占全国交易量的90%以上,Nifty 50指数是其核心基准,而BSE是亚洲最古老的交易所,Sensex 30指数代表传统企业。
对于开发者、数据分析师和量化研究人员来说,获取印度股市的高质量历史数据是进行市场分析、策略回测和投资决策的基础。本文将详细介绍如何通过API高效对接印度股票市场,获取包括K线、实时行情在内的全面金融数据。
一、环境配置与API基础
1.1 获取API密钥
首先,您需要API获取API密钥,这是调用所有数据接口的凭证。
# StockTV API基础配置
API_KEY = "your_api_key_here" # 通过官网或客服获取
BASE_URL = "https://api.stocktv.top"
# 印度市场特定参数
INDIA_COUNTRY_ID = 14 # 印度国家代码
NSE_EXCHANGE_ID = 46 # NSE交易所代码
BSE_EXCHANGE_ID = 74 # BSE交易所代码
1.2 安装必要依赖库
根据您的开发语言选择相应的安装方式:
# Python环境安装
pip install requests websocket-client pandas pytz plotly
// Java项目依赖(Maven)
// 在pom.xml中添加HttpClient和JSON处理依赖
二、获取印度股票列表
在获取历史数据前,需要先了解印度市场的股票列表及其标识符。
2.1 获取NSE和BSE股票列表
import requests
def get_indian_stocks(page=1, page_size=50):
"""获取印度股票列表"""
url = f"{BASE_URL}/stock/stocks"
params = {
"countryId": INDIA_COUNTRY_ID, # 印度国家ID
"pageSize": page_size,
"page": page,
"key": API_KEY
}
response = requests.get(url, params=params)
return response.json()
# 示例调用
stocks = get_indian_stocks()
print(f"获取到{len(stocks['data']['records'])}只印度股票")
2.2 解析股票列表数据
StockTV返回的股票列表包含以下关键信息:
{
"code": 200,
"data": {
"records": [
{
"id": 946725, // 重要:这是PID,后续查K线要用
"name": "Inventure Growth Securities",
"symbol": "IGSL",
"exchangeId": 46, // 46代表NSE,74代表BSE
"last": 2.46, // 最新价
"chgPct": -20.13, // 涨跌幅
"countryNameTranslated": "India"
}
]
}
}
三、获取印度股票K线数据
K线数据是历史数据分析的核心,包含开盘价、最高价、最低价、收盘价和成交量等信息。
3.1 多周期K线获取接口
import pandas as pd
import requests
def get_india_kline(pid, interval="15m"):
"""
获取印度股票K线数据
:param pid: 股票ID(从股票列表中获取)
:param interval: 时间间隔(1m/5m/15m/1h/1d)
"""
url = f"{BASE_URL}/stock/kline"
params = {
"pid": pid,
"interval": interval,
"key": API_KEY
}
response = requests.get(url, params=params)
data = response.json()
# 转换为Pandas DataFrame
df = pd.DataFrame(data['data'])
df['time'] = pd.to_datetime(df['time'], unit='ms') # 转换时间戳
return df
# 获取Reliance Industries的日线数据
reliance_kline = get_india_kline(12345, "1d")
3.2 支持的时间周期
StockTV API支持多种时间周期,满足不同分析需求:
| 周期参数 | 说明 | 适用场景 |
|---|---|---|
| PT1M | 1分钟K线 | 高频交易分析 |
| PT5M | 5分钟K线 | 短期趋势分析 |
| PT15M | 15分钟K线 | 日内交易 |
| PT1H | 1小时K线 | 中期趋势分析 |
| P1D | 日线数据 | 长期投资分析 |
3.3 Java语言获取K线数据示例
对于Java开发者,可以使用以下方式获取K线数据:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import org.json.JSONArray;
import org.json.JSONObject;
public class IndiaKLineFetcher {
public static void main(String[] args) throws Exception {
String apiUrl = "https://api.stocktv.top/stock/kline?pid=12345&interval=P1D&key=YOUR_API_KEY";
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JSONObject jsonResponse = new JSONObject(response.body());
JSONArray data = jsonResponse.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject item = data.getJSONObject(i);
System.out.println("时间: " + item.getLong("time") +
", 开盘价: " + item.getDouble("open") +
", 最高价: " + item.getDouble("high") +
", 最低价: " + item.getDouble("low") +
", 收盘价: " + item.getDouble("close"));
}
}
}
四、高级数据获取功能
4.1 获取印度指数数据
印度市场的主要指数(如Nifty 50和Sensex)是市场风向标。
def get_indian_indices():
"""获取印度主要指数数据"""
url = f"{BASE_URL}/stock/indices"
params = {
"countryId": INDIA_COUNTRY_ID,
"key": API_KEY
}
response = requests.get(url, params=params)
return response.json()
# 获取指数数据
indices = get_indian_indices()
nifty50 = next(i for i in indices['data'] if i['name'] == 'Nifty 50')
print(f"Nifty 50当前点位: {nifty50['last']}")
4.2 IPO新股数据获取
印度IPO市场活跃,StockTV API提供新股上市日历和详细信息。
def get_india_ipo_list(status="upcoming"):
"""
获取印度IPO列表
:param status: upcoming(即将上市)/recent(近期上市)
"""
url = f"{BASE_URL}/stock/getIpo"
params = {
"countryId": INDIA_COUNTRY_ID,
"status": status,
"key": API_KEY
}
response = requests.get(url, params=params)
return response.json()
# 获取即将上市的IPO
upcoming_ipos = get_india_ipo_list("upcoming")
print("即将上市的IPO:")
for ipo in upcoming_ipos['data'][:5]:
print(f"{ipo['company']} ({ipo['symbol']}) - 发行价: ₹{ipo['ipoPrice']}")
五、专业级数据处理与可视化
5.1 K线数据可视化
使用Plotly等库对获取的K线数据进行可视化展示。
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def plot_advanced_kline(df, title="印度股票K线图"):
"""绘制专业K线图"""
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
vertical_spacing=0.03, subplot_titles=(title, '成交量'),
row_width=[0.2, 0.7])
# K线主图
fig.add_trace(go.Candlestick(x=df['time'], open=df['open'],
high=df['high'], low=df['low'],
close=df['close'], name="K线"),
row=1, col=1)
# 成交量图
fig.add_trace(go.Bar(x=df['time'], y=df['volume'],
name="成交量", marker_color='rgba(100, 100, 255, 0.6)'),
row=2, col=1)
fig.update_layout(xaxis_rangeslider_visible=False)
fig.show()
# 使用示例
plot_advanced_kline(reliance_kline, "Reliance Industries K线图")
5.2 数据存储方案
对于大量历史数据,建议使用数据库进行存储管理。
from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
Base = declarative_base()
class HistoricalData(Base):
__tablename__ = 'india_historical_data'
id = Column(Integer, primary_key=True)
symbol = Column(String(20))
exchange = Column(String(10))
open_price = Column(Float)
high_price = Column(Float)
low_price = Column(Float)
close_price = Column(Float)
volume = Column(Integer)
timestamp = Column(DateTime)
created_at = Column(DateTime, default=datetime.utcnow)
# 初始化数据库连接
engine = create_engine('sqlite:///india_market.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
六、生产环境最佳实践
6.1 错误处理与重试机制
在生产环境中,稳定的错误处理机制至关重要。
from tenacity import retry, stop_after_attempt, wait_exponential
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@retry(stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10))
def safe_api_call(url, params):
"""带重试机制的API调用"""
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
logger.error(f"API请求失败: {e}")
raise
# 使用安全API调用
try:
data = safe_api_call(f"{BASE_URL}/stock/kline", params)
except Exception as e:
logger.error(f"获取K线数据失败: {e}")
6.2 性能优化方案
对于大量数据的获取,性能优化是必要的。
from threading import Thread
from concurrent.futures import ThreadPoolExecutor, as_completed
import redis
from functools import lru_cache
# 初始化Redis连接用于缓存
r = redis.Redis(host='localhost', port=6379, db=0)
@lru_cache(maxsize=100)
def get_stock_info(symbol):
"""缓存股票基本信息"""
cache_key = f"stock:{symbol}:info"
cached = r.get(cache_key)
if cached:
return json.loads(cached)
# 缓存未命中时调用API
url = f"{BASE_URL}/stock/queryStocks"
params = {"symbol": symbol, "countryId": INDIA_COUNTRY_ID, "key": API_KEY}
data = safe_api_call(url, params)
r.setex(cache_key, 3600, json.dumps(data)) # 缓存1小时
return data
# 批量获取K线数据优化
def batch_get_kline(symbols, interval):
"""批量获取K线数据,减少API调用次数"""
results = {}
with ThreadPoolExecutor(max_workers=5) as executor:
future_to_symbol = {
executor.submit(get_india_kline, sym, "NSE", interval): sym
for sym in symbols
}
for future in as_completed(future_to_symbol):
symbol = future_to_symbol[future]
try:
results[symbol] = future.result()
except Exception as e:
logger.error(f"获取{symbol}数据失败: {e}")
return results
七、印度市场特殊考量
7.1 时区处理
印度使用IST时区(UTC+5:30),所有时间戳需要正确转换。
from pytz import timezone
import pandas as pd
def convert_to_ist(timestamp):
"""将时间戳转换为印度标准时间"""
utc_time = pd.to_datetime(timestamp, unit='ms', utc=True)
ist = timezone('Asia/Kolkata')
return utc_time.tz_convert(ist)
# 应用时区转换
df['time_ist'] = df['time'].apply(convert_to_ist)
7.2 交易时间考虑
印度股市交易时间为工作日09:15-15:30 IST(UTC+5:30),中间有12:00-12:15的午休时间,数据处理时需考虑这些非交易时段。
结语
通过StockTV API,开发者可以高效地获取印度股票市场的全面历史数据,为量化分析、策略回测和投资决策提供数据支持。本文介绍了从基础配置到高级应用的完整流程,涵盖了REST API调用、数据可视化、错误处理和性能优化等关键环节。
印度金融市场具有巨大的增长潜力和独特的特性,通过可靠的数据接口获取准确、及时的市场数据,是把握投资机会的重要基础。希望本文能为您的印度股市数据分析项目提供实用的技术参考。
本文代码示例基于StockTV API v3.2,实际开发请以最新官方文档为准。