关于 twelvedata-api
twelvedata-api 是通过 Twelve Data API 和 Python SDK 获取金融市场数据的技能,涵盖价格、历史序列、参考与基本面数据、技术指标及可用的实时流。
主要功能
- 01实时报价与历史 OHLCV 序列
- 02股票、外汇、加密货币、ETF 和指数数据
- 03基本面与参考数据接口
- 04100 多种技术指标
- 05批量查询多个代码
- 06WebSocket 价格流
适用场景
- 01获取报价或历史价格用于分析
- 02比较证券的基本面数据
- 03结合时间序列计算技术指标
- 04接收实时价格更新
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ adaptationio/ skrillz --skill twelvedata-api安装后在 Claude Code 中输入/twelvedata-api确认已加载。
附带文件references/ENDPOINTS.mdscripts/twelvedata_client.py
详细介绍
Twelve Data API 集成
全面的金融数据 API,提供股票、外汇、加密货币、ETF、指数和 100 多种技术指标,并提供出色的 Python SDK 支持。
快速开始
身份验证
# Environment variable (recommended)
export TWELVEDATA_API_KEY="your_api_key"
# Or in .env file
TWELVEDATA_API_KEY=your_api_key
基本用法(Python)
import requests
import os
API_KEY = os.getenv("TWELVEDATA_API_KEY")
BASE_URL = "https://api.twelvedata.com"
def get_quote(symbol: str) -> dict:
"""Get real-time quote for a symbol."""
response = requests.get(
f"{BASE_URL}/quote",
params={"symbol": symbol, "apikey": API_KEY}
)
return response.json()
# Example
quote = get_quote("AAPL")
print(f"AAPL: ${quote['close']} ({quote['percent_change']}%)")
使用官方 SDK
from twelvedata import TDClient
td = TDClient(apikey="your_api_key")
# Get time series
ts = td.time_series(
symbol="AAPL",
interval="1day",
outputsize=30
).as_pandas()
# Get quote
quote = td.quote(symbol="AAPL").as_json()
# Get with technical indicators
ts_with_indicators = td.time_series(
symbol="AAPL",
interval="1day",
outputsize=50
).with_sma(time_period=20).with_rsi().as_pandas()
API 端点参考
核心数据
| 端点 | 描述 | 积分 |
|---|---|---|
/quote | 实时行情 | 1 |
/price | 仅当前价格 | 1 |
/eod | 日终价格 | 1 |
/time_series | 历史 OHLCV | 1 |
/exchange_rate | 货币转换 | 1 |
参考数据
| 端点 | 描述 | 积分 |
|---|---|---|
/symbol_search | 搜索代码 | 1 |
/instruments | 列出所有金融工具 | 免费 |
/exchanges | 列出交易所 | 免费 |
/instrument_type | 列出类型 | 免费 |
/earliest_timestamp | 数据起始日期 | 免费 |
基本面数据
| 端点 | 描述 | 积分 |
|---|---|---|
/income_statement | 损益表 | 100 |
/balance_sheet | 资产负债表 | 100 |
/cash_flow | 现金流量 | 100 |
/earnings | 盈利历史 | 100 |
/earnings_calendar | 即将公布的财报 | 100 |
/dividends | 股息历史 | 1 |
/splits | 拆股历史 | 1 |
/statistics | 关键统计数据 | 100 |
/profile | 公司简介 | 100 |
技术指标(100 多种)
所有指标均消耗 1 个积分,并可与 time_series 一起获取:
趋势: SMA、EMA、WMA、DEMA、TEMA、KAMA、MAMA、T3、TRIMA、VWMA 动量: RSI、MACD、随机指标、Williams %R、ADX、CCI、MFI、ROC、AROON 波动率: 布林带、ATR、肯特纳通道、唐奇安通道 成交量: OBV、AD、ADOSC、VWAP
速率限制
| 套餐 | 每分钟调用次数 | 每日 | WebSocket |
|---|---|---|---|
| 免费 | 8 | 800 | 仅试用 |
| Grow($29) | 55-377 | 无限制 | ❌ |
| Pro($99) | 610-1597 | 无限制 | ✅ |
| Enterprise($329) | 2584+ | 无限制 | ✅ |
积分系统:
- 标准端点:每个代码消耗 1 个积分
- 基本面数据:每个代码消耗 100 个积分
- 批量请求:费用与单独请求相同
常见任务
任务:使用 Pandas 获取时间序列
from twelvedata import TDClient
import pandas as pd
td = TDClient(apikey=API_KEY)
def get_historical_data(symbol: str, days: int = 100) -> pd.DataFrame:
"""Get historical OHLCV data as DataFrame."""
ts = td.time_series(
symbol=symbol,
interval="1day",
outputsize=days
)
return ts.as_pandas()
# Example
df = get_historical_data("AAPL", 100)
print(df.head())
任务:使用多个指标进行技术分析
def get_technical_analysis(symbol: str) -> pd.DataFrame:
"""Get price data with technical indicators."""
ts = td.time_series(
symbol=symbol,
interval="1day",
outputsize=100
)
# Chain indicators
df = (ts
.with_sma(time_period=20)
.with_sma(time_period=50)
.with_rsi(time_period=14)
.with_macd()
.with_bbands()
.as_pandas()
)
return df
# Example
analysis = get_technical_analysis("AAPL")
任务:获取多个代码(批量)
def get_batch_quotes(symbols: list) -> dict:
"""Get quotes for multiple symbols efficiently."""
symbol_str = ",".join(symbols)
response = requests.get(
f"{BASE_URL}/quote",
params={
"symbol": symbol_str,
"apikey": API_KEY
}
)
return response.json()
# Example: Up to 120 symbols per request
quotes = get_batch_quotes(["AAPL", "MSFT", "GOOGL", "AMZN"])
任务:获取基本面数据
def get_fundamentals(symbol: str) -> dict:
"""Get comprehensive fundamental data."""
# Note: Each call costs 100 credits
profile = requests.get(
f"{BASE_URL}/profile",
params={"symbol": symbol, "apikey": API_KEY}
).json()
stats = requests.get(
f"{BASE_URL}/statistics",
params={"symbol": symbol, "apikey": API_KEY}
).json()
return {
"name": profile.get("name"),
"sector": profile.get("sector"),
"industry": profile.get("industry"),
"market_cap": stats.get("statistics", {}).get("valuations_metrics", {}).get("market_capitalization"),
"pe_ratio": stats.get("statistics", {}).get("valuations_metrics", {}).get("trailing_pe"),
"dividend_yield": stats.get("statistics", {}).get("dividends_and_splits", {}).get("dividend_yield")
}
任务:获取外汇汇率
def get_forex_rate(from_currency: str, to_currency: str) -> dict:
"""Get currency exchange rate."""
response = requests.get(
f"{BASE_URL}/exchange_rate",
params={
"symbol": f"{from_currency}/{to_currency}",
"apikey": API_KEY
}
)
return response.json()
# Example
rate = get_forex_rate("USD", "EUR")
print(f"USD/EUR: {rate['rate']}")
任务:获取加密货币数据
def get_crypto_price(symbol: str, exchange: str = "Binance") -> dict:
"""Get cryptocurrency price."""
response = requests.get(
f"{BASE_URL}/quote",
params={
"symbol": f"{symbol}/USD",
"exchange": exchange,
"apikey": API_KEY
}
)
return response.json()
# Example
btc = get_crypto_price("BTC")
print(f"BTC: ${btc['close']}")
任务:搜索代码
def search_symbols(query: str, show_plan: bool = False) -> list:
"""Search for stock/crypto symbols."""
params = {
"symbol": query,
"apikey": API_KEY
}
if show_plan:
params["show_plan"] = "true"
response = requests.get(f"{BASE_URL}/symbol_search", params=params)
return response.json().get("data", [])
# Example
results = search_symbols("Apple")
for r in results[:5]:
print(f"{r['symbol']}: {r['instrument_name']}")
WebSocket 实时流
from twelvedata import TDClient
td = TDClient(apikey=API_KEY)
def on_event(event):
"""Handle real-time price updates."""
print(f"{event['symbol']}: ${event['price']}")
# Create WebSocket (requires Pro plan)
ws = td.websocket(
symbols=["AAPL", "MSFT", "GOOGL"],
on_event=on_event
)
ws.connect()
ws.keep_alive()
错误处理
def safe_api_call(endpoint: str, params: dict) -> dict:
"""Make API call with error handling."""
params["apikey"] = API_KEY
try:
response = requests.get(f"{BASE_URL}/{endpoint}", params=params)
data = response.json()
# Check for API errors
if "status" in data and data["status"] == "error":
print(f"API Error: {data.get('message', 'Unknown error')}")
return {}
# Check remaining credits
credits_used = response.headers.get("api-credits-used")
credits_left = response.headers.get("api-credits-left")
if credits_left:
print(f"Credits remaining: {credits_left}")
return data
except Exception as e:
print(f"Request error: {e}")
return {}
免费版与高级版功能
免费版包含
- 每分钟 8 次 API 调用,每日 800 次
- 美国股票、外汇、加密货币
- 时间序列数据(日终)
- 所有技术指标
- 基础参考数据
- 1-2 年的日内历史数据
- 30 多年的每日历史数据
需要高级版
- 更高的速率限制
- 国际股票(Grow+)
- WebSocket 流(Pro+)
- 盘前/盘后市场数据(Pro+)
- 延长交易时段
- 共同基金和 ETF 明细(Enterprise)
- 无每日限制
最佳实践
- 使用批量请求 - 每次调用最多可请求 120 个代码
- 缓存参考数据 - 交易所和金融工具很少变动
- 使用 SDK 的 pandas 输出 - 更便于处理数据
- 组合指标 - 与 time_series 一起获取(总计 1 个积分)
- 监控积分 - 检查响应标头
- 使用合适的间隔 - 分析使用 1day,交易使用 1min
安装
# Python SDK with all features
pip install twelvedata[matplotlib,plotly]
# Basic installation
pip install twelvedata
# For WebSocket
pip install websocket-client
相关技能
finnhub-api- 侧重实时新闻alphavantage-api- 可替代的指标来源fmp-api- 侧重基本面分析
参考资料
评论
支持 Markdown