{
"cells": [
{
"cell_type": "markdown",
"id": "c67739d7-e46b-404c-bba3-5271b06ad2ee",
"metadata": {},
"source": [
"## Multi-Agent Financial Analysis System\n",
"#### A Collaborative Agentic AI for Market Insight Generation\n",
"
\n",
"\n",
"### Aliaksei Matsarski,Ian Rebmann – Team 6\n",
"### AAI-520-03 – Natural Language Processing and GenAI\n",
"### Instructor: Mirsardar Esnaeilli, Ph.D\n",
"### Shiley-Marcos School of Engineering, University of San Diego\n",
"### October 20, 2025\n"
]
},
{
"cell_type": "markdown",
"id": "6d64badb-1b22-43a5-a680-d960c4c7b78e",
"metadata": {},
"source": [
"## 1. Overview"
]
},
{
"cell_type": "markdown",
"id": "de32ae6a-90c2-42c7-9ed6-712c37b3f11c",
"metadata": {},
"source": [
"This notebook implements a Multi-Agent Financial Analysis System powered by agentic AI. It orchestrates specialized LLM agents to analyze market news, earnings reports, and stock data, producing structured, explainable investment insights.\n",
"Unlike traditional single-pipeline systems, this framework enables reasoning, task routing, self-critique, and iterative refinement — mirroring professional financial research workflows."
]
},
{
"cell_type": "markdown",
"id": "fa74af42-3265-46f1-82b9-7524e6290eb3",
"metadata": {},
"source": [
"## 2. LLM Initialization"
]
},
{
"cell_type": "markdown",
"id": "410834a2-5b5c-404d-8592-5499a73d473f",
"metadata": {},
"source": [
"Initializes the OpenAI-compatible ChatOpenAI model and environment configuration.\n",
"This step defines model parameters (e.g., temperature, model name) and API keys. It ensures reproducibility and sets up the base reasoning component shared by all agents."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8bad6079-aa26-4c61-a43e-bf2897ab51ed",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from langchain_openai import ChatOpenAI\n",
"\n",
"def init_main_model(llm_model_name: str):\n",
" openai_api_key = os.getenv(\"openai_api_key\")\n",
" llm = ChatOpenAI(api_key=openai_api_key, model=llm_model_name, temperature=0)\n",
"\n",
" return llm"
]
},
{
"cell_type": "markdown",
"id": "1449d0e8-0ffd-4f07-b721-08695d31f52e",
"metadata": {},
"source": [
"## 3. Agents Overview"
]
},
{
"cell_type": "markdown",
"id": "3afebe1d-ab88-4430-8c4a-d752a542b74d",
"metadata": {},
"source": [
"### 3.1 News Agent"
]
},
{
"cell_type": "markdown",
"id": "81ab4759-6c93-414b-b120-5cefa08bd5bb",
"metadata": {},
"source": [
"Focuses on market-moving catalysts.\n",
"\n",
"- Integrates web search (via DuckDuckGo or custom search_news_tool) to retrieve current headlines.\n",
"\n",
"- Summarizes sentiment and relevance using an LLM prompt template.\n",
"\n",
"- Outputs structured findings that downstream agents can interpret.\n",
"\n",
"Tools used:\n",
"\n",
"- duckduckgo_search for headline discovery\n",
"\n",
"- langchain.tools for tool registration\n",
"\n",
"- ChatPromptTemplate for templated prompts"
]
},