mirror of
https://github.com/hwchase17/langchain
synced 2024-11-11 19:11:02 +00:00
cd926ac3dd
**Description:** In this PR, I am adding a `PolygonFinancials` tool, which can be used to get financials data for a given ticker. The financials data is the fundamental data that is found in income statements, balance sheets, and cash flow statements of public US companies. **Twitter**: [@virattt](https://twitter.com/virattt)
89 lines
2.9 KiB
Python
89 lines
2.9 KiB
Python
"""
|
|
Util that calls several of Polygon's stock market REST APIs.
|
|
Docs: https://polygon.io/docs/stocks/getting-started
|
|
"""
|
|
import json
|
|
from typing import Dict, Optional
|
|
|
|
import requests
|
|
from langchain_core.pydantic_v1 import BaseModel, root_validator
|
|
from langchain_core.utils import get_from_dict_or_env
|
|
|
|
POLYGON_BASE_URL = "https://api.polygon.io/"
|
|
|
|
|
|
class PolygonAPIWrapper(BaseModel):
|
|
"""Wrapper for Polygon API."""
|
|
|
|
polygon_api_key: Optional[str] = None
|
|
|
|
@root_validator()
|
|
def validate_environment(cls, values: Dict) -> Dict:
|
|
"""Validate that api key in environment."""
|
|
polygon_api_key = get_from_dict_or_env(
|
|
values, "polygon_api_key", "POLYGON_API_KEY"
|
|
)
|
|
values["polygon_api_key"] = polygon_api_key
|
|
|
|
return values
|
|
|
|
def get_financials(self, ticker: str) -> Optional[dict]:
|
|
"""
|
|
Get fundamental financial data, which is found in balance sheets,
|
|
income statements, and cash flow statements for a given ticker.
|
|
"""
|
|
url = (
|
|
f"{POLYGON_BASE_URL}vX/reference/financials?"
|
|
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 get_last_quote(self, ticker: str) -> Optional[dict]:
|
|
"""Get the most recent National Best Bid and Offer (Quote) for a ticker."""
|
|
url = f"{POLYGON_BASE_URL}v2/last/nbbo/{ticker}?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 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_financials":
|
|
return json.dumps(self.get_financials(ticker))
|
|
elif 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.")
|