From 6da48b66dd36c57fc7ca6a70a733fd42f3c8297f Mon Sep 17 00:00:00 2001 From: "bastien.migette" Date: Mon, 6 Oct 2025 12:15:22 +0200 Subject: [PATCH] Added macro economic analyst - 2 --- FRED_MACRO_INTEGRATION.md | 112 +++++++++++++++++- tradingagents/agents/__init__.py | 2 + .../agents/analysts/macro_analyst.py | 78 ++++++++++++ tradingagents/agents/utils/agent_utils.py | 5 + .../agents/utils/macro_data_tools.py | 82 +++++++++++++ tradingagents/graph/setup.py | 8 ++ tradingagents/graph/trading_graph.py | 13 +- 7 files changed, 293 insertions(+), 7 deletions(-) create mode 100644 tradingagents/agents/analysts/macro_analyst.py create mode 100644 tradingagents/agents/utils/macro_data_tools.py diff --git a/FRED_MACRO_INTEGRATION.md b/FRED_MACRO_INTEGRATION.md index 264d7730..07dc963b 100644 --- a/FRED_MACRO_INTEGRATION.md +++ b/FRED_MACRO_INTEGRATION.md @@ -1,7 +1,7 @@ # FRED API Macro Data Integration ## Summary -Added FRED (Federal Reserve Economic Data) API support to the TradingAgents vendor methods system for macroeconomic analysis. +Added FRED (Federal Reserve Economic Data) API support to the TradingAgents vendor methods system for macroeconomic analysis, including a new **Macro Analyst** agent. ## Files Added @@ -24,9 +24,22 @@ New module providing FRED API integration with the following functions: - **`get_fed_calendar_and_minutes(curr_date)`** - Federal Reserve meeting calendar and policy updates - **`get_macro_economic_summary(curr_date, lookback_days=90)`** - Complete macro economic analysis combining all components +### 2. `tradingagents/agents/analysts/macro_analyst.py` +New macro analyst agent that uses FRED API tools to analyze economic conditions: +- Analyzes Federal Reserve policy and economic indicators +- Evaluates inflation, employment, and growth trends +- Assesses Treasury yield curve and recession signals +- Provides market implications and trading considerations + +### 3. `tradingagents/agents/utils/macro_data_tools.py` +Tool wrapper functions for LangChain integration: +- **`get_economic_indicators(curr_date, lookback_days)`** - Comprehensive economic indicators +- **`get_yield_curve(curr_date)`** - Treasury yield curve with inversion analysis +- **`get_fed_calendar(curr_date)`** - Fed meeting calendar and policy updates + ## Files Modified -### 2. `tradingagents/dataflows/interface.py` +### 4. `tradingagents/dataflows/interface.py` Updated vendor routing system to include FRED macro data: **Added Imports:** @@ -71,6 +84,76 @@ VENDOR_LIST = [ }, ``` +### 5. `tradingagents/agents/__init__.py` +Added macro analyst to exports: +```python +from .analysts.macro_analyst import create_macro_analyst + +__all__ = [ + # ... existing exports ... + "create_macro_analyst", +] +``` + +### 6. `tradingagents/agents/utils/agent_utils.py` +Added macro tool imports: +```python +from tradingagents.agents.utils.macro_data_tools import ( + get_economic_indicators, + get_yield_curve, + get_fed_calendar +) +``` + +### 7. `tradingagents/graph/setup.py` +Added macro analyst option to graph setup: +```python +def setup_graph( + self, selected_analysts=["market", "social", "news", "fundamentals"] +): + """Set up and compile the agent workflow graph. + + Args: + selected_analysts (list): List of analyst types to include. Options are: + - "market": Market analyst + - "social": Social media analyst + - "news": News analyst + - "fundamentals": Fundamentals analyst + - "macro": Macro economic analyst # New! + """ + # ... existing analyst setup ... + + if "macro" in selected_analysts: + analyst_nodes["macro"] = create_macro_analyst( + self.quick_thinking_llm + ) + delete_nodes["macro"] = create_msg_delete() + tool_nodes["macro"] = self.tool_nodes["macro"] +``` + +### 8. `tradingagents/graph/trading_graph.py` +Added macro tools import and tool node: +```python +from tradingagents.agents.utils.agent_utils import ( + # ... existing imports ... + get_economic_indicators, + get_yield_curve, + get_fed_calendar +) + +def _create_tool_nodes(self) -> Dict[str, ToolNode]: + return { + # ... existing tool nodes ... + "macro": ToolNode( + [ + get_economic_indicators, + get_yield_curve, + get_fed_calendar, + ] + ), + } +``` + ## Configuration Required To use FRED API features, set the FRED API key via: @@ -92,6 +175,22 @@ To use FRED API features, set the FRED API key via: ## Usage Examples +### Enable Macro Analyst in Graph + +```python +from tradingagents.graph.trading_graph import TradingAgentsGraph + +# Create graph with macro analyst enabled +graph = TradingAgentsGraph( + selected_analysts=["market", "fundamentals", "macro"], # Include "macro" + debug=True, + config=your_config +) + +# Run analysis +result = graph.propagate("AAPL", "2025-10-06") +``` + ### Via Vendor Routing System ```python @@ -165,11 +264,12 @@ All functions return formatted markdown strings suitable for LLM analysis: Changes were made with minimal modifications to existing code: -1. ✅ **New file only** - `macro_utils.py` is a new addition -2. ✅ **Additive changes** - Only added new entries to existing dictionaries +1. ✅ **New files only** - `macro_utils.py`, `macro_analyst.py`, `macro_data_tools.py` are new additions +2. ✅ **Additive changes** - Only added new entries to existing dictionaries and imports 3. ✅ **No breaking changes** - Existing functionality unchanged -4. ✅ **Follows existing patterns** - Uses same vendor routing architecture as other data sources -5. ✅ **Consistent naming** - Follows existing naming conventions (`get_*` pattern) +4. ✅ **Follows existing patterns** - Uses same vendor routing and analyst architecture +5. ✅ **Consistent naming** - Follows existing naming conventions (`get_*`, `create_*_analyst` patterns) +6. ✅ **Optional feature** - Macro analyst is opt-in via `selected_analysts` parameter ## Testing diff --git a/tradingagents/agents/__init__.py b/tradingagents/agents/__init__.py index d84d9eb1..239cef4c 100644 --- a/tradingagents/agents/__init__.py +++ b/tradingagents/agents/__init__.py @@ -6,6 +6,7 @@ from .analysts.fundamentals_analyst import create_fundamentals_analyst from .analysts.market_analyst import create_market_analyst from .analysts.news_analyst import create_news_analyst from .analysts.social_media_analyst import create_social_media_analyst +from .analysts.macro_analyst import create_macro_analyst from .researchers.bear_researcher import create_bear_researcher from .researchers.bull_researcher import create_bull_researcher @@ -29,6 +30,7 @@ __all__ = [ "create_bull_researcher", "create_research_manager", "create_fundamentals_analyst", + "create_macro_analyst", "create_market_analyst", "create_neutral_debator", "create_news_analyst", diff --git a/tradingagents/agents/analysts/macro_analyst.py b/tradingagents/agents/analysts/macro_analyst.py new file mode 100644 index 00000000..e22f7dec --- /dev/null +++ b/tradingagents/agents/analysts/macro_analyst.py @@ -0,0 +1,78 @@ +from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder +import time +import json +from tradingagents.agents.utils.agent_utils import get_economic_indicators, get_yield_curve, get_fed_calendar +from tradingagents.dataflows.config import get_config + + +def create_macro_analyst(llm): + def macro_analyst_node(state): + current_date = state["trade_date"] + ticker = state["company_of_interest"] + company_name = state["company_of_interest"] + + tools = [ + get_economic_indicators, + get_yield_curve, + get_fed_calendar, + ] + + system_message = ( + "You are a macro economic analyst tasked with analyzing Federal Reserve data, economic indicators, and macroeconomic trends. " + "Your objective is to write a comprehensive report detailing current economic conditions, monetary policy implications, and their impact on financial markets. " + "Analyze key indicators such as:\n" + "- Federal Funds Rate and monetary policy trajectory\n" + "- Inflation indicators (CPI, PPI)\n" + "- Employment data (unemployment rate, payrolls)\n" + "- Treasury yield curve and inversion signals\n" + "- Economic growth indicators (GDP, PMI)\n" + "- Market volatility (VIX)\n\n" + "Provide detailed analysis of:\n" + "1. Current economic cycle positioning\n" + "2. Federal Reserve policy stance and likely direction\n" + "3. Inflation and employment trends\n" + "4. Yield curve implications for recession risk\n" + "5. Market implications and trading considerations\n\n" + "Use the available tools: `get_economic_indicators` for comprehensive economic data, " + "`get_yield_curve` for Treasury yields and inversion analysis, and `get_fed_calendar` for FOMC schedule and policy trajectory. " + "Make sure to provide detailed, actionable insights rather than generic summaries. " + "Append a Markdown table at the end summarizing key macro indicators and their implications." + ) + + prompt = ChatPromptTemplate.from_messages( + [ + ( + "system", + "You are a helpful AI assistant, collaborating with other assistants." + " Use the provided tools to progress towards answering the question." + " If you are unable to fully answer, that's OK; another assistant with different tools" + " will help where you left off. Execute what you can to make progress." + " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable," + " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop." + " You have access to the following tools: {tool_names}.\n{system_message}" + "For your reference, the current date is {current_date}. The company we want to look at is {ticker}", + ), + MessagesPlaceholder(variable_name="messages"), + ] + ) + + prompt = prompt.partial(system_message=system_message) + prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools])) + prompt = prompt.partial(current_date=current_date) + prompt = prompt.partial(ticker=ticker) + + chain = prompt | llm.bind_tools(tools) + + result = chain.invoke(state["messages"]) + + report = "" + + if len(result.tool_calls) == 0: + report = result.content + + return { + "messages": [result], + "macro_report": report, + } + + return macro_analyst_node diff --git a/tradingagents/agents/utils/agent_utils.py b/tradingagents/agents/utils/agent_utils.py index 6cf294a1..7155d9b2 100644 --- a/tradingagents/agents/utils/agent_utils.py +++ b/tradingagents/agents/utils/agent_utils.py @@ -19,6 +19,11 @@ from tradingagents.agents.utils.news_data_tools import ( get_insider_transactions, get_global_news ) +from tradingagents.agents.utils.macro_data_tools import ( + get_economic_indicators, + get_yield_curve, + get_fed_calendar +) def create_msg_delete(): def delete_messages(state): diff --git a/tradingagents/agents/utils/macro_data_tools.py b/tradingagents/agents/utils/macro_data_tools.py new file mode 100644 index 00000000..b5329ebb --- /dev/null +++ b/tradingagents/agents/utils/macro_data_tools.py @@ -0,0 +1,82 @@ +from typing import Annotated +from langchain_core.tools import tool + + +@tool +def get_economic_indicators( + curr_date: Annotated[str, "Current date in yyyy-mm-dd format"], + lookback_days: Annotated[int, "How many days to look back for data"] = 90, +): + """ + Retrieve comprehensive economic indicators report from FRED including: + - Federal Funds Rate + - Consumer Price Index (CPI) and Producer Price Index (PPI) + - Unemployment Rate and Nonfarm Payrolls + - GDP Growth Rate + - ISM Manufacturing PMI + - Consumer Confidence + - VIX (Market Volatility) + + Args: + curr_date (str): Current date in yyyy-mm-dd format + lookback_days (int): How many days to look back for data + + Returns: + str: Comprehensive economic indicators report with analysis + """ + from tradingagents.dataflows.interface import route_to_vendor + + result = route_to_vendor( + "get_economic_indicators", + curr_date=curr_date, + lookback_days=lookback_days + ) + return str(result) + + +@tool +def get_yield_curve( + curr_date: Annotated[str, "Current date in yyyy-mm-dd format"], +): + """ + Retrieve US Treasury yield curve data from FRED with inversion analysis. + Includes yields for 1M, 3M, 6M, 1Y, 2Y, 3Y, 5Y, 7Y, 10Y, 20Y, and 30Y maturities. + Provides 2Y-10Y spread analysis and yield curve interpretation. + + Args: + curr_date (str): Current date in yyyy-mm-dd format + + Returns: + str: Treasury yield curve data with analysis and recession signals + """ + from tradingagents.dataflows.interface import route_to_vendor + + result = route_to_vendor( + "get_yield_curve", + curr_date=curr_date + ) + return str(result) + + +@tool +def get_fed_calendar( + curr_date: Annotated[str, "Current date in yyyy-mm-dd format"], +): + """ + Retrieve Federal Reserve meeting calendar and recent policy updates. + Includes FOMC meeting schedule, recent Fed Funds rate history, + and key policy considerations. + + Args: + curr_date (str): Current date in yyyy-mm-dd format + + Returns: + str: Fed calendar, meeting schedule, and policy trajectory + """ + from tradingagents.dataflows.interface import route_to_vendor + + result = route_to_vendor( + "get_fed_calendar", + curr_date=curr_date + ) + return str(result) diff --git a/tradingagents/graph/setup.py b/tradingagents/graph/setup.py index b270ffc0..68838362 100644 --- a/tradingagents/graph/setup.py +++ b/tradingagents/graph/setup.py @@ -48,6 +48,7 @@ class GraphSetup: - "social": Social media analyst - "news": News analyst - "fundamentals": Fundamentals analyst + - "macro": Macro economic analyst """ if len(selected_analysts) == 0: raise ValueError("Trading Agents Graph Setup Error: no analysts selected!") @@ -85,6 +86,13 @@ class GraphSetup: delete_nodes["fundamentals"] = create_msg_delete() tool_nodes["fundamentals"] = self.tool_nodes["fundamentals"] + if "macro" in selected_analysts: + analyst_nodes["macro"] = create_macro_analyst( + self.quick_thinking_llm + ) + delete_nodes["macro"] = create_msg_delete() + tool_nodes["macro"] = self.tool_nodes["macro"] + # Create researcher and manager nodes bull_researcher_node = create_bull_researcher( self.quick_thinking_llm, self.bull_memory diff --git a/tradingagents/graph/trading_graph.py b/tradingagents/graph/trading_graph.py index 40cdff75..3e44db42 100644 --- a/tradingagents/graph/trading_graph.py +++ b/tradingagents/graph/trading_graph.py @@ -33,7 +33,10 @@ from tradingagents.agents.utils.agent_utils import ( get_news, get_insider_sentiment, get_insider_transactions, - get_global_news + get_global_news, + get_economic_indicators, + get_yield_curve, + get_fed_calendar ) from .conditional_logic import ConditionalLogic @@ -155,6 +158,14 @@ class TradingAgentsGraph: get_income_statement, ] ), + "macro": ToolNode( + [ + # Macroeconomic analysis tools + get_economic_indicators, + get_yield_curve, + get_fed_calendar, + ] + ), } def propagate(self, company_name, trade_date):