
{
"cell_type": "markdown",
"id": "7d8be7ab-f439-4734-90b9-05fec56a84b7",
"metadata": {},
"source": [
"#### News Agent Tools"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "81c3d2f7-679c-4862-93bf-1efb2ed9122f",
"metadata": {},
"outputs": [],
"source": [
"from langchain.tools import tool\n",
"try:\n",
" from duckduckgo_search import DDGS\n",
"except Exception:\n",
" DDGS = None\n",
"\n",
"@tool(\"search_news\", return_direct=False)\n",
"def search_news_tool(query: str, max_results: int = 5) -> str:\n",
" \"\"\"\n",
" Search latest headlines & snippets relevant to a stock or topic.\n",
" Uses duckduckgo_search as a simple public news proxy.\n",
" Returns a concise, newline-separated list of 'title — url'.\n",
" \"\"\"\n",
" if DDGS is None:\n",
" return (\"duckduckgo_search not installed. \"\n",
" \"Install with `pip install duckduckgo-search` \"\n",
" \"or replace this tool with your news API.\")\n",
" items = []\n",
" with DDGS() as ddgs:\n",
" for r in ddgs.news(query, timelimit=\"7d\", max_results=max_results):\n",
" title = r.get(\"title\", \"\")[:160]\n",
" url = r.get(\"url\", \"\")\n",
" if title and url:\n",
" items.append(f\"{title} — {url}\")\n",
" if not items:\n",
" return \"No recent news found.\"\n",
" return \"\\n\".join(items)"
]
},
{
"cell_type": "markdown",
"id": "44a7b828-de97-4fbd-a24b-6a7c8fad6e5b",
"metadata": {},
"source": [
"#### News Agent"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7a262a48-05f4-4fa1-b716-1f7d137e0f76",
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import AgentExecutor, create_tool_calling_agent\n",
"from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from agents.news_agent.tools import search_news_tool\n",
"\n",
"news_agent_system = (\n",
" \"You are a News Analyst. Use the search tool to gather 5-8 recent, credible items.\"\n",
" \"Synthesize themes, risks, catalysts, and sentiment for investors. Output a concise\"\n",
" \"markdown summary with bullet points and 1-2 short citations (URLs).\"\n",
")\n",
"\n",
"def create_news_agent(model) -> AgentExecutor:\n",
"\n",
" prompt = ChatPromptTemplate.from_messages(\n",
" [\n",
" (\"system\", news_agent_system),\n",
" (\"human\", \"{input}\"),\n",
" MessagesPlaceholder(\"agent_scratchpad\"),\n",
" ]\n",
" )\n",
" agent = create_tool_calling_agent(llm=model, tools=[search_news_tool], prompt=prompt)\n",
"\n",
" return AgentExecutor(agent=agent, tools=[search_news_tool], verbose=False, handle_parsing_errors=True)"
]
},
{
"cell_type": "markdown",
"id": "7fc6b0f0-3bd7-4e3a-9f2d-30955d7ef27f",
"metadata": {},
"source": [
"### 3.2 Earnings Agent"
]
},
{
"cell_type": "markdown",
"id": "d15a8b60-09cd-428e-a4e3-4606e30386dd",
"metadata": {},
"source": [
"Analyzes corporate earnings reports and financial statements.\n",
"\n",
"- Parses key performance indicators (revenue, EPS, margins).\n",
"\n",
"- Compares against consensus estimates.\n",
"\n",
"- Produces a concise summary and sentiment classification (positive/neutral/negative).\n",
"\n",
"Uses similar modular design — each step encapsulated in a callable tool or agent chain."
]
},