-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Refactor FinancialDatasetAPI integration and add configuration classes for API setup. #42
Open
anhquan075
wants to merge
2
commits into
virattt:main
Choose a base branch
from
anhquan075:refactor/make-a-class-to-use-the-financial-api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+326
−187
Open
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,74 +1,89 @@ | ||
from datetime import datetime | ||
|
||
from langchain_openai.chat_models import ChatOpenAI | ||
|
||
from agents.state import AgentState | ||
from tools.api import search_line_items, get_financial_metrics, get_insider_trades, get_market_cap, get_prices | ||
|
||
from datetime import datetime | ||
from tools.api.financial_dataset import ( | ||
FinancialDatasetAPI, | ||
) | ||
|
||
llm = ChatOpenAI(model="gpt-4o") | ||
|
||
|
||
def market_data_agent(state: AgentState): | ||
"""Responsible for gathering and preprocessing market data""" | ||
messages = state["messages"] | ||
data = state["data"] | ||
|
||
# Set default dates | ||
end_date = data["end_date"] or datetime.now().strftime('%Y-%m-%d') | ||
end_date = data["end_date"] or datetime.now().strftime("%Y-%m-%d") | ||
if not data["start_date"]: | ||
# Calculate 3 months before end_date | ||
end_date_obj = datetime.strptime(end_date, '%Y-%m-%d') | ||
start_date = end_date_obj.replace(month=end_date_obj.month - 3) if end_date_obj.month > 3 else \ | ||
end_date_obj.replace(year=end_date_obj.year - 1, month=end_date_obj.month + 9) | ||
start_date = start_date.strftime('%Y-%m-%d') | ||
end_date_obj = datetime.strptime(end_date, "%Y-%m-%d") | ||
start_date = ( | ||
end_date_obj.replace(month=end_date_obj.month - 3) | ||
if end_date_obj.month > 3 | ||
else end_date_obj.replace( | ||
year=end_date_obj.year - 1, month=end_date_obj.month + 9 | ||
) | ||
) | ||
start_date = start_date.strftime("%Y-%m-%d") | ||
else: | ||
start_date = data["start_date"] | ||
|
||
financial_api = FinancialDatasetAPI() | ||
|
||
# Get the historical price data | ||
prices = get_prices( | ||
ticker=data["ticker"], | ||
start_date=start_date, | ||
prices = financial_api.get_prices( | ||
ticker=data["ticker"], | ||
start_date=start_date, | ||
end_date=end_date, | ||
) | ||
|
||
# Get the financial metrics | ||
financial_metrics = get_financial_metrics( | ||
ticker=data["ticker"], | ||
report_period=end_date, | ||
period='ttm', | ||
financial_metrics = financial_api.get_financial_metrics( | ||
ticker=data["ticker"], | ||
report_period=end_date, | ||
period="ttm", | ||
limit=1, | ||
) | ||
|
||
# Get the insider trades | ||
insider_trades = get_insider_trades( | ||
ticker=data["ticker"], | ||
insider_trades = financial_api.get_insider_trades( | ||
ticker=data["ticker"], | ||
end_date=end_date, | ||
limit=5, | ||
) | ||
|
||
# Get the market cap | ||
market_cap = get_market_cap( | ||
market_cap = financial_api.get_market_cap( | ||
ticker=data["ticker"], | ||
) | ||
|
||
# Get the line_items | ||
financial_line_items = search_line_items( | ||
ticker=data["ticker"], | ||
line_items=["free_cash_flow", "net_income", "depreciation_and_amortization", "capital_expenditure", "working_capital"], | ||
period='ttm', | ||
financial_line_items = financial_api.search_line_items( | ||
ticker=data["ticker"], | ||
line_items=[ | ||
"free_cash_flow", | ||
"net_income", | ||
"depreciation_and_amortization", | ||
"capital_expenditure", | ||
"working_capital", | ||
], | ||
period="ttm", | ||
limit=2, | ||
) | ||
|
||
return { | ||
"messages": messages, | ||
"data": { | ||
**data, | ||
"prices": prices, | ||
"start_date": start_date, | ||
**data, | ||
"prices": prices, | ||
"start_date": start_date, | ||
"end_date": end_date, | ||
"financial_metrics": financial_metrics, | ||
"insider_trades": insider_trades, | ||
"market_cap": market_cap, | ||
"financial_line_items": financial_line_items, | ||
} | ||
} | ||
}, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
from abc import ABC, abstractmethod | ||
from typing import Any, Dict, Optional | ||
|
||
import requests | ||
from requests.exceptions import RequestException | ||
|
||
from .config import BaseAPIConfig | ||
|
||
|
||
class BaseAPIClient(ABC): | ||
"""Abstract base class for API clients.""" | ||
|
||
def __init__(self, config: BaseAPIConfig): | ||
self.config = config | ||
self.headers = self._get_headers() | ||
|
||
@abstractmethod | ||
def _get_headers(self) -> Dict[str, str]: | ||
"""Return headers required for API requests.""" | ||
pass | ||
|
||
@abstractmethod | ||
def _handle_response(self, response: requests.Response) -> Dict[str, Any]: | ||
"""Handle API response and return parsed data.""" | ||
pass | ||
|
||
def _get_base_url(self) -> str: | ||
"""Implementation of abstract method for base URL.""" | ||
return self.config.base_url | ||
|
||
def _make_request( | ||
self, | ||
endpoint: str, | ||
method: str = "GET", | ||
params: Optional[Dict[str, Any]] = None, | ||
json_data: Optional[Dict[str, Any]] = None, | ||
) -> Dict[str, Any]: | ||
"""Make HTTP request to the API with error handling.""" | ||
url = f"{self._get_base_url()}/{endpoint.lstrip('/')}" | ||
|
||
try: | ||
response = requests.request( | ||
method=method, | ||
url=url, | ||
headers=self.headers, | ||
params=params, | ||
json=json_data, | ||
) | ||
return self._handle_response(response) | ||
except RequestException as e: | ||
raise Exception(f"API request failed: {str(e)}") from e | ||
|
||
def _get_data_or_raise( | ||
self, response_data: Dict[str, Any], key: str, error_message: str | ||
) -> Any: | ||
"""Extract data from response or raise if not found.""" | ||
data = response_data.get(key) | ||
if not data: | ||
raise Exception(error_message) | ||
return data |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
3.9+ syntax is preferred, i.e.
data | { ... }
, rather than{ **data, ... }