alphavantage-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAlpha Vantage API Integration
Alpha Vantage API 集成
Financial data API providing stocks, forex, crypto, technical indicators, fundamental data, economic indicators, and AI-powered news sentiment analysis.
该金融数据API提供股票、外汇、加密货币、技术指标、基本面数据、经济指标以及AI驱动的新闻情绪分析功能。
Quick Start
快速开始
Authentication
身份验证
bash
undefinedbash
undefinedEnvironment variable (recommended)
环境变量(推荐方式)
export ALPHAVANTAGE_API_KEY="your_api_key"
export ALPHAVANTAGE_API_KEY="your_api_key"
Or in .env file
或写入.env文件
ALPHAVANTAGE_API_KEY=your_api_key
undefinedALPHAVANTAGE_API_KEY=your_api_key
undefinedBasic Usage (Python)
Python基础用法
python
import requests
import os
API_KEY = os.getenv("ALPHAVANTAGE_API_KEY")
BASE_URL = "https://www.alphavantage.co/query"
def get_quote(symbol: str) -> dict:
"""Get real-time quote for a symbol."""
response = requests.get(BASE_URL, params={
"function": "GLOBAL_QUOTE",
"symbol": symbol,
"apikey": API_KEY
})
return response.json().get("Global Quote", {})python
import requests
import os
API_KEY = os.getenv("ALPHAVANTAGE_API_KEY")
BASE_URL = "https://www.alphavantage.co/query"
def get_quote(symbol: str) -> dict:
"""获取标的实时报价。"""
response = requests.get(BASE_URL, params={
"function": "GLOBAL_QUOTE",
"symbol": symbol,
"apikey": API_KEY
})
return response.json().get("Global Quote", {})Example
示例
quote = get_quote("AAPL")
print(f"AAPL: ${quote['05. price']} ({quote['10. change percent']})")
undefinedquote = get_quote("AAPL")
print(f"AAPL: ${quote['05. price']} ({quote['10. change percent']})")
undefinedUsing Python Package
使用Python包
python
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicatorspython
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicatorsTime series data
时间序列数据
ts = TimeSeries(key=API_KEY, output_format='pandas')
data, meta = ts.get_daily(symbol='AAPL', outputsize='compact')
ts = TimeSeries(key=API_KEY, output_format='pandas')
data, meta = ts.get_daily(symbol='AAPL', outputsize='compact')
Technical indicators
技术指标
ti = TechIndicators(key=API_KEY, output_format='pandas')
rsi, meta = ti.get_rsi(symbol='AAPL', interval='daily', time_period=14)
undefinedti = TechIndicators(key=API_KEY, output_format='pandas')
rsi, meta = ti.get_rsi(symbol='AAPL', interval='daily', time_period=14)
undefinedAPI Functions Reference
API功能参考
Stock Time Series
股票时间序列
| Function | Description | Free |
|---|---|---|
| 1-60min intervals | ✅ |
| Daily OHLCV | ✅ |
| With splits/dividends | ⚠️ Premium |
| Weekly OHLCV | ✅ |
| Monthly OHLCV | ✅ |
| Latest quote | ✅ |
| Search symbols | ✅ |
| 函数 | 描述 | 免费可用 |
|---|---|---|
| 1-60分钟间隔 | ✅ |
| 每日开盘/最高/最低/收盘/成交量数据 | ✅ |
| 含拆股/分红调整数据 | ⚠️ 付费版 |
| 每周开盘/最高/最低/收盘/成交量数据 | ✅ |
| 每月开盘/最高/最低/收盘/成交量数据 | ✅ |
| 最新报价 | ✅ |
| 标的代码搜索 | ✅ |
Fundamental Data
基本面数据
| Function | Description | Free |
|---|---|---|
| Company overview | ✅ |
| Income statements | ✅ |
| Balance sheets | ✅ |
| Cash flow statements | ✅ |
| Earnings history | ✅ |
| Upcoming earnings | ✅ |
| Upcoming IPOs | ✅ |
| 函数 | 描述 | 免费可用 |
|---|---|---|
| 公司概况 | ✅ |
| 利润表 | ✅ |
| 资产负债表 | ✅ |
| 现金流量表 | ✅ |
| 历史盈利数据 | ✅ |
| 即将发布的财报 | ✅ |
| 即将进行的IPO | ✅ |
Forex
外汇
| Function | Description | Free |
|---|---|---|
| Real-time rate | ✅ |
| Intraday forex | ✅ |
| Daily forex | ✅ |
| Weekly forex | ✅ |
| Monthly forex | ✅ |
| 函数 | 描述 | 免费可用 |
|---|---|---|
| 实时汇率 | ✅ |
| 日内外汇数据 | ✅ |
| 每日外汇数据 | ✅ |
| 每周外汇数据 | ✅ |
| 每月外汇数据 | ✅ |
Cryptocurrency
加密货币
| Function | Description | Free |
|---|---|---|
| Crypto rate | ✅ |
| Daily crypto | ✅ |
| Weekly crypto | ✅ |
| Monthly crypto | ✅ |
| 函数 | 描述 | 免费可用 |
|---|---|---|
| 加密货币汇率 | ✅ |
| 每日加密货币数据 | ✅ |
| 每周加密货币数据 | ✅ |
| 每月加密货币数据 | ✅ |
Technical Indicators (50+)
技术指标(50+种)
| Category | Indicators |
|---|---|
| Trend | SMA, EMA, WMA, DEMA, TEMA, KAMA, MAMA, T3, TRIMA |
| Momentum | RSI, MACD, STOCH, WILLR, ADX, CCI, MFI, ROC, AROON, MOM |
| Volatility | BBANDS, ATR, NATR, TRANGE |
| Volume | OBV, AD, ADOSC |
| Hilbert | HT_TRENDLINE, HT_SINE, HT_PHASOR, etc. |
| 类别 | 指标 |
|---|---|
| 趋势类 | SMA, EMA, WMA, DEMA, TEMA, KAMA, MAMA, T3, TRIMA |
| 动量类 | RSI, MACD, STOCH, WILLR, ADX, CCI, MFI, ROC, AROON, MOM |
| 波动率类 | BBANDS, ATR, NATR, TRANGE |
| 成交量类 | OBV, AD, ADOSC |
| 希尔伯特类 | HT_TRENDLINE, HT_SINE, HT_PHASOR, 等 |
Economic Indicators
经济指标
| Function | Description | Free |
|---|---|---|
| US GDP | ✅ |
| Consumer Price Index | ✅ |
| Inflation rate | ✅ |
| Unemployment rate | ✅ |
| Fed funds rate | ✅ |
| Treasury yields | ✅ |
| 函数 | 描述 | 免费可用 |
|---|---|---|
| 美国GDP | ✅ |
| 消费者价格指数 | ✅ |
| 通货膨胀率 | ✅ |
| 失业率 | ✅ |
| 联邦基金利率 | ✅ |
| 美国国债收益率 | ✅ |
Alpha Intelligence
Alpha智能分析
| Function | Description | Free |
|---|---|---|
| AI sentiment analysis | ✅ |
| Market movers | ✅ |
| Insider trades | ⚠️ Premium |
| Analytics | ⚠️ Premium |
| 函数 | 描述 | 免费可用 |
|---|---|---|
| AI情绪分析 | ✅ |
| 市场涨跌榜 | ✅ |
| 内部交易数据 | ⚠️ 付费版 |
| 高级分析 | ⚠️ 付费版 |
Rate Limits
调用频率限制
| Tier | Daily | Per Minute | Price |
|---|---|---|---|
| Free | 25 | 5 | $0 |
| Premium | Unlimited | 75-1,200 | $49.99-$249.99/mo |
Important: Rate limits are IP-based, not key-based.
| 套餐 | 每日调用次数 | 每分钟调用次数 | 价格 |
|---|---|---|---|
| 免费版 | 25 | 5 | $0 |
| 付费版 | 无限制 | 75-1200 | $49.99-$249.99/月 |
重要提示: 调用频率限制基于IP地址,而非API密钥。
Common Tasks
常见任务
Task: Get Daily Stock Data
任务:获取每日股票数据
python
def get_daily_data(symbol: str, full: bool = False) -> dict:
"""Get daily OHLCV data."""
response = requests.get(BASE_URL, params={
"function": "TIME_SERIES_DAILY",
"symbol": symbol,
"outputsize": "full" if full else "compact",
"apikey": API_KEY
})
return response.json().get("Time Series (Daily)", {})python
def get_daily_data(symbol: str, full: bool = False) -> dict:
"""获取每日开盘/最高/最低/收盘/成交量数据。"""
response = requests.get(BASE_URL, params={
"function": "TIME_SERIES_DAILY",
"symbol": symbol,
"outputsize": "full" if full else "compact",
"apikey": API_KEY
})
return response.json().get("Time Series (Daily)", {})Example
示例
data = get_daily_data("AAPL")
latest = list(data.items())[0]
print(f"{latest[0]}: Close ${latest[1]['4. close']}")
undefineddata = get_daily_data("AAPL")
latest = list(data.items())[0]
print(f"{latest[0]}: 收盘价 ${latest[1]['4. close']}")
undefinedTask: Get Technical Indicator
任务:获取技术指标
python
def get_rsi(symbol: str, period: int = 14) -> dict:
"""Get RSI indicator values."""
response = requests.get(BASE_URL, params={
"function": "RSI",
"symbol": symbol,
"interval": "daily",
"time_period": period,
"series_type": "close",
"apikey": API_KEY
})
return response.json().get("Technical Analysis: RSI", {})python
def get_rsi(symbol: str, period: int = 14) -> dict:
"""获取RSI指标数据。"""
response = requests.get(BASE_URL, params={
"function": "RSI",
"symbol": symbol,
"interval": "daily",
"time_period": period,
"series_type": "close",
"apikey": API_KEY
})
return response.json().get("Technical Analysis: RSI", {})Example
示例
rsi = get_rsi("AAPL")
latest_rsi = list(rsi.values())[0]["RSI"]
print(f"AAPL RSI(14): {latest_rsi}")
undefinedrsi = get_rsi("AAPL")
latest_rsi = list(rsi.values())[0]["RSI"]
print(f"AAPL RSI(14): {latest_rsi}")
undefinedTask: Get Company Overview
任务:获取公司概况
python
def get_company_overview(symbol: str) -> dict:
"""Get comprehensive company information."""
response = requests.get(BASE_URL, params={
"function": "OVERVIEW",
"symbol": symbol,
"apikey": API_KEY
})
data = response.json()
return {
"name": data.get("Name"),
"description": data.get("Description"),
"sector": data.get("Sector"),
"industry": data.get("Industry"),
"market_cap": data.get("MarketCapitalization"),
"pe_ratio": data.get("PERatio"),
"dividend_yield": data.get("DividendYield"),
"eps": data.get("EPS"),
"52_week_high": data.get("52WeekHigh"),
"52_week_low": data.get("52WeekLow"),
"beta": data.get("Beta")
}python
def get_company_overview(symbol: str) -> dict:
"""获取公司综合信息。"""
response = requests.get(BASE_URL, params={
"function": "OVERVIEW",
"symbol": symbol,
"apikey": API_KEY
})
data = response.json()
return {
"name": data.get("Name"),
"description": data.get("Description"),
"sector": data.get("Sector"),
"industry": data.get("Industry"),
"market_cap": data.get("MarketCapitalization"),
"pe_ratio": data.get("PERatio"),
"dividend_yield": data.get("DividendYield"),
"eps": data.get("EPS"),
"52_week_high": data.get("52WeekHigh"),
"52_week_low": data.get("52WeekLow"),
"beta": data.get("Beta")
}Task: Get Forex Rate
任务:获取外汇汇率
python
def get_forex_rate(from_currency: str, to_currency: str) -> dict:
"""Get currency exchange rate."""
response = requests.get(BASE_URL, params={
"function": "CURRENCY_EXCHANGE_RATE",
"from_currency": from_currency,
"to_currency": to_currency,
"apikey": API_KEY
})
return response.json().get("Realtime Currency Exchange Rate", {})python
def get_forex_rate(from_currency: str, to_currency: str) -> dict:
"""获取货币兑换汇率。"""
response = requests.get(BASE_URL, params={
"function": "CURRENCY_EXCHANGE_RATE",
"from_currency": from_currency,
"to_currency": to_currency,
"apikey": API_KEY
})
return response.json().get("Realtime Currency Exchange Rate", {})Example
示例
rate = get_forex_rate("USD", "EUR")
print(f"USD/EUR: {rate['5. Exchange Rate']}")
undefinedrate = get_forex_rate("USD", "EUR")
print(f"USD/EUR: {rate['5. Exchange Rate']}")
undefinedTask: Get Crypto Price
任务:获取加密货币价格
python
def get_crypto_price(symbol: str, market: str = "USD") -> dict:
"""Get cryptocurrency price."""
response = requests.get(BASE_URL, params={
"function": "CURRENCY_EXCHANGE_RATE",
"from_currency": symbol,
"to_currency": market,
"apikey": API_KEY
})
data = response.json().get("Realtime Currency Exchange Rate", {})
return {
"symbol": symbol,
"price": data.get("5. Exchange Rate"),
"last_updated": data.get("6. Last Refreshed")
}python
def get_crypto_price(symbol: str, market: str = "USD") -> dict:
"""获取加密货币价格。"""
response = requests.get(BASE_URL, params={
"function": "CURRENCY_EXCHANGE_RATE",
"from_currency": symbol,
"to_currency": market,
"apikey": API_KEY
})
data = response.json().get("Realtime Currency Exchange Rate", {})
return {
"symbol": symbol,
"price": data.get("5. Exchange Rate"),
"last_updated": data.get("6. Last Refreshed")
}Example
示例
btc = get_crypto_price("BTC")
print(f"BTC: ${float(btc['price']):,.2f}")
undefinedbtc = get_crypto_price("BTC")
print(f"BTC: ${float(btc['price']):,.2f}")
undefinedTask: Get News Sentiment
任务:获取新闻情绪分析
python
def get_news_sentiment(tickers: str = None, topics: str = None) -> list:
"""Get AI-powered news sentiment analysis."""
params = {
"function": "NEWS_SENTIMENT",
"apikey": API_KEY
}
if tickers:
params["tickers"] = tickers
if topics:
params["topics"] = topics
response = requests.get(BASE_URL, params=params)
return response.json().get("feed", [])python
def get_news_sentiment(tickers: str = None, topics: str = None) -> list:
"""获取AI驱动的新闻情绪分析数据。"""
params = {
"function": "NEWS_SENTIMENT",
"apikey": API_KEY
}
if tickers:
params["tickers"] = tickers
if topics:
params["topics"] = topics
response = requests.get(BASE_URL, params=params)
return response.json().get("feed", [])Example
示例
news = get_news_sentiment(tickers="AAPL")
for article in news[:3]:
sentiment = article.get("overall_sentiment_label", "N/A")
print(f"{article['title'][:50]}... [{sentiment}]")
undefinednews = get_news_sentiment(tickers="AAPL")
for article in news[:3]:
sentiment = article.get("overall_sentiment_label", "N/A")
print(f"{article['title'][:50]}... [{sentiment}]")
undefinedTask: Get Economic Indicators
任务:获取经济指标
python
def get_economic_indicator(indicator: str) -> dict:
"""Get US economic indicator data."""
response = requests.get(BASE_URL, params={
"function": indicator,
"apikey": API_KEY
})
return response.json()python
def get_economic_indicator(indicator: str) -> dict:
"""获取美国经济指标数据。"""
response = requests.get(BASE_URL, params={
"function": indicator,
"apikey": API_KEY
})
return response.json()Examples
示例
gdp = get_economic_indicator("REAL_GDP")
cpi = get_economic_indicator("CPI")
unemployment = get_economic_indicator("UNEMPLOYMENT")
fed_rate = get_economic_indicator("FEDERAL_FUNDS_RATE")
undefinedgdp = get_economic_indicator("REAL_GDP")
cpi = get_economic_indicator("CPI")
unemployment = get_economic_indicator("UNEMPLOYMENT")
fed_rate = get_economic_indicator("FEDERAL_FUNDS_RATE")
undefinedTask: Get Earnings Calendar
错误处理
python
def get_earnings_calendar(horizon: str = "3month") -> list:
"""Get upcoming earnings releases."""
import csv
from io import StringIO
response = requests.get(BASE_URL, params={
"function": "EARNINGS_CALENDAR",
"horizon": horizon, # 3month, 6month, 12month
"apikey": API_KEY
})
# Returns CSV format
reader = csv.DictReader(StringIO(response.text))
return list(reader)python
def safe_api_call(params: dict) -> dict:
"""带错误处理的API调用。"""
params["apikey"] = API_KEY
try:
response = requests.get(BASE_URL, params=params)
data = response.json()
# 检查调用频率限制
if "Note" in data:
print(f"调用频率限制提示: {data['Note']}")
return {}
# 检查错误信息
if "Error Message" in data:
print(f"API错误: {data['Error Message']}")
return {}
# 检查提示信息(通常是调用频率限制)
if "Information" in data:
print(f"提示信息: {data['Information']}")
return {}
return data
except Exception as e:
print(f"请求错误: {e}")
return {}Example
免费版与付费版功能对比
—
免费版包含
earnings = get_earnings_calendar()
for e in earnings[:5]:
print(f"{e['symbol']}: {e['reportDate']}")
undefined- 每日25次调用
- 每分钟5次调用
- 历史时间序列数据(20+年)
- 50+种技术指标
- 基本面数据
- 外汇与加密货币数据
- 经济指标
- 新闻情绪分析
Error Handling
需付费版支持
python
def safe_api_call(params: dict) -> dict:
"""Make API call with error handling."""
params["apikey"] = API_KEY
try:
response = requests.get(BASE_URL, params=params)
data = response.json()
# Check for rate limit
if "Note" in data:
print(f"Rate limit: {data['Note']}")
return {}
# Check for error message
if "Error Message" in data:
print(f"API Error: {data['Error Message']}")
return {}
# Check for information message (often rate limit)
if "Information" in data:
print(f"Info: {data['Information']}")
return {}
return data
except Exception as e:
print(f"Request error: {e}")
return {}- 无限制每日调用
- 调整后时间序列数据
- 美国市场实时数据
- 15分钟延迟数据
- 内部交易数据
- 高级分析功能
- 优先支持
Free vs Premium Features
最佳实践
Free Tier Includes
—
- 25 requests per day
- 5 requests per minute
- Historical time series (20+ years)
- 50+ technical indicators
- Fundamental data
- Forex and crypto
- Economic indicators
- News sentiment
- 缓存响应结果 - 数据不会频繁更新
- 使用精简输出模式 - 除非需要完整历史数据
- 合理批量调用 - 免费版每日25次限制严格
- 处理调用频率限制 - 检查响应中的"Note"字段
- 使用Pandas输出 - 配合alpha_vantage包使用
- 存储历史数据 - 避免重复获取相同数据
Premium Required
安装
- Unlimited daily requests
- Adjusted time series
- Realtime US market data
- 15-minute delayed data
- Insider transactions
- Advanced analytics
- Priority support
bash
undefinedBest Practices
官方Python封装包
- Cache responses - Data doesn't change frequently
- Use compact outputsize - Unless you need full history
- Batch requests wisely - 25/day limit is strict
- Handle rate limits - Check for "Note" key in response
- Use pandas output - With alpha_vantage package
- Store historical data - Avoid re-fetching same data
pip install alpha_vantage pandas
Installation
如需异步支持
bash
undefinedpip install aiohttp
undefinedOfficial Python wrapper
结合Pandas使用
pip install alpha_vantage pandas
python
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
import pandas as pdFor async support
初始化Pandas输出模式
pip install aiohttp
undefinedts = TimeSeries(key=API_KEY, output_format='pandas')
ti = TechIndicators(key=API_KEY, output_format='pandas')
Usage with Pandas
获取每日数据
python
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
import pandas as pddata, meta = ts.get_daily(symbol='AAPL', outputsize='compact')
Initialize with pandas output
获取指标数据
ts = TimeSeries(key=API_KEY, output_format='pandas')
ti = TechIndicators(key=API_KEY, output_format='pandas')
sma, _ = ti.get_sma(symbol='AAPL', interval='daily', time_period=20)
rsi, _ = ti.get_rsi(symbol='AAPL', interval='daily', time_period=14)
Get daily data
合并数据
data, meta = ts.get_daily(symbol='AAPL', outputsize='compact')
analysis = data.join([sma, rsi])
undefinedGet indicators
相关工具
sma, _ = ti.get_sma(symbol='AAPL', interval='daily', time_period=20)
rsi, _ = ti.get_rsi(symbol='AAPL', interval='daily', time_period=14)
- - 实时报价与新闻
finnhub-api - - 更多指标,更宽松的调用限制
twelvedata-api - - 专注基本面分析
fmp-api
Combine
参考资料
Related Skills
—
- - Real-time quotes and news
finnhub-api - - More indicators, better rate limits
twelvedata-api - - Fundamental analysis focus
fmp-api
—
References
—