通过 iTick API 集成尼日利亚 (NG) 股票市场数据 – 实时行情 & 历史K线
发布: (2026年2月10日 GMT+8 00:20)
6 分钟阅读
原文: Dev.to
抱歉,我没有看到您要翻译的正文内容。请把需要翻译的文本(除 > Source: … 之外的部分)粘贴在这里,我会按照要求为您翻译成简体中文,并保留原有的格式、Markdown 语法以及技术术语。
1. 准备工作:API 设置基础
1.1 注册与 API Token
iTick 目前是尼日利亚市场上较为可靠的本地金融数据提供商之一,提供实时和历史数据。
- 访问 官方站点 并注册开发者账号。
- 完成邮箱验证。
- 你将收到你的 API_TOKEN(在旧文档中有时仍称为 API_KEY)。此 token 是后续所有 API 调用的核心凭证——请妥善保管。
1.2 环境搭建
我使用 Python 3.8+。基本使用只需两个主要库:
pip install requests pandas mplfinance
requests– 用于 HTTP 调用pandas– 用于数据结构化mplfinance– 可选,用于绘制蜡烛图
2. 实战1 – 获取实时行情
当前端点(2026)
GET /stock/quote?region=NG&code=xxxx
重要:尼日利亚的市场代码现已改为 NG(不再是 NSENG)。
干净且可复用的实现
import requests
import time
from typing import Dict, Optional
import pandas as pd
class ITickNGAPI:
"""
iTick API wrapper for Nigerian (NG) stock market data – 2026 version
"""
def __init__(self, token: str):
self.base_url = "https://api.itick.org"
self.token = token
self.headers = {
"accept": "application/json",
"token": self.token
}
def get_realtime_quote(self, stock_code: str) -> Optional[Dict]:
"""
Get real‑time quote for a single stock
:param stock_code: e.g. "DANGCEM"
:return: quote dictionary or None if failed
"""
for retry in range(3):
try:
url = f"{self.base_url}/stock/quote"
params = {
"region": "NG",
"code": stock_code.upper() # must be uppercase
}
response = requests.get(
url,
headers=self.headers,
params=params,
timeout=10
)
if response.status_code == 200:
result = response.json()
if result.get("code") == 0 and "data" in result:
quote = result["data"]
return {
"Symbol": quote["s"],
"Last Price": quote["ld"],
"Open": quote["o"],
"High": quote["h"],
"Low": quote["l"],
"Volume": quote["v"],
"Change": quote["ch"],
"Change %": quote["chp"],
"Timestamp": quote["t"],
"Trading Status": quote["ts"] # 0=normal, 1=suspended, etc.
}
else:
print(f"No real‑time data found for {stock_code} or API error")
return None
else:
print(f"Request failed – status {response.status_code} – retry {retry+1}")
time.sleep(1.5)
except requests.exceptions.Timeout:
print(f"Timeout – retry {retry+1}")
time.sleep(1.5)
except Exception as e:
print(f"Exception: {str(e)}")
return None
return None
# ────────────────────────────────────────────────
if __name__ == "__main__":
MY_TOKEN = "your_itick_token_here"
api = ITickNGAPI(MY_TOKEN)
quote = api.get_realtime_quote("DANGCEM")
if quote:
print("=== Nigerian (NG) Real‑time Quote ===")
for k, v in quote.items():
print(f"{k}: {v}")
3. 获取历史 K‑线 数据
def get_historical_klines(
self,
stock_code: str,
k_type: int = 8,
limit: int = 30,
end_timestamp: Optional[int] = None
) -> Optional[pd.DataFrame]:
"""
Fetch historical k‑line data
"""
try:
url = f"{self.base_url}/stock/kline"
params = {
"region": "NG",
"code": stock_code.upper(),
"kType": k_type,
"limit": limit
}
if end_timestamp:
params["et"] = end_timestamp
response = requests.get(
url, headers=self.headers, params=params, timeout=12
)
if response.status_code == 200:
result = response.json()
if result.get("code") == 0 and "data" in result:
# Convert list of dicts to DataFrame
df = pd.DataFrame(result["data"])
# Rename columns for readability
df.rename(columns={
"t": "Timestamp",
"o": "Open",
"h": "High",
"l": "Low",
"c": "Close",
"v": "Volume"
}, inplace=True)
# Convert timestamp from ms to datetime (UTC)
df["Timestamp"] = pd.to_datetime(df["Timestamp"], unit="ms", utc=True)
return df
else:
print(f"API returned error for {stock_code}: {result.get('msg')}")
return None
else:
print(f"HTTP error {response.status_code} when fetching k‑lines")
return None
except Exception as e:
print(f"Exception while fetching k‑lines: {e}")
return None
使用示例
if __name__ == "__main__":
api = ITickNGAPI(MY_TOKEN)
# Daily K‑lines (last 30 days)
df_daily = api.get_historical_klines("DANGCEM", k_type=8, limit=30)
if df_daily is not None:
print(df_daily.head())
# Optional: candlestick chart with mplfinance
import mplfinance as mpf
plot_df = df_daily.copy()
plot_df.set_index("Timestamp", inplace=True)
mpf.plot(
plot_df,
type='candle',
volume=True,
title='DANGCEM (NG) Daily',
ylabel='Price (NGN)',
figratio=(16, 9),
style='yahoo'
)
4. 重要说明(2026 版)
- 市场代码为
NG— 不再是NSENG。 - 认证现在使用普通的
token头部(不再使用Bearer api_key:secret)。 - 所有时间戳均为 UTC 毫秒级 Unix 时间戳。
- 免费层有速率限制 — 在生产环境中请添加
sleep或升级计划。 - 价格单位为 尼日利亚奈拉 (NGN)。
5. 总结与建议
将尼日利亚股票数据集成进来显然没有美国或中国市场那样即插即用,但一旦了解了其怪癖(市场代码变更、时间戳处理、速率限制),就可以应付自如。
关键要点
- 始终实现超时 + 重试机制。
- 正确转换时间戳(UTC → 您的目标时区)。
- 尽早使用 pandas —— 它让数据清洗和可视化更加轻松。
免责声明: 本文仅作技术参考,不构成投资建议。投资有风险。
官方文档
- (link placeholder)
GitHub 组织
- (link placeholder)
希望这能帮助在 2026 年尝试获取 NGX 数据的朋友!欢迎在评论中留下问题或分享您的经验。
祝您的项目顺利!