
{
"cell_type": "markdown",
"id": "529197ba-1e17-4b74-9a99-c4718ad25ee9",
"metadata": {},
"source": [
"#### Earnings Agent Tools"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "12b1149d-4c61-46f5-85a9-02920ed9e148",
"metadata": {},
"outputs": [],
"source": [
"from langchain.tools import tool\n",
"import yfinance as yf\n",
"import datetime as dt\n",
"\n",
"@tool(\"fetch_earnings\", return_direct=False)\n",
"def fetch_earnings_tool(ticker: str) -> str:\n",
" \"\"\"\n",
" Fetch upcoming and recent earnings info via yfinance.\n",
" Returns a concise summary (dates + surprises if available).\n",
" \"\"\"\n",
" tk = yf.Ticker(ticker)\n",
" lines = [f\"EARNINGS SNAPSHOT for {ticker.upper()}\"]\n",
"\n",
" # Upcoming earnings (earnings_dates includes future dates)\n",
" try:\n",
" ed = tk.earnings_dates # DataFrame if available\n",
" if ed is not None and not ed.empty:\n",
" # Take the next upcoming date and last reported\n",
" ed_sorted = ed.sort_index()\n",
" upcoming = ed_sorted[ed_sorted.index >= dt.datetime.now().date()]\n",
" last = ed_sorted[ed_sorted.index < dt.datetime.now().date()]\n",
" if not upcoming.empty:\n",
" lines.append(f\"Upcoming: {upcoming.index[0].strftime('%Y-%m-%d')}\")\n",
" if not last.empty:\n",
" # Try EPS surprise columns if present\n",
" row = last.iloc[-1]\n",
" surprise = None\n",
" for k in [\"EPS Surprise %\", \"Surprise(%)\", \"epssurprisepct\", \"epssurprisepercent\"]:\n",
" if k in row and row[k] is not None:\n",
" surprise = row[k]\n",
" break\n",
" lines.append(\n",
" f\"Last reported: {last.index[-1].strftime('%Y-%m-%d')}\"\n",
" + (f\", EPS surprise: {surprise}\" if surprise is not None else \"\")\n",
" )\n",
" else:\n",
" lines.append(\"No earnings_dates available.\")\n",
" except Exception as e:\n",
" lines.append(f\"earnings_dates unavailable: {e}\")\n",
"\n",
" # Quarterly financials (very high-level)\n",
" try:\n",
" qf = tk.quarterly_financials\n",
" if qf is not None and not qf.empty:\n",
" cols = list(qf.columns)\n",
" if cols:\n",
" last_q = cols[0]\n",
" revenue = qf.loc[\"Total Revenue\", last_q] if \"Total Revenue\" in qf.index else None\n",
" gross_profit = qf.loc[\"Gross Profit\", last_q] if \"Gross Profit\" in qf.index else None\n",
" lines.append(f\"Last quarter ({last_q.date()}): Revenue={revenue}, GrossProfit={gross_profit}\")\n",
" except Exception:\n",
" pass\n",
"\n",
" return \"\\n\".join(lines)"
]
},
{
"cell_type": "markdown",
"id": "89951220-c05e-4374-9bc8-f640d29e2fc0",
"metadata": {},
"source": [
"#### Earnings Agent"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9bf7d226-2885-42e1-bd4a-064192ba6513",
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import AgentExecutor, create_tool_calling_agent\n",
"from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from agents.earnings_agent.tools import fetch_earnings_tool\n",
"\n",
"earnings_agent_system = (\n",
" \"You are an Earnings Analyst. Use the earnings tool to summarize the latest and upcoming\"\n",
" \"earnings information (dates, surprises if available) and key line items. Provide a \"\n",
" \"short view on momentum and watchouts. Output concise markdown.\"\n",
")\n",
"\n",
"def create_earnings_agent(model) -> AgentExecutor:\n",
"\n",
" prompt = ChatPromptTemplate.from_messages(\n",
" [\n",
" (\"system\", earnings_agent_system),\n",
" (\"human\", \"{input}\"),\n",
" MessagesPlaceholder(\"agent_scratchpad\"),\n",
" ]\n",
" )\n",
" agent = create_tool_calling_agent(llm=model, tools=[fetch_earnings_tool], prompt=prompt)\n",
"\n",
" return AgentExecutor(agent=agent, tools=[fetch_earnings_tool], verbose=False, handle_parsing_errors=True)"
]
},
{
"cell_type": "markdown",
"id": "092e5091-ae1b-44f7-88f4-600499f87b14",
"metadata": {},
"source": [
"### 3.3 Market Agent"
]
},
{
"cell_type": "markdown",
"id": "1fb285c6-6b32-4b2e-a7d1-b20a8f4ce7d6",
"metadata": {},
"source": [
"Integrates quantitative signals (stock trends, volatility, RSI, etc.) with textual insights from the other agents.\n",
"Performs reasoning over structured market data and qualitative narratives to identify actionable opportunities."
]
},
{
"cell_type": "markdown",
"id": "61170e19-91b1-480c-900b-45dbb009e52a",
"metadata": {},
"source": [
"#### Market Agent Tools"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1f9aef88-159c-4804-a537-d7309cd06fcc",
"metadata": {},
"outputs": [],
"source": [
"from langchain.tools import tool\n",
"import yfinance as yf\n",
"import datetime as dt\n",
"\n",
"@tool(\"fetch_market_snapshot\", return_direct=False)\n",
"def fetch_market_snapshot_tool(ticker: str) -> str:\n",
" \"\"\"\n",
" Pulls basic market snapshot with yfinance: price, change, volume, valuation.\n",
" Returns a compact textual snapshot.\n",
" \"\"\"\n",
" tk = yf.Ticker(ticker)\n",
" info = {}\n",
" try:\n",
" price = tk.fast_info.last_price\n",
" prev_close = tk.fast_info.previous_close\n",
" change = None\n",
" if price is not None and prev_close:\n",
" change = (price - prev_close) / prev_close * 100\n",
" info.update({\n",
" \"price\": price, \"prev_close\": prev_close, \"pct_change\": change,\n",
" \"market_cap\": tk.fast_info.market_cap, \"volume\": tk.fast_info.last_volume,\n",
" \"currency\": tk.fast_info.currency\n",
" })\n",
" except Exception as e:\n",
" return f\"Market snapshot failed: {e}\"\n",
"\n",
" lines = [f\"MARKET SNAPSHOT for {ticker.upper()}\"]\n",
" lines.append(f\"Price: {info.get('price')} {info.get('currency')}\")\n",
" if info.get(\"pct_change\") is not None:\n",
" lines.append(f\"Day change: {info['pct_change']:.2f}%\")\n",
" lines.append(f\"Market Cap: {info.get('market_cap')}\")\n",
" lines.append(f\"Volume: {info.get('volume')}\")\n",
" return \"\\n\".join(lines)"
]
},
{
"cell_type": "markdown",
"id": "b97c1c85-036a-4298-a602-469c0b5bae86",
"metadata": {},
"source": [
"#### Market Agent"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "242fb17f-be7c-4e19-be55-8c56007fd358",
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import AgentExecutor, create_tool_calling_agent\n",
"from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from agents.market_agent.tools import fetch_market_snapshot_tool\n",
"from pathlib import Path\n",
"import yaml\n",
"\n",
"market_agent_system = (\n",
" \"You are a Market & Valuation Analyst. Use the market snapshot tool to extract current\" \n",
" \"trading context and discuss short-term technicals/flow and high-level valuation notes.\" \n",
" \"Output concise markdown.\"\n",
")\n",
"\n",
"\n",
"def create_market_agent(model) -> AgentExecutor:\n",
"\n",
" prompt = ChatPromptTemplate.from_messages(\n",
" [\n",
" (\"system\", market_agent_system),\n",
" (\"human\", \"{input}\"),\n",
" MessagesPlaceholder(\"agent_scratchpad\"),\n",
" ]\n",
" )\n",
" agent = create_tool_calling_agent(llm=model, tools=[fetch_market_snapshot_tool], prompt=prompt)\n",
"\n",
" return AgentExecutor(agent=agent, tools=[fetch_market_snapshot_tool], verbose=False, handle_parsing_errors=True)"
]
},
{
"cell_type": "markdown",
"id": "4373c80a-c833-4dd8-8083-ef69a4edf871",
"metadata": {},
"source": [
"## 4. Workflow"
]
},
{
"cell_type": "markdown",
"id": "edebefcd-0aa9-435d-874c-2eb04c296468",
"metadata": {},
"source": [
"This section defines the coordination logic and workflow orchestration:\n",
"\n",
"- Supervisor Agent routes queries to relevant specialists (news, earnings, or market).\n",
"\n",
"- Tool execution is dynamically selected based on the input context.\n",
"\n",
"- Memory and reflection allow the system to carry forward past reasoning chains.\n",
"\n",
"- Prompts are defined using ChatPromptTemplate, and YAML configuration supports modular editing."
]
},