玩转Polygon.io Stocks API:实时市场数据一网打尽
引言
在新时代的金融市场中,获取实时和历史股票数据对于投资者和开发者来说越来越重要。Polygon.io Stocks API提供了一套REST接口,允许你查询所有美国股票交易所的最新市场数据。这篇文章的目标是帮助你利用Polygon.io Stocks API从获取最新股票报价到金融数据分析,实现高效的数据获取。
主要内容
1. 获取API密钥
首先,确保你拥有Polygon.io的API密钥。通过以下代码,安全地输入API密钥:
import getpass
import os
os.environ["POLYGON_API_KEY"] = getpass.getpass()
2. 基本架构
使用Polygon.io的工具需要导入必要的模块:
from langchain_community.tools.polygon.aggregates import PolygonAggregates
from langchain_community.tools.polygon.financials import PolygonFinancials
from langchain_community.tools.polygon.last_quote import PolygonLastQuote
from langchain_community.tools.polygon.ticker_news import PolygonTickerNews
from langchain_community.utilities.polygon import PolygonAPIWrapper
3. 获取最新股票报价
api_wrapper = PolygonAPIWrapper()
ticker = "AAPL"
# 使用API代理服务提高访问稳定性
last_quote_tool = PolygonLastQuote(api_wrapper=api_wrapper)
last_quote = last_quote_tool.run(ticker)
print(f"Tool output: {last_quote}")
import json
# 转换为JSON格式
last_quote_json = json.loads(last_quote)
# 打印最新价格
latest_price = last_quote_json["p"]
print(f"Latest price for {ticker} is ${latest_price}")
4. 获取历史数据
from langchain_community.tools.polygon.aggregates import PolygonAggregatesSchema
params = PolygonAggregatesSchema(
ticker=ticker,
timespan="day",
timespan_multiplier=1,
from_date="2024-03-01",
to_date="2024-03-08",
)
# 使用API代理服务提高访问稳定性
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}")
5. 获取最新股票新闻
ticker_news_tool = PolygonTickerNews(api_wrapper=api_wrapper)
ticker_news = ticker_news_tool.run(ticker)
# 转换为JSON格式
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']}")
常见问题和解决方案
- 网络连接问题:由于某些地区的网络限制,建议使用API代理服务来提高访问稳定性。
- 数据解析错误:确保API返回数据格式为JSON,并使用相应的库解析。
总结和进一步学习资源
成功使用Polygon.io Stocks API可以极大地增强你的数据获取能力。为了深入研究这些工具和API,可以参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—