alphavantage-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Alpha 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
undefined
bash
undefined

Environment 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
undefined
ALPHAVANTAGE_API_KEY=your_api_key
undefined

Basic 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']})")
undefined
quote = get_quote("AAPL") print(f"AAPL: ${quote['05. price']} ({quote['10. change percent']})")
undefined

Using Python Package

使用Python包

python
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
python
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators

Time 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)
undefined
ti = TechIndicators(key=API_KEY, output_format='pandas') rsi, meta = ti.get_rsi(symbol='AAPL', interval='daily', time_period=14)
undefined

API Functions Reference

API功能参考

Stock Time Series

股票时间序列

FunctionDescriptionFree
TIME_SERIES_INTRADAY
1-60min intervals
TIME_SERIES_DAILY
Daily OHLCV
TIME_SERIES_DAILY_ADJUSTED
With splits/dividends⚠️ Premium
TIME_SERIES_WEEKLY
Weekly OHLCV
TIME_SERIES_MONTHLY
Monthly OHLCV
GLOBAL_QUOTE
Latest quote
SYMBOL_SEARCH
Search symbols
函数描述免费可用
TIME_SERIES_INTRADAY
1-60分钟间隔
TIME_SERIES_DAILY
每日开盘/最高/最低/收盘/成交量数据
TIME_SERIES_DAILY_ADJUSTED
含拆股/分红调整数据⚠️ 付费版
TIME_SERIES_WEEKLY
每周开盘/最高/最低/收盘/成交量数据
TIME_SERIES_MONTHLY
每月开盘/最高/最低/收盘/成交量数据
GLOBAL_QUOTE
最新报价
SYMBOL_SEARCH
标的代码搜索

Fundamental Data

基本面数据

FunctionDescriptionFree
OVERVIEW
Company overview
INCOME_STATEMENT
Income statements
BALANCE_SHEET
Balance sheets
CASH_FLOW
Cash flow statements
EARNINGS
Earnings history
EARNINGS_CALENDAR
Upcoming earnings
IPO_CALENDAR
Upcoming IPOs
函数描述免费可用
OVERVIEW
公司概况
INCOME_STATEMENT
利润表
BALANCE_SHEET
资产负债表
CASH_FLOW
现金流量表
EARNINGS
历史盈利数据
EARNINGS_CALENDAR
即将发布的财报
IPO_CALENDAR
即将进行的IPO

Forex

外汇

FunctionDescriptionFree
CURRENCY_EXCHANGE_RATE
Real-time rate
FX_INTRADAY
Intraday forex
FX_DAILY
Daily forex
FX_WEEKLY
Weekly forex
FX_MONTHLY
Monthly forex
函数描述免费可用
CURRENCY_EXCHANGE_RATE
实时汇率
FX_INTRADAY
日内外汇数据
FX_DAILY
每日外汇数据
FX_WEEKLY
每周外汇数据
FX_MONTHLY
每月外汇数据

Cryptocurrency

加密货币

FunctionDescriptionFree
CURRENCY_EXCHANGE_RATE
Crypto rate
DIGITAL_CURRENCY_DAILY
Daily crypto
DIGITAL_CURRENCY_WEEKLY
Weekly crypto
DIGITAL_CURRENCY_MONTHLY
Monthly crypto
函数描述免费可用
CURRENCY_EXCHANGE_RATE
加密货币汇率
DIGITAL_CURRENCY_DAILY
每日加密货币数据
DIGITAL_CURRENCY_WEEKLY
每周加密货币数据
DIGITAL_CURRENCY_MONTHLY
每月加密货币数据

Technical Indicators (50+)

技术指标(50+种)

CategoryIndicators
TrendSMA, EMA, WMA, DEMA, TEMA, KAMA, MAMA, T3, TRIMA
MomentumRSI, MACD, STOCH, WILLR, ADX, CCI, MFI, ROC, AROON, MOM
VolatilityBBANDS, ATR, NATR, TRANGE
VolumeOBV, AD, ADOSC
HilbertHT_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

经济指标

FunctionDescriptionFree
REAL_GDP
US GDP
CPI
Consumer Price Index
INFLATION
Inflation rate
UNEMPLOYMENT
Unemployment rate
FEDERAL_FUNDS_RATE
Fed funds rate
TREASURY_YIELD
Treasury yields
函数描述免费可用
REAL_GDP
美国GDP
CPI
消费者价格指数
INFLATION
通货膨胀率
UNEMPLOYMENT
失业率
FEDERAL_FUNDS_RATE
联邦基金利率
TREASURY_YIELD
美国国债收益率

Alpha Intelligence

Alpha智能分析

FunctionDescriptionFree
NEWS_SENTIMENT
AI sentiment analysis
TOP_GAINERS_LOSERS
Market movers
INSIDER_TRANSACTIONS
Insider trades⚠️ Premium
ANALYTICS_FIXED_WINDOW
Analytics⚠️ Premium
函数描述免费可用
NEWS_SENTIMENT
AI情绪分析
TOP_GAINERS_LOSERS
市场涨跌榜
INSIDER_TRANSACTIONS
内部交易数据⚠️ 付费版
ANALYTICS_FIXED_WINDOW
高级分析⚠️ 付费版

Rate Limits

调用频率限制

TierDailyPer MinutePrice
Free255$0
PremiumUnlimited75-1,200$49.99-$249.99/mo
Important: Rate limits are IP-based, not key-based.
套餐每日调用次数每分钟调用次数价格
免费版255$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']}")
undefined
data = get_daily_data("AAPL") latest = list(data.items())[0] print(f"{latest[0]}: 收盘价 ${latest[1]['4. close']}")
undefined

Task: 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}")
undefined
rsi = get_rsi("AAPL") latest_rsi = list(rsi.values())[0]["RSI"] print(f"AAPL RSI(14): {latest_rsi}")
undefined

Task: 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']}")
undefined
rate = get_forex_rate("USD", "EUR") print(f"USD/EUR: {rate['5. Exchange Rate']}")
undefined

Task: 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}")
undefined
btc = get_crypto_price("BTC") print(f"BTC: ${float(btc['price']):,.2f}")
undefined

Task: 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}]")
undefined
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}]")
undefined

Task: 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")
undefined
gdp = get_economic_indicator("REAL_GDP") cpi = get_economic_indicator("CPI") unemployment = get_economic_indicator("UNEMPLOYMENT") fed_rate = get_economic_indicator("FEDERAL_FUNDS_RATE")
undefined

Task: 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
  1. 缓存响应结果 - 数据不会频繁更新
  2. 使用精简输出模式 - 除非需要完整历史数据
  3. 合理批量调用 - 免费版每日25次限制严格
  4. 处理调用频率限制 - 检查响应中的"Note"字段
  5. 使用Pandas输出 - 配合alpha_vantage包使用
  6. 存储历史数据 - 避免重复获取相同数据

Premium Required

安装

  • Unlimited daily requests
  • Adjusted time series
  • Realtime US market data
  • 15-minute delayed data
  • Insider transactions
  • Advanced analytics
  • Priority support
bash
undefined

Best Practices

官方Python封装包

  1. Cache responses - Data doesn't change frequently
  2. Use compact outputsize - Unless you need full history
  3. Batch requests wisely - 25/day limit is strict
  4. Handle rate limits - Check for "Note" key in response
  5. Use pandas output - With alpha_vantage package
  6. Store historical data - Avoid re-fetching same data
pip install alpha_vantage pandas

Installation

如需异步支持

bash
undefined
pip install aiohttp
undefined

Official Python wrapper

结合Pandas使用

pip install alpha_vantage pandas
python
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
import pandas as pd

For async support

初始化Pandas输出模式

pip install aiohttp
undefined
ts = 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 pd
data, 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])
undefined

Get 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

参考资料

analysis = data.join([sma, rsi])
undefined

Related Skills

  • finnhub-api
    - Real-time quotes and news
  • twelvedata-api
    - More indicators, better rate limits
  • fmp-api
    - Fundamental analysis focus

References