技术背景介绍
Polygon.io 是一个提供 REST API 的平台,允许用户从所有美国股票交易所查询最新的市场数据。本文将介绍如何使用 Polygon.io API 获取股票市场数据,比如最新的报价、新闻及财务信息。
核心原理解析
Polygon.io 提供了多种 API 接口,如 PolygonAggregates
, PolygonFinancials
, PolygonLastQuote
和 PolygonTickerNews
。通过这些接口,我们可以方便地获取股票的最新市场数据、历史价格、新闻以及财务状况。
代码实现演示(重点)
我们将通过一些示例代码详细展示如何调用 Polygon.io API 来获取 AAPL(苹果公司)的最新数据。
1. 获取最新报价
import os
import json
import getpass
from langchain_community.tools.polygon.last_quote import PolygonLastQuote
from langchain_community.utilities.polygon import PolygonAPIWrapper
# 设置 API Key(建议从环境变量中读取)
os.environ["POLYGON_API_KEY"] = getpass.getpass(prompt="Polygon API Key: ")
# 初始化 Polygon API 包装器
api_wrapper = PolygonAPIWrapper(api_key=os.environ["POLYGON_API_KEY"])
ticker = "AAPL"
# 获取最新报价工具
last_quote_tool = PolygonLastQuote(api_wrapper=api_wrapper)
# 获取最新报价
last_quote = last_quote_tool.run(ticker)
print(f"Tool output: {last_quote}")
# 转换为 JSON 格式
last_quote_json = json.loads(last_quote)
latest_price = last_quote_json["p"]
print(f"Latest price for {ticker} is ${latest_price}")
输出示例:
Tool output: {"P": 170.5, "S": 2, "T": "AAPL", "X": 11, "i": [604], "p": 170.48, "q": 106666224, "s": 1, "t": 1709945992614283138, "x": 12, "y": 1709945992614268948, "z": 3}
Latest price for AAPL is $170.48
2. 获取历史价格(聚合数据)
from langchain_community.tools.polygon.aggregates import PolygonAggregates, PolygonAggregatesSchema
# 定义参数
params = PolygonAggregatesSchema(
ticker=ticker,
timespan="day",
timespan_multiplier=1,
from_date="2024-03-01",
to_date="2024-03-08",
)
# 获取聚合数据工具
aggregates_tool = PolygonAggregates(api_wrapper=api_wrapper)
# 获取历史价格
aggregates = aggregates_tool.run(tool_input=params.dict())
aggregates_json = json.loads(aggregates)
print(f"Total aggregates: {len(aggregates_json)}")
print(f"Aggregates: {aggregates_json}")
输出示例:
Total aggregates: 6
Aggregates: [{'v': 73450582.0, 'vw': 179.0322, 'o': 179.55, 'c': 179.66, 'h': 180.53, 'l': 177.38, 't': 1709269200000, 'n': 911077}, ...]
3. 获取最新新闻
from langchain_community.tools.polygon.ticker_news import PolygonTickerNews
# 获取新闻工具
ticker_news_tool = PolygonTickerNews(api_wrapper=api_wrapper)
# 获取新闻
ticker_news = ticker_news_tool.run(ticker)
ticker_news_json = json.loads(ticker_news)
print(f"Total news items: {len(ticker_news_json)}")
# 展示第一条新闻
news_item = ticker_news_json[0]
print(f"Title: {news_item['title']}")
print(f"Description: {news_item['description']}")
print(f"Publisher: {news_item['publisher']['name']}")
print(f"URL: {news_item['article_url']}")
输出示例:
Total news items: 10
Title: An AI surprise could fuel a 20% rally for the S&P 500 in 2024, says UBS
Description: If Gen AI causes a big productivity boost, stocks could see an unexpected rally this year, say UBS strategists.
Publisher: MarketWatch
URL: https://www.marketwatch.com/story/an-ai-surprise-could-fuel-a-20-rally-for-the-s-p-500-in-2024-says-ubs-1044d716
4. 获取财务信息
from langchain_community.tools.polygon.financials import PolygonFinancials
# 获取财务工具
financials_tool = PolygonFinancials(api_wrapper=api_wrapper)
# 获取财务数据
financials = financials_tool.run(ticker)
financials_json = json.loads(financials)
print(f"Total reporting periods: {len(financials_json)}")
# 打印最近报告期的财务数据
financial_data = financials_json[0]
print(f"Company name: {financial_data['company_name']}")
print(f"CIK: {financial_data['cik']}")
print(f"Fiscal period: {financial_data['fiscal_period']}")
print(f"End date: {financial_data['end_date']}")
print(f"Start date: {financial_data['start_date']}")
# 展示损益表数据
print(f"Income statement: {financial_data['financials']['income_statement']}")
输出示例:
Total reporting periods: 10
Company name: APPLE INC
CIK: 0000320193
Fiscal period: TTM
End date: 2023-12-30
Start date: 2022-12-31
Income statement: {'diluted_earnings_per_share': {'value': 6.42, 'unit': 'USD / shares', 'label': 'Diluted Earnings Per Share', 'order': 4300}, ...}
应用场景分析
Polygon.io 提供的 API 非常适合用于金融数据分析、量化交易、实时市场监控等场景。无论是个人投资者还是金融机构,都可以利用这些数据来做出更加明智的投资决策。
实践建议
- 确保 API Key 安全:在代码中不要直接硬编码 API Key,建议使用环境变量。
- 关注 API 限流:合理管理 API 调用频率,避免超出限额。
- 使用缓存:对于并不常变动的数据(如历史数据),可以适当使用缓存机制,提高查询效率。
结束语:如果遇到问题欢迎在评论区交流。
—END—