Skip to content

The agent engineering platform.

community: Add PolygonTickerNews Tool (#17808)

Virat Singh92e52e89ca43
diff --git a/docs/docs/integrations/tools/polygon.ipynb b/docs/docs/integrations/tools/polygon.ipynb
index 62b078d0d8..0349ac67f7 100644
--- a/docs/docs/integrations/tools/polygon.ipynb
+++ b/docs/docs/integrations/tools/polygon.ipynb
@@ -7,11 +7,11 @@
"id": "245a954a"
},
"source": [
- "# Polygon Stock Market API\n",
+ "# Polygon Stock Market API Tools\n",
"\n",
">[Polygon](https://polygon.io/) The Polygon.io Stocks API provides REST endpoints that let you query the latest market data from all US stock exchanges.\n",
"\n",
- "Use the ``PolygonAPIWrapper`` to get stock market data like the latest quote for a ticker."
+ "This notebook uses tools to get stock market data like the latest quote and news for a ticker from Polygon."
]
},
{
@@ -20,7 +20,8 @@
"id": "34bb5968",
"metadata": {
"id": "34bb5968",
- "is_executing": true
+ "is_executing": true,
+ "scrolled": true
},
"outputs": [],
"source": [
@@ -32,7 +33,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 24,
"id": "ac4910f8",
"metadata": {
"id": "ac4910f8",
@@ -41,43 +42,161 @@
"outputs": [],
"source": [
"from langchain_community.tools.polygon.last_quote import PolygonLastQuote\n",
+ "from langchain_community.tools.polygon.ticker_news import PolygonTickerNews\n",
"from langchain_community.utilities.polygon import PolygonAPIWrapper"
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 25,
+ "id": "8660b910-905b-46f3-9541-920b9fc3d4d6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "api_wrapper = PolygonAPIWrapper()\n",
+ "ticker = \"AAPL\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "347f6951-b383-4675-b116-9b7d16c1f505",
+ "metadata": {},
+ "source": [
+ "### Get latest quote for ticker"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 55,
"id": "84b8f773",
"metadata": {
"id": "84b8f773"
},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Tool output: {\"P\": 180.99, \"S\": 5, \"T\": \"AAPL\", \"X\": 11, \"i\": [604], \"p\": 180.98, \"q\": 31662815, \"s\": 2, \"t\": 1708445246516556649, \"x\": 21, \"y\": 1708445246516369924, \"z\": 3}\n"
+ ]
+ }
+ ],
"source": [
- "tool = PolygonLastQuote(api_wrapper=PolygonAPIWrapper())"
+ "# Get the last quote for ticker\n",
+ "last_quote_tool = PolygonLastQuote(api_wrapper=api_wrapper)\n",
+ "last_quote = last_quote_tool.run(ticker)\n",
+ "print(f\"Tool output: {last_quote}\")"
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 29,
"id": "068991a6",
"metadata": {
"id": "068991a6",
"outputId": "c5cdc6ec-03cf-4084-cc6f-6ae792d91d39"
},
+ "outputs": [],
+ "source": [
+ "import json\n",
+ "\n",
+ "# Convert the last quote response to JSON\n",
+ "last_quote = last_quote_tool.run(ticker)\n",
+ "last_quote_json = json.loads(last_quote)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "id": "174e2556-eb3e-48a4-bde6-9a3309fae9c9",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Latest price for AAPL is $180.74\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Print the latest price for ticker\n",
+ "latest_price = last_quote_json[\"p\"]\n",
+ "print(f\"Latest price for {ticker} is ${latest_price}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "04f1b612-f91f-471c-8264-9cc8c14bdaef",
+ "metadata": {},
+ "source": [
+ "### Get latest news for ticker"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 58,
+ "id": "024982db-1402-4bd7-9788-6cb369a9565d",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Tool output: [{\"id\": \"RckckqTS-K2zI6WRyycBB0HonfGLc2MPTQROWsbpKSA\", \"publisher\": {\"name\": \"The Motley Fool\", \"homepage_url\": \"https://www.fool.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/themotleyfool.svg\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/themotleyfool.ico\"}, \"title\": \"Should You Worry About Apple's Slowdown in China?\", \"author\": \"[email protected] (Adria Cimino)\", \"published_utc\": \"2024-02-20T15:10:00Z\", \"article_url\": \"https://www.fool.com/investing/2024/02/20/should-you-worry-about-apples-slowdown-in-china/\", \"tickers\": [\"AAPL\"], \"image_url\": \"https://g.foolcdn.com/editorial/images/765910/aapl.png\", \"description\": \"A local smartphone giant is gaining market share.\", \"keywords\": [\"investing\"]}, {\"id\": \"5goYCKw3ZsHlJYwN1XX8AJCyybZuvfJeoUz38SzlYBM\", \"publisher\": {\"name\": \"The Motley Fool\", \"homepage_url\": \"https://www.fool.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/themotleyfool.svg\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/themotleyfool.ico\"}, \"title\": \"Vanguard Total Stock Market ETF: Buy, Sell, or Hold?\", \"author\": \"[email protected] (Justin Pope)\", \"published_utc\": \"2024-02-20T12:30:00Z\", \"article_url\": \"https://www.fool.com/investing/2024/02/20/vanguard-total-stock-market-etf-buy-sell-or-hold/\", \"tickers\": [\"VTI\", \"AAPL\", \"MSFT\", \"GOOGL\", \"AMZN\", \"NVDA\", \"META\", \"TSLA\", \"GOOG\"], \"image_url\": \"https://g.foolcdn.com/editorial/images/765208/getty-buy-sell-hold-stocks-decide-ratings-analysts.jpg\", \"description\": \"This is the ultimate tool to diversify your portfolio.\", \"keywords\": [\"investing\"]}, {\"id\": \"F2nshszd6rBX-JJMHtbPuA325ZBizcq7iIJ7PBK_114\", \"publisher\": {\"name\": \"MarketWatch\", \"homepage_url\": \"https://www.marketwatch.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/marketwatch.svg\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/marketwatch.ico\"}, \"title\": \"Wall Street\\u2019s \\u2018mob psychology\\u2019 could fuel a dangerous stock meltup, warns top strategist\", \"author\": \"MarketWatch\", \"published_utc\": \"2024-02-20T12:20:00Z\", \"article_url\": \"https://www.marketwatch.com/story/wall-streets-mob-psychology-could-fuel-a-dangerous-stock-meltup-warns-top-strategist-fc8647c6\", \"tickers\": [\"NVDA\", \"GOOGL\", \"AMZN\", \"AAPL\", \"META\", \"MSFT\", \"NFLX\", \"TSLA\", \"COF\", \"DFS\", \"WMT\", \"VZIO\", \"HD\", \"PANW\", \"CZR\", \"SMCI\", \"OCGN\", \"NIO\", \"MARA\", \"AMD\", \"COIN\"], \"amp_url\": \"https://www.marketwatch.com/amp/story/wall-streets-mob-psychology-could-fuel-a-dangerous-stock-meltup-warns-top-strategist-fc8647c6\", \"image_url\": \"https://images.mktw.net/im-59050122/social\", \"description\": \"Ed Yardeni says giddy Wall Street analysts could be the undoing of this stock market.\"}, {\"id\": \"uvUtqCvuVV-wyCECL0DTIbHdqAtEgviJqSrPurvrqEQ\", \"publisher\": {\"name\": \"Zacks Investment Research\", \"homepage_url\": \"https://www.zacks.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/zacks.png\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/zacks.ico\"}, \"title\": \"Should Vanguard Mega Cap ETF (MGC) Be on Your Investing Radar?\", \"author\": \"Zacks Equity Research\", \"published_utc\": \"2024-02-20T11:20:07Z\", \"article_url\": \"https://www.zacks.com/stock/news/2228257/should-vanguard-mega-cap-etf-mgc-be-on-your-investing-radar\", \"tickers\": [\"MGC\", \"AMZN\", \"AAPL\", \"MSFT\", \"SPY\", \"IVV\"], \"amp_url\": \"https://www.zacks.com/amp/stock/news/2228257/should-vanguard-mega-cap-etf-mgc-be-on-your-investing-radar\", \"image_url\": \"https://staticx-tuner.zacks.com/images/default_article_images/default17.jpg\", \"description\": \"Style Box ETF report for MGC\"}, {\"id\": \"RRxHgtvw7_7Ql0QhUphMlzXdUjWhJbpZVjHqR7N5TCg\", \"publisher\": {\"name\": \"Zacks Investment Research\", \"homepage_url\": \"https://www.zacks.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/zacks.png\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/zacks.ico\"}, \"title\": \"Should Vanguard S&P 500 ETF (VOO) Be on Your Investing Radar?\", \"author\": \"Zacks Equity Research\", \"published_utc\": \"2024-02-20T11:20:06Z\", \"article_url\": \"https://www.zacks.com/stock/news/2228264/should-vanguard-sp-500-etf-voo-be-on-your-investing-radar\", \"tickers\": [\"VOO\", \"AMZN\", \"AAPL\", \"MSFT\", \"SPY\", \"IVV\"], \"amp_url\": \"https://www.zacks.com/amp/stock/news/2228264/should-vanguard-sp-500-etf-voo-be-on-your-investing-radar\", \"image_url\": \"https://staticx-tuner.zacks.com/images/default_article_images/default24.jpg\", \"description\": \"Style Box ETF report for VOO\"}, {\"id\": \"QBaNxnCVlXTHlVAChWRdM5RrWCD9f20qp6aUxfdxrEI\", \"publisher\": {\"name\": \"Zacks Investment Research\", \"homepage_url\": \"https://www.zacks.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/zacks.png\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/zacks.ico\"}, \"title\": \"Should Fidelity Nasdaq Composite Index ETF (ONEQ) Be on Your Investing Radar?\", \"author\": \"Zacks Equity Research\", \"published_utc\": \"2024-02-20T11:20:05Z\", \"article_url\": \"https://www.zacks.com/stock/news/2228269/should-fidelity-nasdaq-composite-index-etf-oneq-be-on-your-investing-radar\", \"tickers\": [\"ONEQ\", \"AMZN\", \"AAPL\", \"MSFT\", \"QQQ\", \"VUG\"], \"amp_url\": \"https://www.zacks.com/amp/stock/news/2228269/should-fidelity-nasdaq-composite-index-etf-oneq-be-on-your-investing-radar\", \"image_url\": \"https://staticx-tuner.zacks.com/images/default_article_images/default29.jpg\", \"description\": \"Style Box ETF report for ONEQ\"}, {\"id\": \"aVYhWKzOHm1Y8k8z9ka0xrCCI-tiUWYDdsrPuDFzG_g\", \"publisher\": {\"name\": \"The Motley Fool\", \"homepage_url\": \"https://www.fool.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/themotleyfool.svg\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/themotleyfool.ico\"}, \"title\": \"Apple Is Synonymous With iPhones, But Its Largest Gross Margin Comes From Somewhere Else Entirely\", \"author\": \"[email protected] (Neil Patel)\", \"published_utc\": \"2024-02-20T11:07:00Z\", \"article_url\": \"https://www.fool.com/investing/2024/02/20/apple-synonymous-iphones-devices-gross-margin/\", \"tickers\": [\"AAPL\"], \"image_url\": \"https://g.foolcdn.com/editorial/images/765917/aapl_revenue_bar.png\", \"description\": \"Investors need to pay attention to a budding segment.\", \"keywords\": [\"investing\"]}, {\"id\": \"6uW_52HjWOj3sKeCdPrqN4ZHmIbJAZxXV5naPVzjaHw\", \"publisher\": {\"name\": \"The Motley Fool\", \"homepage_url\": \"https://www.fool.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/themotleyfool.svg\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/themotleyfool.ico\"}, \"title\": \"Warren Buffett Has 51% of Berkshire Hathaway's $370 Billion Portfolio Invested in 2 Stocks\", \"author\": \"[email protected] (Trevor Jennewine)\", \"published_utc\": \"2024-02-20T10:45:00Z\", \"article_url\": \"https://www.fool.com/investing/2024/02/20/warren-buffett-51-portfolio-invested-in-2-stocks/\", \"tickers\": [\"AAPL\", \"KO\", \"BRK.A\", \"BRK.B\"], \"image_url\": \"https://g.foolcdn.com/editorial/images/765625/market-3.jpg\", \"description\": \"Warren Buffett's Berkshire Hathaway has more than half of its stock portfolio invested in Apple and Coca-Cola.\", \"keywords\": [\"investing\"]}, {\"id\": \"aE6I7jULkhZEsKWnVsRNUaPYNfsHBC89wARk4mf6iPQ\", \"publisher\": {\"name\": \"Investing.com\", \"homepage_url\": \"https://www.investing.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/investing.png\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/investing.ico\"}, \"title\": \"20-Year High Bullish Sentiment Meets Record Tech Allocation: Recipe for Disaster?\", \"author\": \"Investing.com\", \"published_utc\": \"2024-02-20T10:24:00Z\", \"article_url\": \"https://www.investing.com/analysis/20year-high-bullish-sentiment-meets-record-tech-allocation-recipe-for-disaster-200646188\", \"tickers\": [\"MSFT\", \"AAPL\", \"NVDA\", \"AMZN\", \"GOOGL\", \"META\"], \"amp_url\": \"https://m.investing.com/analysis/20year-high-bullish-sentiment-meets-record-tech-allocation-recipe-for-disaster-200646188?ampMode=1\", \"image_url\": \"https://i-invdn-com.investing.com/redesign/images/seo/investingcom_analysis_og.jpg\"}, {\"id\": \"EJIIij7T9dEbvogmzWS_P_1cLvVskocSSLrM3p2V_qE\", \"publisher\": {\"name\": \"Investing.com\", \"homepage_url\": \"https://www.investing.com/\", \"logo_url\": \"https://s3.polygon.io/public/assets/news/logos/investing.png\", \"favicon_url\": \"https://s3.polygon.io/public/assets/news/favicons/investing.ico\"}, \"title\": \"3 Wide-Moat Stocks Worth Buying in 2024\", \"author\": \"The Tokenist\", \"published_utc\": \"2024-02-20T07:09:00Z\", \"article_url\": \"https://www.investing.com/analysis/3-widemoat-stocks-worth-buying-in-2024-200646181\", \"tickers\": [\"KO\", \"GOOGL\", \"AAPL\", \"META\", \"AMZN\", \"MSFT\", \"NVDA\", \"AX\", \"QTWO\", \"ADBE\", \"CRM\"], \"amp_url\": \"https://m.investing.com/analysis/3-widemoat-stocks-worth-buying-in-2024-200646181?ampMode=1\", \"image_url\": \"https://i-invdn-com.investing.com/redesign/images/seo/investingcom_analysis_og.jpg\"}]\n"
+ ]
+ }
+ ],
+ "source": [
+ "ticker_news_tool = PolygonTickerNews(api_wrapper=api_wrapper)\n",
+ "ticker_news = ticker_news_tool.run(ticker)\n",
+ "print(f\"Tool output: {ticker_news}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 57,
+ "id": "dfd26ef6-2d92-483e-9780-484091bd3774",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Total news items: 10\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Convert the news response to JSON array\n",
+ "ticker_news_json = json.loads(ticker_news)\n",
+ "print(f\"Total news items: {len(ticker_news_json)}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 56,
+ "id": "dbbb4b43-1096-45f3-8000-45538b3c73ee",
+ "metadata": {},
"outputs": [
{
- "data": {
- "text/plain": [
- "{'results': {'P': 185.86, 'S': 1, 'T': 'AAPL', 'X': 11, 'i': [604], 'p': 185.81, 'q': 106551669, 's': 2, 't': 1705098436014023700, 'x': 12, 'y': 1705098436014009300, 'z': 3}}"
- ]
- },
- "execution_count": 1,
- "metadata": {},
- "output_type": "execute_result"
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Title: Should You Worry About Apple's Slowdown in China?\n",
+ "Description: A local smartphone giant is gaining market share.\n",
+ "Publisher: The Motley Fool\n",
+ "URL: https://www.fool.com/investing/2024/02/20/should-you-worry-about-apples-slowdown-in-china/\n"
+ ]
}
],
"source": [
- "tool.run(\"AAPL\")"
+ "# Inspect the first news item\n",
+ "news_item = ticker_news_json[0]\n",
+ "print(f\"Title: {news_item['title']}\")\n",
+ "print(f\"Description: {news_item['description']}\")\n",
+ "print(f\"Publisher: {news_item['publisher']['name']}\")\n",
+ "print(f\"URL: {news_item['article_url']}\")"
]
}
],
@@ -86,9 +205,9 @@
"provenance": []
},
"kernelspec": {
- "name": "venv",
+ "display_name": "Python (langchain)",
"language": "python",
- "display_name": "venv"
+ "name": "langchain"
},
"language_info": {
"codemirror_mode": {
@@ -100,7 +219,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.9.1"
+ "version": "3.9.18"
},
"vscode": {
"interpreter": {
diff --git a/libs/community/langchain_community/agent_toolkits/polygon/toolkit.py b/libs/community/langchain_community/agent_toolkits/polygon/toolkit.py
index 748c84c1ee..73cf95f684 100644
--- a/libs/community/langchain_community/agent_toolkits/polygon/toolkit.py
+++ b/libs/community/langchain_community/agent_toolkits/polygon/toolkit.py
@@ -2,7 +2,7 @@ from typing import List
from langchain_community.agent_toolkits.base import BaseToolkit
from langchain_community.tools import BaseTool
-from langchain_community.tools.polygon import PolygonLastQuote
+from langchain_community.tools.polygon import PolygonLastQuote, PolygonTickerNews
from langchain_community.utilities.polygon import PolygonAPIWrapper
@@ -18,7 +18,10 @@ class PolygonToolkit(BaseToolkit):
tools = [
PolygonLastQuote(
api_wrapper=polygon_api_wrapper,
- )
+ ),
+ PolygonTickerNews(
+ api_wrapper=polygon_api_wrapper,
+ ),
]
return cls(tools=tools)
diff --git a/libs/community/langchain_community/tools/__init__.py b/libs/community/langchain_community/tools/__init__.py
index 59ad157de5..58af2e95ac 100644
--- a/libs/community/langchain_community/tools/__init__.py
+++ b/libs/community/langchain_community/tools/__init__.py
@@ -510,6 +510,12 @@ def _import_polygon_tool_PolygonLastQuote() -> Any:
return PolygonLastQuote
+def _import_polygon_tool_PolygonTickerNews() -> Any:
+ from langchain_community.tools.polygon.ticker_news import PolygonTickerNews
+
+ return PolygonTickerNews
+
+
def _import_powerbi_tool_InfoPowerBITool() -> Any:
from langchain_community.tools.powerbi.tool import InfoPowerBITool
@@ -957,6 +963,8 @@ def __getattr__(name: str) -> Any:
return _import_plugin()
elif name == "PolygonLastQuote":
return _import_polygon_tool_PolygonLastQuote()
+ elif name == "PolygonTickerNews":
+ return _import_polygon_tool_PolygonTickerNews()
elif name == "InfoPowerBITool":
return _import_powerbi_tool_InfoPowerBITool()
elif name == "ListPowerBITool":
@@ -1141,6 +1149,7 @@ __all__ = [
"OpenWeatherMapQueryRun",
"PubmedQueryRun",
"PolygonLastQuote",
+ "PolygonTickerNews",
"RedditSearchRun",
"QueryCheckerTool",
"QueryPowerBITool",
diff --git a/libs/community/langchain_community/tools/polygon/__init__.py b/libs/community/langchain_community/tools/polygon/__init__.py
index acc8bc4ac7..b61740a8a2 100644
--- a/libs/community/langchain_community/tools/polygon/__init__.py
+++ b/libs/community/langchain_community/tools/polygon/__init__.py
@@ -1,7 +1,9 @@
"""Polygon IO tools."""
from langchain_community.tools.polygon.last_quote import PolygonLastQuote
+from langchain_community.tools.polygon.ticker_news import PolygonTickerNews
__all__ = [
"PolygonLastQuote",
+ "PolygonTickerNews",
]
diff --git a/libs/community/langchain_community/tools/polygon/ticker_news.py b/libs/community/langchain_community/tools/polygon/ticker_news.py
new file mode 100644
index 0000000000..9d858ebc8f
--- /dev/null
+++ b/libs/community/langchain_community/tools/polygon/ticker_news.py
@@ -0,0 +1,36 @@
+from typing import Optional, Type
+
+from langchain_core.callbacks import CallbackManagerForToolRun
+from langchain_core.pydantic_v1 import BaseModel
+from langchain_core.tools import BaseTool
+
+from langchain_community.utilities.polygon import PolygonAPIWrapper
+
+
+class Inputs(BaseModel):
+ """Inputs for Polygon's Ticker News API"""
+
+ query: str
+
+
+class PolygonTickerNews(BaseTool):
+ """Tool that gets the latest news for a given ticker from Polygon"""
+
+ mode: str = "get_ticker_news"
+ name: str = "polygon_ticker_news"
+ description: str = (
+ "A wrapper around Polygon's Ticker News API. "
+ "This tool is useful for fetching the latest news for a stock. "
+ "Input should be the ticker that you want to get the latest news for."
+ )
+ args_schema: Type[BaseModel] = Inputs
+
+ api_wrapper: PolygonAPIWrapper
+
+ def _run(
+ self,
+ query: str,
+ run_manager: Optional[CallbackManagerForToolRun] = None,
+ ) -> str:
+ """Use the Polygon API tool."""
+ return self.api_wrapper.run(self.mode, ticker=query)
diff --git a/libs/community/langchain_community/utilities/polygon.py b/libs/community/langchain_community/utilities/polygon.py
index bd7aa9964f..9c6c3e7511 100644
--- a/libs/community/langchain_community/utilities/polygon.py
+++ b/libs/community/langchain_community/utilities/polygon.py
@@ -39,8 +39,29 @@ class PolygonAPIWrapper(BaseModel):
return data.get("results", None)
+ def get_ticker_news(self, ticker: str) -> Optional[dict]:
+ """
+ Get the most recent news articles relating to a stock ticker symbol,
+ including a summary of the article and a link to the original source.
+ """
+ url = (
+ f"{POLYGON_BASE_URL}v2/reference/news?"
+ f"ticker={ticker}&"
+ f"apiKey={self.polygon_api_key}"
+ )
+ response = requests.get(url)
+ data = response.json()
+
+ status = data.get("status", None)
+ if status != "OK":
+ raise ValueError(f"API Error: {data}")
+
+ return data.get("results", None)
+
def run(self, mode: str, ticker: str) -> str:
if mode == "get_last_quote":
return json.dumps(self.get_last_quote(ticker))
+ elif mode == "get_ticker_news":
+ return json.dumps(self.get_ticker_news(ticker))
else:
raise ValueError(f"Invalid mode {mode} for Polygon API.")
diff --git a/libs/community/tests/unit_tests/tools/test_imports.py b/libs/community/tests/unit_tests/tools/test_imports.py
index 95fd431557..09e73983ef 100644
--- a/libs/community/tests/unit_tests/tools/test_imports.py
+++ b/libs/community/tests/unit_tests/tools/test_imports.py
@@ -85,6 +85,7 @@ EXPECTED_ALL = [
"OpenWeatherMapQueryRun",
"PubmedQueryRun",
"PolygonLastQuote",
+ "PolygonTickerNews",
"RedditSearchRun",
"QueryCheckerTool",
"QueryPowerBITool",
diff --git a/libs/community/tests/unit_tests/tools/test_public_api.py b/libs/community/tests/unit_tests/tools/test_public_api.py
index 1595dd4710..2758300011 100644
--- a/libs/community/tests/unit_tests/tools/test_public_api.py
+++ b/libs/community/tests/unit_tests/tools/test_public_api.py
@@ -87,6 +87,7 @@ _EXPECTED = [
"OpenWeatherMapQueryRun",
"PubmedQueryRun",
"PolygonLastQuote",
+ "PolygonTickerNews",
"RedditSearchRun",
"QueryCheckerTool",
"QueryPowerBITool",