File size: 28,616 Bytes
fd4627c
 
 
 
a57d323
fd4627c
 
a57d323
 
 
 
 
 
 
 
 
fd4627c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a57d323
 
 
 
 
 
 
 
 
 
 
 
 
 
fd4627c
 
 
a57d323
fd4627c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
{
 "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",
    "<br>\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": [
    "<b>Focuses on market-moving catalysts.</b>\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",
    "<b>Tools used:</b>\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": [
    "<b>Analyzes corporate earnings reports and financial statements.</b>\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",
    "<b>Key Strengths</b>\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
}