
{
"cell_type": "markdown",
"id": "ab795dd3-686e-412d-9257-5ba2e3200d21",
"metadata": {},
"source": [
"### 4.1 Graph Nodes"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "206e9a1d-f2da-4af4-a39e-d6dc76ba2524",
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import AgentExecutor\n",
"from workflow.graph_state import GraphState\n",
"\n",
"news_user_prompt = \"Research recent news for {ticker}. Focus on price-moving catalysts.\"\n",
"earnings_user_prompt = \"Analyze earnings for {ticker}. Summarize last and upcoming earnings. Use the tool.\"\n",
"market_user_prompt = \"Provide a market snapshot for {ticker}. Use the tool.\"\n",
"\n",
"AGENTS = [\"news\", \"earnings\", \"market\"]\n",
"\n",
"def news_node(state: GraphState, agent: AgentExecutor) -> GraphState:\n",
" ticker = state[\"ticker\"]\n",
" query = news_user_prompt.format(ticker=ticker)\n",
" res = agent.invoke({\"input\": query})\n",
" state[\"news_summary\"] = res[\"output\"]\n",
" state[\"completed\"] = list(set(state[\"completed\"] + [\"news\"]))\n",
" return state\n",
"\n",
"\n",
"def earnings_node(state: GraphState, agent: AgentExecutor) -> GraphState:\n",
" ticker = state[\"ticker\"]\n",
" query = earnings_user_prompt.format(ticker=ticker)\n",
" res = agent.invoke({\"input\": query})\n",
" state[\"earnings_summary\"] = res[\"output\"]\n",
" state[\"completed\"] = list(set(state[\"completed\"] + [\"earnings\"]))\n",
" return state\n",
"\n",
"\n",
"def market_node(state: GraphState, agent: AgentExecutor) -> GraphState:\n",
" ticker = state[\"ticker\"]\n",
" query = market_user_prompt.format(ticker=ticker)\n",
" res = agent.invoke({\"input\": query})\n",
" state[\"market_summary\"] = res[\"output\"]\n",
" state[\"completed\"] = list(set(state[\"completed\"] + [\"market\"]))\n",
" return state\n",
"\n",
"\n",
"def synth_node(state: GraphState, synthesizer_chain) -> GraphState:\n",
" out = synthesizer_chain.invoke(\n",
" {\n",
" \"ticker\": state[\"ticker\"],\n",
" \"news_summary\": state.get(\"news_summary\", \"\"),\n",
" \"earnings_summary\": state.get(\"earnings_summary\", \"\"),\n",
" \"market_summary\": state.get(\"market_summary\", \"\"),\n",
" }\n",
" )\n",
" state[\"final_recommendation\"] = out.content if hasattr(out, \"content\") else str(out)\n",
" return state\n",
" \n",
"def supervisor_node(state: GraphState) -> GraphState:\n",
" # Do any bookkeeping here if needed; otherwise just pass state through\n",
" return state\n",
"\n",
"def supervisor_router(state: GraphState) -> str:\n",
" remaining = [a for a in AGENTS if a not in state.get(\"completed\", [])]\n",
" return remaining[0] if remaining else \"synth\""
]
},
{
"cell_type": "markdown",
"id": "f27d4f01-74bc-4fa3-888f-98947c11d282",
"metadata": {},
"source": [
"### 4.2 Graph State"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8d9787f0-27d5-4b48-9a0f-29e72da51855",
"metadata": {},
"outputs": [],
"source": [
"from typing import TypedDict, List, Optional, Dict, Any\n",
"\n",
"class GraphState(TypedDict):\n",
" ticker: str\n",
" query: str # general query / task\n",
" # outputs collected from agents\n",
" news_summary: Optional[str]\n",
" earnings_summary: Optional[str]\n",
" market_summary: Optional[str]\n",
" # bookkeeping\n",
" completed: List[str]\n",
" # final\n",
" final_recommendation: Optional[str]"
]
},
{
"cell_type": "markdown",
"id": "9ab7d2ec-fa8c-4388-a102-8d2dad8cfe31",
"metadata": {},
"source": [
"### 4.3 Agents Workflow"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c8413fbc-749c-442e-bc23-0b7c2cb54647",
"metadata": {},
"outputs": [],
"source": [
"from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"import yaml\n",
"from langgraph.graph import StateGraph, END\n",
"\n",
"from agents.earnings_agent.earnings_agent import create_earnings_agent\n",
"from agents.market_agent.market_agent import create_market_agent\n",
"from agents.news_agent.news_agent import create_news_agent\n",
"from model.init_model import init_main_model\n",
"from workflow.graph_state import GraphState\n",
"from workflow.nodes.nodes import news_node, earnings_node, market_node, synth_node, supervisor_node, AGENTS, supervisor_router\n",
"from pathlib import Path\n",
"\n",
"system_synthesizer = (\n",
" \"You are the Lead Portfolio Analyst. Merge inputs from News, Earnings, and Market agents.\" \n",
" \"Produce a final, actionable recommendation block (Buy/Hold/Sell with confidence 0-1),\" \n",
" \"key drivers (bull/bear), near-term catalysts, and 2-3 risks. Be concise and concrete.\"\n",
")\n",
"\n",
"human_synthesizer = (\n",
" \"Ticker: {ticker}\\n\\n\"\n",
" \"### News Summary\\n{news_summary}\\n\\n\"\n",
" \"### Earnings Summary\\n{earnings_summary}\\n\\n\"\n",
" \"### Market Summary\\n{market_summary}\\n\\n\"\n",
" \"Write the final recommendation now.\"\n",
")\n",
"\n",
"def make_synthesizer(model):\n",
" \"\"\"Final writer to merge all agent outputs into actionable recommendations.\"\"\"\n",
" template = ChatPromptTemplate.from_messages(\n",
" [\n",
" (\"system\", system_synthesizer),\n",
" (\"human\", human_synthesizer)\n",
" ]\n",
" )\n",
" return template | model # LC chain: Prompt -> LLM\n",
"\n",
"def build_agents_workflow(llm_model_name):\n",
" # --- Base LLM for agents & synthesizer, we can initiate different models for agents here ---\n",
" model = init_main_model(llm_model_name)\n",
"\n",
" # --- Create specialized agents ---\n",
" news_agent = create_news_agent(model)\n",
" earnings_agent = create_earnings_agent(model)\n",
" market_agent = create_market_agent(model)\n",
"\n",
" # --- Create synthesizer chain ---\n",
" synthesizer = make_synthesizer(model)\n",
"\n",
" # --- LangGraph: wire nodes ---\n",
" g = StateGraph(GraphState)\n",
"\n",
" # Bind node callables with their dependencies via closures\n",
" g.add_node(\"news\", lambda s: news_node(s, news_agent))\n",
" g.add_node(\"earnings\", lambda s: earnings_node(s, earnings_agent))\n",
" g.add_node(\"market\", lambda s: market_node(s, market_agent))\n",
" g.add_node(\"synth\", lambda s: synth_node(s, synthesizer))\n",
"\n",
" # Supervisor node\n",
" g.add_node(\"supervisor\", supervisor_node)\n",
" # Edges: start -> supervisor -> (news|earnings|market|synth) -> supervisor ... -> synth -> END\n",
" g.set_entry_point(\"supervisor\")\n",
"\n",
" for a in AGENTS:\n",
" g.add_edge(a, \"supervisor\")\n",
" g.add_edge(\"synth\", END)\n",
"\n",
" # Route decisions come from the router function (returns a string)\n",
" g.add_conditional_edges(\n",
" \"supervisor\",\n",
" supervisor_router, # returns: \"news\" | \"earnings\" | \"market\" | \"synth\"\n",
" {\n",
" \"news\": \"news\",\n",
" \"earnings\": \"earnings\",\n",
" \"market\": \"market\",\n",
" \"synth\": \"synth\",\n",
" },\n",
" )\n",
"\n",
" return g.compile()"
]
},
{
"cell_type": "markdown",
"id": "bcc79b8d-cd71-405f-b4f0-bd6656e4931c",
"metadata": {},
"source": [
"## 5 Run"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "41288526-ba4d-4980-b847-791ea5c119d8",
"metadata": {},
"outputs": [],
"source": [
"from workflow.agents_workflow import build_agents_workflow\n",
"from workflow.graph_state import GraphState\n",
"\n",
"# Run locally without gradio\n",
"\n",
"app = build_agents_workflow(llm_model_name=\"gpt-4o-mini\")\n",
"\n",
"def run_user_query(ticker):\n",
" QUERY = f\" Produce investor-ready insights for {ticker}.\"\n",
" init_state: GraphState = {\n",
" \"ticker\": ticker,\n",
" \"query\": QUERY,\n",
" \"news_summary\": None,\n",
" \"earnings_summary\": None,\n",
" \"market_summary\": None,\n",
" \"completed\": [],\n",
" \"final_recommendation\": None,\n",
" }\n",
" final_state = app.invoke(init_state)\n",
"\n",
" return final_state\n",
"\n",
"state = run_user_query(\"AAPL\")\n",
"\n",
"print(\"\\n\" + \"=\" * 80)\n",
"print(f\"### NEWS SUMMARY\\n{state['news_summary']}\\n\")\n",
"print(f\"### EARNINGS SUMMARY\\n{state['earnings_summary']}\\n\")\n",
"print(f\"### MARKET SUMMARY\\n{state['market_summary']}\\n\")\n",
"print(f\"### FINAL RECOMMENDATION\\n{state['final_recommendation']}\\n\")"
]
},
{
"cell_type": "markdown",
"id": "fc07563c-91af-4d9d-b8dc-c920e41f163a",
"metadata": {},
"source": [
"## 6. System Architecture Summary"
]
},
{
"cell_type": "markdown",
"id": "478cd45e-f264-4b05-8dac-5716f95880d1",
"metadata": {},
"source": [
"| **Component** | **Description** |\n",
"| -------------------- | ----------------------------------------------- |\n",
"| **Supervisor Agent** | Plans, routes, and consolidates results |\n",
"| **News Agent** | Gathers market news and sentiment |\n",
"| **Earnings Agent** | Extracts and interprets company earnings data |\n",
"| **Market Agent** | Analyzes stock trends and technical indicators |\n",
"| **Evaluator Agent** | Critiques and scores the overall report |\n",
"| **Memory Layer** | Maintains conversational and analytical context |\n",
"| **Iteration Loop** | Refines reasoning via feedback cycles |\n",
"\n",
"Key Strengths\n",
"✅ Modular YAML + LangChain integration for reusable prompt templates.\n",
"✅ Realistic workflow emulating professional equity research teams.\n",
"✅ Self-evaluating loop ensures higher factual consistency.\n",
"✅ Extensible for additional agents (e.g., ESG Analyst, Risk Scorer).\n"
]
},
{
"cell_type": "markdown",
"id": "8de30b3f-f006-4a6a-94af-53d6d794c346",
"metadata": {},
"source": [
"## 7. Conclusion"
]
},
{
"cell_type": "markdown",
"id": "bb1bcbc0-1e67-4477-964d-f67a0e6b2205",
"metadata": {},
"source": [
"The Multi-Agent Financial Analysis System exemplifies next-generation AI infrastructure for market intelligence — one that reasons, collaborates, and evolves.\n",
"By blending structured reasoning with self-improvement loops, it brings the intelligence of multi-analyst teams into an automated, explainable framework for financial decision-making."
]
},
{
"cell_type": "markdown",
"id": "bcdb4784-735a-4e1d-801d-5ac1a57e5c1d",
"metadata": {},
"source": [
"## 8. Appendix "
]
},
{
"cell_type": "raw",
"id": "ffffb61c-1367-4a7d-af22-7d6d035dd368",
"metadata": {},
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "5ac71f1d-fc85-4ec3-9c7f-281aa3bd3353",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}