Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Read by thought-leaders and decision-makers around the world. Phone Number: +1-650-246-9381 Email: pub@towardsai.net
228 Park Avenue South New York, NY 10003 United States
Website: Publisher: https://towardsai.net/#publisher Diversity Policy: https://towardsai.net/about Ethics Policy: https://towardsai.net/about Masthead: https://towardsai.net/about
Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Founders: Roberto Iriondo, , Job Title: Co-founder and Advisor Works for: Towards AI, Inc. Follow Roberto: X, LinkedIn, GitHub, Google Scholar, Towards AI Profile, Medium, ML@CMU, FreeCodeCamp, Crunchbase, Bloomberg, Roberto Iriondo, Generative AI Lab, Generative AI Lab VeloxTrend Ultrarix Capital Partners Denis Piffaretti, Job Title: Co-founder Works for: Towards AI, Inc. Louie Peters, Job Title: Co-founder Works for: Towards AI, Inc. Louis-François Bouchard, Job Title: Co-founder Works for: Towards AI, Inc. Cover:
Towards AI Cover
Logo:
Towards AI Logo
Areas Served: Worldwide Alternate Name: Towards AI, Inc. Alternate Name: Towards AI Co. Alternate Name: towards ai Alternate Name: towardsai Alternate Name: towards.ai Alternate Name: tai Alternate Name: toward ai Alternate Name: toward.ai Alternate Name: Towards AI, Inc. Alternate Name: towardsai.net Alternate Name: pub.towardsai.net
5 stars – based on 497 reviews

Frequently Used, Contextual References

TODO: Remember to copy unique IDs whenever it needs used. i.e., URL: 304b2e42315e

Resources

Our 15 AI experts built the most comprehensive, practical, 90+ lesson courses to master AI Engineering - we have pathways for any experience at Towards AI Academy. Cohorts still open - use COHORT10 for 10% off.

Publication

Is This the Future of Financial Analysis? RAG & Multi-Agent Systems Explained
Data Science   Latest   Machine Learning

Is This the Future of Financial Analysis? RAG & Multi-Agent Systems Explained

Last Updated on April 25, 2025 by Editorial Team

Author(s): Saurab

Originally published on Towards AI.

Is This the Future of Financial Analysis? RAG & Multi-Agent Systems Explained

The modern financial sector is drowning in data. The large volume and complexity are exploding, overwhelming traditional analysis methods. Quickly and accurately extracting insights from this digital ocean isn’t just an advantage anymore — it’s essential for survival and success. Old approaches stumble with unstructured data, miss subtle market shifts, and struggle to adapt quickly, leading to missed opportunities and flawed decisions.

Enter a new wave of AI: Retrieval-Augmented Generation (RAG) and multi-agent systems. This potent combination promises to reshape financial analysis, breaking through old limitations and unlocking deeper, faster insights from the ever-growing financial data universe.

Demystifying Retrieval-Augmented Generation (RAG) in Finance

Photo by MJ Duford on Unsplash

Think of RAG as turbocharging Large Language Models (LLMs). It cleverly uses the LLM’s ability to generate human-like text with a dynamic retrieval system. This lets the AI fetch and use information from external, up-to-the-minute data sources — crucial in the fast-paced world of finance.

Unlike standard LLMs locked into their training data, RAG systems actively search vast knowledge bases (like internal company documents, financial databases, or the web) to find the most relevant information for a specific query before generating an answer. This on-demand access to current information is a game-changer.

How RAG Works in Practice (Simplified):

  1. Data Ingestion & Processing: Financial documents, reports, news feeds, etc., are collected.
  2. Chunking: This data is broken down into smaller, meaningful pieces.
  3. Embedding: An AI model converts these text chunks into numerical representations (vectors) that capture their meaning.
  4. Vector Database Storage: These vectors are stored in a specialized database, optimized for finding similar vectors quickly.
  5. Query & Retrieval: When you ask a question (or an AI agent does), RAG converts the query into a vector and searches the database for the most similar data chunks (the most relevant information).
  6. Augmentation: The retrieved relevant information is added as context to the original query.
  7. Generation: The LLM (like Gemini) uses both the original query and the fetched context to generate a grounded, accurate, and up-to-date answer.

Why is RAG a Big Deal for Finance?

  • Accuracy & Reliability: Answers are based on verifiable data, not just the LLM’s internal knowledge. As one leader noted, “RAG is the answer to delivering enterprise AI into production… [It] can bring accurate, auditable AI to FSI enterprises…”
  • Better Decisions: Access to the latest data means faster, more informed analysis — critical when facing market volatility and strict regulations.
  • Fewer “Hallucinations”: RAG reduces the risk of the AI making things up by grounding it in real data.
  • Cost-Effective Updates: Instead of expensive retraining, you update the knowledge base RAG draws from, keeping the AI current without breaking the bank.

Recent RAG Advancements & Applications:

  • Adaptive Retrieval: Prioritizing contextually relevant, real-time data over static datasets.
  • Cross-Disciplinary Techniques: Using knowledge graphs to connect disparate data points for more coherent insights.
  • Multimodal RAG: Integrating text, images (like charts in PDFs), and potentially audio for richer analysis.
  • Real-World Uses: Powering sophisticated legal AI, improving credit risk assessment with real-time data, personalizing investment advice, streamlining regulatory compliance (e.g., summarizing Basel III), enhancing algorithmic trading, boosting fraud detection/AML, and automating report generation.

The Synergy of Multi-Agent Systems for Financial Intelligence

Why use one AI when you can have a team? Multi-agent systems employ multiple specialized AI agents that collaborate to tackle complex problems. Think of it as a distributed AI workforce. Instead of one generalist AI, you break down tasks (like financial analysis) and assign them to agents with specific expertise: a data retriever, a market analyst, a sentiment specialist, etc.

Advantages of the Multi-Agent Approach:

  • Modularity & Specialization: Each agent focuses on what it does best, improving efficiency and accuracy.
  • Parallelism & Speed: Multiple agents can work simultaneously, drastically speeding up analysis.
  • Scalability & Adaptability: Easily add or modify agents as market conditions or analysis needs change.
  • Robustness: The failure of one agent doesn’t necessarily crash the whole system.
  • Improved Decision-Making: Problems are viewed from multiple angles, leading to more comprehensive solutions.
  • Real-Time Responsiveness: Crucial for reacting quickly to market movements.

Multi-Agent Systems in Action in Finance:

  • Optimizing investment strategies with real-time data.
  • Enhancing risk management through diverse perspectives.
  • Automating compliance checks and regulatory reporting.
  • Improving fraud detection by monitoring transactions for anomalies.
  • Simulating market dynamics for better understanding.
  • Developing and backtesting trading strategies safely.
  • Managing complex portfolios and executing trades efficiently.

Introducing the RAG Specialist Agent

To fully leverage RAG within our multi-agent system, we introduce a dedicated RAG Specialist Agent.

  • Role: Knowledge Retriever & Context Provider
  • Goal: To efficiently query vector databases and external knowledge sources, retrieve the most relevant and up-to-date information based on other agents’ needs, and provide this context for augmented analysis.
  • Backstory: An expert in semantic search, vector embeddings, database optimization, and information retrieval architecture.
  • Potential Tools: Vector Database Query Tools (interfaces for ChromaDB, Pinecone, FAISS, etc.), Document Loaders/Parsers, Web Search APIs, Knowledge Graph Query Tools.

This agent acts as the librarian and research assistant for the entire crew, ensuring that all other agents have access to the best possible information before making decisions or generating insights.

CrewAI: Your Orchestration Platform for Financial Agents

CrewAI is a lean, fast Python framework specifically designed for building and managing multi-agent systems. It’s independent and offers both high-level simplicity for quick development and low-level control for customization — perfect for creating tailored financial AI teams.

Key CrewAI Features for Finance:

  • Role-Based Agents: Define agents with specific roles (like Market Analyst), goals, and backstories.
  • Flexible Tools: Equip agents with custom functions or APIs (their “tools”) to interact with the outside world — fetching data, running calculations, executing code, etc.
  • Example Tools:Financial Data API Clients (Alpha Vantage, Yahoo Finance)
  • Web Scraping Tools (using libraries like BeautifulSoup)
  • Sentiment Analysis APIs or Libraries (NLTK, spaCy, Transformers)
  • Technical Analysis Libraries (TA-Lib wrappers)
  • Quantitative Libraries (NumPy, SciPy for risk models)
  • Code Execution Tools (PythonREPLTool): Allow agents to write and run Python code for custom calculations, data manipulation, or simple strategy testing.
  • Writing/Reporting Tools: Format outputs or generate summaries.
  • Vector Database Query Tools (for the RAG Specialist).
  • Intelligent Collaboration: Agents work together, share insights, and coordinate tasks (sequentially or hierarchically).
  • Task Management: Define workflows (sequential or parallel) with automatic dependency management.
  • Memory & Context: Agents remember past interactions for coherent reasoning.
  • Monitoring & Observability: Track agent performance and identify areas for improvement.

Introducing the Manager Agent

To ensure smooth operation and effective collaboration within our growing team of specialized agents, we introduce a Manager Agent.

  • Role: Workflow Orchestrator & Synthesizer
  • Goal: looks after the entire analysis process, delegate tasks to appropriate agents, ensure timely completion, manage dependencies, and synthesize the findings from different agents into a final, coherent output or recommendation.
  • Backstory: An experienced project manager adept at coordinating complex systems, ensuring alignment with high-level objectives, and facilitating effective communication between specialized units.
  • Potential Tools: Task Scheduling/Delegation Tools (leveraging CrewAI’s internal mechanics), Progress Monitoring Tools, Report Aggregation/Formatting Tools, Quality Assurance Checks.

The Manager Agent acts as the conductor of the AI orchestra, ensuring all the specialized agents play their part effectively and contribute to the overall goal.

Empowering Agents with Gemini: The Brains Behind the Analysis

Gemini, Google’s advanced AI model, is an excellent choice to power the “thinking” of CrewAI agents.

  • Native Multimodality: Understands text, code, and potentially images/charts — great for diverse financial data.
  • Strong Reasoning: Excels at natural language, complex math, and code generation — perfect for financial analysis and strategy development.
  • Scalability: Efficiently processes the large datasets common in finance.
  • Real-Time Capability: Designed to handle streaming data for timely insights.
  • Google Ecosystem Integration: Connects with tools like Sheets and Docs for seamless workflows (if applicable).

Using Gemini as the LLM gives the CrewAI agents powerful cognitive abilities to understand financial nuances and generate insightful outputs.

Building a Financial Analysis Powerhouse: Enhanced Implementation

Let’s revisit our portfolio management and trading decision system, now incorporating the RAG Specialist and Manager Agent, along with more specific tools.

Our Enhanced AI Agent Crew:

RAG Specialist Agent: (As defined above) Retrieves relevant context from vector databases and external sources.

  • Tools: Vector DB Client, Document Parsers, Web Search Tool.

Data Retriever Agent: Fetches real-time and historical market data.

  • Role: Financial Data Specialist
  • Goal: Acquire accurate, timely market data via APIs and other sources.
  • Backstory: Expert in financial data APIs, web scraping, and data cleaning.
  • Tools: AlphaVantageTool, YahooFinanceTool, Custom Web Scraper Tool.

Market Analyst Agent: Analyzes market trends, economic indicators, and performs technical/fundamental analysis.

  • Role: Quantitative & Qualitative Analyst
  • Goal: Identify investment opportunities and risks based on broad market conditions and specific asset analysis.
  • Backstory: Experienced analyst skilled in technical indicators, macroeconomic analysis, and financial modeling.
  • Tools: WebsiteSearchTool, EconomicDataTool (FRED), TechnicalAnalysisTool (TA-Lib), CodeExecutionTool.

News Sentiment Analyzer Agent: Gauges market sentiment from news and social media.

  • Role: Sentiment Analysis Expert
  • Goal: Quantify market mood towards specific assets or the market overall.
  • Backstory: NLP expert specializing in financial text and sentiment extraction.
  • Tools: SentimentAnalysisAPI_Tool, SocialMediaMonitorTool, WebsiteSearchTool.

Trading Strategist Agent: Develops and backtests trading strategies.

  • Role: Strategy Developer & Backtester
  • Goal: Generate actionable trading signals (buy/sell/hold) based on integrated analysis.
  • Backstory: Seasoned algorithmic trader proficient in strategy design and validation.
  • Tools: BacktestingFrameworkTool, CodeExecutionTool, TechnicalAnalysisTool.

Risk Management Agent: Assesses portfolio risk and potential trade risks.

  • Role: Risk Assessment Specialist
  • Goal: Quantify and mitigate financial risk using established models.
  • Backstory: Quantitative risk expert familiar with VaR, portfolio theory, and stress testing.
  • Tools: VaR_CalculationTool, PortfolioOptimizationTool, MonteCarloSimulationTool, CodeExecutionTool.

Manager Agent: (As defined above) Oversees the workflow, coordinates agents, and synthesizes the final output.

  • Tools: CrewAI Task Management, Report Synthesizer Tool.

Example Workflow & Tasks:

  1. Task (Manager): Define analysis scope (e.g., analyze AAPL, GOOGL, MSFT for next trading day). Delegate initial data gathering.
  2. Task (RAG Specialist): Retrieve recent relevant news summaries, analyst reports, and regulatory filings related to the target stocks and overall market sector from the knowledge base. Provide this context.
  3. Task (Data Retriever): Fetch latest price/volume data and relevant historical data for AAPL, GOOGL, MSFT.
  4. Task (Market Analyst): Analyze retrieved data and RAG context. Assess current market trends, economic indicators, perform technical analysis on target stocks. Generate market outlook report.
  5. Task (News Sentiment Analyzer): Analyze retrieved news/social media data and RAG context. Generate sentiment scores/summaries for target stocks.
  6. Task (Trading Strategist): Integrate Market Analyst report, Sentiment report, and RAG context. Develop potential buy/sell/hold signals with entry/exit points. Optionally, run simple backtests using the CodeExecutionTool.
  7. Task (Risk Manager): Evaluate the risk profile of the proposed trades/strategy using its tools (e.g., calculate potential portfolio VaR change). Suggest risk mitigation adjustments if necessary.
  8. Task (Manager): Synthesize inputs from all agents (Analysis, Sentiment, Strategy, Risk Assessment) into a final, concise recommendation report.
import os
import requests
import yfinance as yf
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from ta.volatility import BollingerBands
from ta.momentum import RSIIndicator
from ta.trend import MACD
from crewai_tools import BaseTool
from typing import Type, Any
from pydantic.v1 import BaseModel, Field # crewai uses pydantic v1


# --- RAG Simulation Tool ---
class SimulatedVectorDBQueryTool(BaseTool):
name: str = "Simulated Knowledge Base Query"
description: str = ("Queries a simulated knowledge base for relevant information "
"based on keywords. Input should be a string of keywords.")

# Simulate a simple knowledge base
knowledge_base = {
"market outlook": "Recent reports suggest cautious optimism in the tech sector, while energy faces headwinds.",
"AAPL news": "Apple reported strong earnings but issued conservative guidance for the next quarter.",
"GOOGL analysis": "Analysts remain bullish on Google's advertising revenue growth.",
"MSFT strategy": "Microsoft continues to expand its cloud offerings, driving significant growth.",
"interest rates": "The Federal Reserve is expected to maintain current interest rates in the upcoming meeting.",
"inflation": "Inflation metrics show a slight decrease but remain above the target range."
}

def _run(self, keywords: str) -> str:
results = []
search_terms = keywords.lower().split()
try:
for key, value in self.knowledge_base.items():
if any(term in key.lower() for term in search_terms):
results.append(value)
if not results:
return "No specific information found for these keywords in the simulated knowledge base."
return "\n".join(results)
except Exception as e:
return f"Error querying simulated knowledge base: {e}"

# --- Financial Data Tool ---
class MarketDataTool(BaseTool):
name: str = "Yahoo Finance Market Data Fetcher"
description: str = ("Fetches historical stock price (Open, High, Low, Close) and Volume "
"data from Yahoo Finance. Input should be the stock ticker symbol (e.g., 'AAPL'). "
"Fetches data for the last 3 months by default.")

def _run(self, ticker: str) -> str:
try:
stock = yf.Ticker(ticker)
# Fetch data for the last 3 months
hist = stock.history(period="3mo")
if hist.empty:
return f"No historical data found for ticker {ticker} on Yahoo Finance."
# Return the data as a string representation (or summary)
return f"Fetched 3 months data for {ticker}:\n{hist.tail().to_string()}" # Show last 5 days
except Exception as e:
return f"Error fetching market data for {ticker}: {e}"

# --- Basic Web Scraper Tool ---
class SimpleWebScraperTool(BaseTool):
name: str = "Simple Financial News Headline Scraper"
description: str = ("Scrapes headlines from a specific financial news site "
"(e.g., MarketWatch Market Pulse). Input should be the URL "
"'https://www.marketwatch.com/investing/pulse'.")

def _run(self, url: str = "https://www.marketwatch.com/investing/pulse") -> str:
# Basic check to ensure the right URL is somewhat intended
if "marketwatch.com" not in url:
return "Error: This tool is configured for MarketWatch Pulse headlines."
try:
headers = {'User-Agent': 'Mozilla/5.0'} # Some sites block default python user-agent
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status() # Raise an exception for bad status codes

soup = BeautifulSoup(response.text, 'html.parser')

# NOTE: These selectors are specific to MarketWatch as of Apr 2025 and WILL BREAK if the site changes.
# This demonstrates the fragility of scraping.
headlines = []
# Look for common headline patterns (this requires inspecting the site)
elements = soup.select('h3.article__headline a.link, div.article__content h3 a') # Example selectors

for elem in elements[:10]: # Limit to first 10 found headlines
if elem and elem.text:
headlines.append(elem.text.strip())

if not headlines:
return "Could not find headlines using known selectors. Site structure may have changed."

return "Recent Headlines:\n- " + "\n- ".join(headlines)

except requests.exceptions.RequestException as e:
return f"Error during web request: {e}"
except Exception as e:
return f"Error scraping headlines from {url}: {e}"

# --- Technical Analysis Tool ---
class TechnicalAnalysisTool(BaseTool):
name: str = "Stock Technical Analysis Calculator"
description: str = ("Calculates common technical indicators (SMA 20, RSI 14, MACD) for a "
"given stock ticker using the last 3 months of historical data. "
"Input should be the stock ticker symbol (e.g., 'MSFT').")

def _run(self, ticker: str) -> str:
try:
stock = yf.Ticker(ticker)
hist = stock.history(period="3mo")
if hist.empty:
return f"No historical data found for {ticker} to perform technical analysis."

# Ensure DataFrame has 'Close' column
if 'Close' not in hist.columns:
return f"Historical data for {ticker} missing 'Close' column."

# Calculate indicators using the 'ta' library
hist['SMA_20'] = hist['Close'].rolling(window=20).mean()
rsi_indicator = RSIIndicator(close=hist['Close'], window=14)
hist['RSI_14'] = rsi_indicator.rsi()
macd_indicator = MACD(close=hist['Close'])
hist['MACD_diff'] = macd_indicator.macd_diff() # MACD Line - Signal Line

# Get the latest values
latest_sma = hist['SMA_20'].iloc[-1]
latest_rsi = hist['RSI_14'].iloc[-1]
latest_macd_diff = hist['MACD_diff'].iloc[-1]

return (f"Technical Indicators for {ticker} (latest):\n"
f"- SMA(20): {latest_sma:.2f}\n"
f"- RSI(14): {latest_rsi:.2f}\n"
f"- MACD Diff: {latest_macd_diff:.2f}")

except Exception as e:
return f"Error calculating technical indicators for {ticker}: {e}"

# --- Sentiment Analysis Tool ---
class SentimentAnalysisTool(BaseTool):
name: str = "Simple Text Sentiment Analyzer"
description: str = ("Analyzes the sentiment (positive, neutral, negative) of a given "
"text snippet using NLTK's VADER. Input is the text to analyze.")
analyzer: SentimentIntensityAnalyzer = None

def __init__(self, **kwargs: Any):
super().__init__(**kwargs)
# Initialize analyzer upon instantiation
self.analyzer = SentimentIntensityAnalyzer()

def _run(self, text: str) -> str:
try:
vs = self.analyzer.polarity_scores(text)
score = vs['compound']
if score >= 0.05:
sentiment = "Positive"
elif score <= -0.05:
sentiment = "Negative"
else:
sentiment = "Neutral"
return f"Sentiment: {sentiment} (Compound Score: {score:.3f})"
except Exception as e:
return f"Error analyzing sentiment: {e}"

# --- Risk Calculation Tool ---
class VaRCalculationTool(BaseTool):
name: str = "Simple Historical Value-at-Risk (VaR) Calculator"
description: str = ("Calculates the 1-day 95% historical Value-at-Risk (VaR) for a stock "
"based on the last year of daily returns. Input is the stock ticker symbol (e.g., 'GOOGL').")

def _run(self, ticker: str) -> str:
try:
stock = yf.Ticker(ticker)
hist = stock.history(period="1y") # Get 1 year of data
if hist.empty or 'Close' not in hist.columns:
return f"Insufficient historical data for {ticker} to calculate VaR."

# Calculate daily percentage returns
hist['Daily_Return'] = hist['Close'].pct_change()

# Drop NaN values (first value will be NaN)
daily_returns = hist['Daily_Return'].dropna()

if len(daily_returns) < 20: # Need some data points
return f"Not enough return data points for {ticker} to calculate VaR reliably."

# Calculate VaR at 95% confidence level (5th percentile of returns)
var_95 = np.percentile(daily_returns, 5) # Or daily_returns.quantile(0.05)

return f"Estimated 1-Day 95% Historical VaR for {ticker}: {var_95:.2%}"

except Exception as e:
return f"Error calculating VaR for {ticker}: {e}"

# --- Basic Report Formatting Tool ---
class ReportFormatterTool(BaseTool):
name: str = "Simple Markdown Report Formatter"
description: str = ("Formats provided text sections into a basic markdown report. "
"Input should be a dictionary where keys are section titles and values are the text content.")

def _run(self, report_sections: dict) -> str:
try:
markdown_report = f"# Financial Analysis Report - {pd.Timestamp.now().strftime('%Y-%m-%d')}\n\n"
for title, content in report_sections.items():
markdown_report += f"## {title.replace('_', ' ').title()}\n"
markdown_report += f"{content}\n\n"
return markdown_report.strip()
except Exception as e:
return f"Error formatting report: {e}"

--
from crewai_tools import PythonREPLTool
# Note: This tool allows agents to execute arbitrary Python code.
# Use with EXTREME caution in production environments due to security risks.
python_repl_tool = PythonREPLTool()

# --- Instantiate all tools ---
vector_db_tool = SimulatedVectorDBQueryTool()
market_data_tool = MarketDataTool()
simple_scraper_tool = SimpleWebScraperTool()
tech_analysis_tool = TechnicalAnalysisTool()
sentiment_analyzer_tool = SentimentAnalysisTool()
var_calculator_tool = VaRCalculationTool()
report_formatter_tool = ReportFormatterTool()
# Web search tool from crewai_tools
from crewai_tools import WebsiteSearchTool
# You might want to use Serper for better web search, requires SERPER_API_KEY env var
# from crewai_tools import SerperDevTool
# web_search_tool = SerperDevTool()
web_search_tool = WebsiteSearchTool() # Using the basic one for less setup

Multi Agents code block:

import os
from crewai import Crew, Agent, Task, Process
from langchain_google_genai import GoogleGenerativeAI
from dotenv import load_dotenv

load_dotenv() # Load environment variables from .env file

# Initialize Gemini LLM
gemini_llm = GoogleGenerativeAI(model="gemini-2.0-flash-001", google_api_key=os.environ.get("GOOGLE_API_KEY"))

# Define Agents with Tools

rag_specialist = Agent(
role='Knowledge Retriever & Context Provider',
goal="""Retrieve the most relevant, up-to-date, and comprehensive contextual information
(news, analyst sentiment, market trends) about a given stock symbol ({stock_symbol}) and its sector.
Prioritize information quality and synthesis over raw data volume."""
,
backstory="""An expert in semantic search, vector embeddings, and information retrieval systems.
You excel at querying diverse sources (vector databases, web search) and synthesizing disparate
pieces of information into a coherent narrative. You understand the nuances of financial markets
and can filter noise to extract meaningful context for analysts."""
,
llm=gemini_llm,
tools=[vector_db_tool, web_search_tool],
verbose=True,
allow_delegation=True
)

data_retriever = Agent(
role='Financial Data Specialist',
goal="""Accurately and reliably acquire timely market data (historical prices, volume)
for a specific stock symbol ({stock_symbol}) using designated APIs (e.g., Yahoo Finance).
Ensure data integrity and correct formatting for downstream analysis."""
,
backstory="""An expert in interacting with financial data APIs like Yahoo Finance.
You are meticulous about data accuracy, handling potential API errors gracefully,
and providing data in a clean, usable format. You understand the importance of
reliable data for quantitative analysis."""
,
llm=gemini_llm,
tools=[market_data_tool],
verbose=True,
allow_delegation=True
)

market_analyst = Agent(
role='Quantitative & Qualitative Analyst',
goal="""Analyze market data for {stock_symbol} to identify potential investment opportunities and risks.
This involves calculating and interpreting key technical indicators, correlating them with market context,
and identifying significant patterns or events. Utilize calculation tools and web search for confirmation."""
,
backstory="""A seasoned market analyst with deep expertise in technical analysis (chart patterns, indicators like SMA, RSI, MACD),
macroeconomic factors, and interpreting financial news. You are skilled at using quantitative tools
and coding for custom analysis, bridging the gap between raw data and actionable insights. You focus on
objective interpretation supported by evidence."""
,
llm=gemini_llm,
tools=[tech_analysis_tool, web_search_tool, python_repl_tool],
verbose=True,
allow_delegation=True,
)

news_sentiment_analyzer = Agent(
role='Sentiment Analysis Expert',
goal="""Quantify the prevailing market sentiment towards {stock_symbol} by analyzing news headlines,
articles, and contextual information. Provide an aggregated sentiment score and identify key themes
driving the sentiment."""
,
backstory="""An NLP expert specializing in financial text analysis. You leverage advanced sentiment analysis
models and web scraping techniques to gauge the market's mood concerning specific assets. You understand
that sentiment can be a leading indicator and focus on providing a nuanced view, including intensity
and key drivers of the observed sentiment."""
,
llm=gemini_llm,
tools=[sentiment_analyzer_tool, simple_scraper_tool, web_search_tool],
verbose=True,
allow_delegation=True
)

trading_strategist = Agent(
role='Strategy Developer',
goal="""Synthesize technical analysis, sentiment data, and market context to generate a clear,
actionable short-term trading view (e.g., Bullish, Bearish, Neutral) for {stock_symbol}.
Provide concise justification based on the integrated analysis."""
,
backstory="""An experienced algorithmic trader and strategist, proficient in translating complex analysis
into concrete trading decisions. You excel at weighing conflicting signals (e.g., technical vs. sentiment)
and formulating a probabilistic view. You can use coding tools to test simple strategic logic or weighting."""
,
llm=gemini_llm,
tools=[tech_analysis_tool, python_repl_tool], # Can use TA tool for reference and REPL for logic
verbose=True,
allow_delegation=True
)

risk_manager = Agent(
role='Risk Assessment Specialist',
goal="""Quantify the potential downside risk for {stock_symbol} using standard financial risk models like
Value-at-Risk (VaR). Report the risk metric clearly and concisely."""
,
backstory="""A quantitative risk expert with a strong background in financial modeling, portfolio theory,
and risk metrics. You are familiar with calculating and interpreting VaR and other risk measures,
understanding their assumptions and limitations. You focus on providing objective risk assessments."""
,
llm=gemini_llm,

tools=[var_calculator_tool, python_repl_tool], # REPL for potential custom risk calcs if needed
verbose=True,
allow_delegation=True
)

manager_agent = Agent(
role='Workflow Orchestrator & Report Synthesizer',
goal="""Oversee the entire analysis workflow for {stock_symbol}, ensuring agents collaborate effectively,
meet their objectives, and maintain high quality standards. Synthesize all findings into a cohesive,
well-structured final report for the end-user."""
,
backstory="""An experienced AI project manager specialized in coordinating multi-agent systems for complex
analysis tasks. You excel at delegation, quality control, and synthesizing information from diverse sources
into a clear, actionable final product. You ensure the final report directly addresses the initial request
and integrates all analytical components logically."""
,
llm=gemini_llm,
tools=[report_formatter_tool], # Primarily uses formatter, but orchestrates others
verbose=True,
allow_delegation=True # Can delegate tasks to other agents
)


# --- Define Tasks with Enhanced Descriptions (incorporating CoT-like steps) ---

stock_symbol = 'AAPL' # Define the target stock

task_retrieve_context = Task(
description=f"""
**Goal:** Gather comprehensive context for {stock_symbol}.
**Steps:**
1. Identify key search terms related to {stock_symbol}, its industry (Tech/Consumer Electronics), and recent market trends.
2. Query the vector database for internal analyst notes, past reports, or relevant saved articles using these terms.
3. Perform web searches for the latest news headlines, analyst rating changes, and major sector news impacting {stock_symbol}.
4. Filter results for relevance and timeliness (e.g., last month).
5. Synthesize the findings into a structured summary covering: general market sentiment towards tech, specific {stock_symbol} news (product launches, earnings, competition), and notable analyst opinions.
**Deliverable:** A structured summary report.
"""
,
agent=rag_specialist,
expected_output=f"""A structured summary containing sections for:
- Overall Tech Market Outlook/Sentiment Summary
- Recent {stock_symbol}-Specific News Highlights
- Summary of Recent Analyst Ratings/Commentary (if found)"""

)

task_fetch_market_data = Task(
description=f"""
**Goal:** Obtain historical market data for {stock_symbol}.
**Steps:**
1. Target stock: {stock_symbol}.
2. Required data: Daily Open, High, Low, Close, Volume (OHLCV).
3. Time period: Last 3 calendar months from today.
4. Use the Yahoo Finance tool to fetch this data.
5. Verify the data seems complete for the period (e.g., no large gaps).
6. Return the data as a single string (e.g., CSV format or similar structured text).
**Deliverable:** A string containing the OHLCV data.
"""
,
agent=data_retriever,
expected_output=f"A string containing the last 3 months of OHLCV data for {stock_symbol}."
)

task_analyze_technicals = Task(
description=f"""
**Goal:** Perform technical analysis on {stock_symbol}'s historical data.
**Inputs:** Historical data string from the data fetcher task.
**Steps:**
1. Parse the provided historical data. If necessary, use the Python REPL tool for parsing/formatting.
2. Calculate the following technical indicators using the appropriate tool or Python REPL:
* Simple Moving Average (SMA) with a 20-day period. Note the latest value.
* Relative Strength Index (RSI) with a 14-day period. Note the latest value and whether it indicates overbought (>70) or oversold (<30) conditions.
* Moving Average Convergence Divergence (MACD) with standard parameters (e.g., 12, 26, 9). Note the latest MACD line, signal line values, and histogram value. Identify any recent crossovers.
3. Optionally, use web search to check for *very recent* (today/yesterday) major technical chart events (e.g., significant gap up/down, break of major support/resistance) that might not be fully reflected in lagging indicators.
4. Synthesize the findings, interpreting the current state of each indicator.
**Deliverable:** A technical analysis summary report.
"""
,
agent=market_analyst,
context=[task_fetch_market_data], # Depends on fetched data
expected_output=f"""A report summarizing:
- Latest SMA(20) value and trend implication.
- Latest RSI(14) value and interpretation (neutral, overbought, oversold).
- Latest MACD value, signal line, histogram, and interpretation (e.g., bullish/bearish crossover, momentum).
- Mention of any significant recent chart events found via web search.
- A brief overall technical picture (e.g., 'mildly bullish momentum', 'showing signs of consolidation')."""

)

task_analyze_sentiment = Task(
description=f"""
**Goal:** Assess the current market sentiment surrounding {stock_symbol}.
**Inputs:** Contextual information from the RAG specialist task.
**Steps:**
1. Review the contextual summary provided (news, analyst notes).
2. Identify a relevant financial news source (e.g., MarketWatch Pulse, Bloomberg headlines for {stock_symbol}). Use web search if needed to find a suitable URL.
3. Use the simple scraper tool to extract recent headlines/snippets about {stock_symbol} from the chosen source.
4. Apply the sentiment analysis tool to:
* The scraped headlines/snippets.
* The key points from the RAG context summary.
5. Aggregate the sentiment scores. Calculate an overall average score (e.g., on a -1 to +1 scale).
6. Summarize the findings, noting the overall sentiment score and mentioning key positive or negative themes driving the sentiment.
**Deliverable:** A sentiment analysis summary.
"""
,
agent=news_sentiment_analyzer,
context=[task_retrieve_context], # Depends on context
expected_output=f"""A summary report including:
- An overall sentiment score for {stock_symbol} (e.g., numerical score and qualitative label like Positive/Neutral/Negative).
- Key themes or news items identified as driving positive sentiment.
- Key themes or news items identified as driving negative sentiment."""

)

task_develop_strategy_view = Task(
description=f"""
**Goal:** Formulate a short-term trading view for {stock_symbol}.
**Inputs:** Technical analysis report, Sentiment analysis report.
**Steps:**
1. Review the technical analysis: What is the trend? What is the momentum (RSI, MACD)? Are there key support/resistance levels suggested?
2. Review the sentiment analysis: Is the current mood positive, negative, or neutral? Are there strong drivers?
3. Synthesize these two aspects:
* Do technicals and sentiment align? (e.g., Bullish technicals + Positive sentiment)
* Do they conflict? (e.g., Bearish technicals + Positive sentiment - suggests caution or potential reversal)
4. Consider the timeframe (short-term).
5. Formulate a clear view: Bullish, Bearish, or Neutral.
6. Write a brief justification explicitly referencing the key technical indicator(s) and sentiment findings that support the view. Use the REPL tool if a simple calculation (e.g., weighting scheme) helps decision-making.
**Deliverable:** A trading view statement with justification.
"""
,
agent=trading_strategist,
context=[task_analyze_technicals, task_analyze_sentiment], # Depends on analysis and sentiment
expected_output=f"""A concise statement comprising:
- **Trading View:** [Bullish/Bearish/Neutral]
- **Justification:** A brief explanation linking specific technical signals (e.g., 'RSI below 30 suggests oversold') and sentiment ('countered by negative news sentiment') to the derived view."""

)

task_assess_risk = Task(
description=f"""
**Goal:** Quantify the short-term downside risk for {stock_symbol} using VaR.
**Inputs:** Requires historical price data (implicitly accessible by the tool or potentially passed via context if the tool needs it explicitly).
**Steps:**
1. Ensure access to the recent historical price data for {stock_symbol}.
2. Use the Value-at-Risk (VaR) calculator tool.
3. Specify the parameters: 1-day time horizon, 95% confidence level, using historical simulation method based on the available data.
4. Execute the calculation.
5. Report the resulting VaR percentage clearly.
**Deliverable:** The calculated VaR value.
"""
,
agent=risk_manager,
# Context could be added if the VaR tool explicitly needs the data string: context=[task_fetch_market_data],
expected_output=f"The calculated 1-day 95% historical VaR for {stock_symbol}, expressed as a percentage (e.g., '1-Day 95% VaR: 1.23%')."
)

task_synthesize_report = Task(
description=f"""
**Goal:** Create the final, comprehensive analysis report for {stock_symbol}.
**Inputs:** Outputs from all preceding tasks (Context, Technicals, Sentiment, Strategy View, Risk Assessment).
**Steps:**
1. Gather the outputs from:
* `task_retrieve_context`
* `task_analyze_technicals`
* `task_analyze_sentiment`
* `task_develop_strategy_view`
* `task_assess_risk`
2. Structure the final report logically. A recommended structure is:
* Executive Summary (1-2 sentences summarizing the overall picture and view).
* Market Context & News Summary (from `task_retrieve_context`).
* Technical Analysis (from `task_analyze_technicals`).
* Sentiment Analysis (from `task_analyze_sentiment`).
* Trading View & Justification (from `task_develop_strategy_view`).
* Risk Assessment (VaR) (from `task_assess_risk`).
* Disclaimer (standard non-advice clause).
3. Synthesize the information for each section. Rephrase findings concisely; avoid simple copy-pasting. Ensure smooth transitions between sections.
4. Use the report formatting tool to generate a clean, readable markdown report.
5. Add a standard disclaimer stating this is not financial advice.
**Deliverable:** The final markdown report.
"""
,
agent=manager_agent,
context=[task_retrieve_context, task_analyze_technicals, task_analyze_sentiment, task_develop_strategy_view, task_assess_risk], # Depends on all previous results
expected_output=f"""A comprehensive, well-formatted markdown report covering the full analysis of {stock_symbol}, including:
- Executive Summary
- Market Context & News
- Technical Analysis (SMA, RSI, MACD interpretation)
- Sentiment Analysis (score and drivers)
- Trading View (Bullish/Bearish/Neutral) with Justification
- Risk Assessment (1-Day 95% VaR)
- Disclaimer"""

)

# --- Create and Run the Crew ---
financial_crew = Crew(
agents=[manager_agent, rag_specialist, data_retriever, market_analyst, news_sentiment_analyzer, trading_strategist, risk_manager],
tasks=[
# Ordered logically based on dependencies
task_retrieve_context,
task_fetch_market_data,
task_analyze_technicals,
task_analyze_sentiment,
task_develop_strategy_view,
task_assess_risk,
task_synthesize_report # Manager's final task
],
process=Process.hierarchical, # Manager delegates tasks based on dependencies
manager_llm=gemini_llm,
verbose=True
)

# Kick off the crew's work
print(f"--- Starting Financial Analysis Crew for {stock_symbol} ---")
try:
results = financial_crew.kickoff()

print("\n--- Final Analysis Report ---")
# The final result from a hierarchical process is typically the output of the last task assigned or synthesized by the manager.
print(results)

except Exception as e:
print(f"\n--- An error occurred during crew execution ---")
print(e)
print("\nNote: If using placeholder tools/LLM, the output will be based on placeholder responses.")

The Role of Mathematics in Informed Financial Decisions

Quantitative finance relies heavily on mathematical models. In our AI system, these equations become tools wielded by the specialized agents.

Common Mathematical Equations in Financial Analysis :

  • The Risk Management Agent might use Mean-Variance Optimization (calculating expected return and variance for different asset mixes) to find optimal portfolio allocations based on risk tolerance. It would use the VaR formula to quantify potential downside.
  • The Market Analyst and Risk Manager would both use Standard Deviation to measure volatility.
  • The Market Analyst might use the P/E Ratio for comparative valuation.
  • The Trading Strategist could use DCF analysis (potentially via the CodeExecutionTool implementing the formula) to assess long-term intrinsic value.

Embedding these models within the agents allows the system to perform rigorous, data-driven financial analysis beyond simple pattern matching.

Conclusion: The Future of AI-Driven Financial Analysis

Combining RAG with multi-agent systems, orchestrated by frameworks like CrewAI and powered by advanced LLMs like Gemini, marks a pivotal moment in financial analysis. This approach tackles data overload head-on, offering real-time insights, collaborative AI intelligence, and sophisticated analytical power.

The benefits are clear: greater efficiency, improved accuracy, and ultimately, smarter, more profitable decisions in the complex world of finance. As AI continues its rapid evolution, systems like these are set to become indispensable tools, empowering finance professionals to navigate modern markets with unprecedented confidence and insight.

Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

Published via Towards AI


Take our 90+ lesson From Beginner to Advanced LLM Developer Certification: From choosing a project to deploying a working product this is the most comprehensive and practical LLM course out there!

Towards AI has published Building LLMs for Production—our 470+ page guide to mastering LLMs with practical projects and expert insights!


Discover Your Dream AI Career at Towards AI Jobs

Towards AI has built a jobs board tailored specifically to Machine Learning and Data Science Jobs and Skills. Our software searches for live AI jobs each hour, labels and categorises them and makes them easily searchable. Explore over 40,000 live jobs today with Towards AI Jobs!

Note: Content contains the views of the contributing authors and not Towards AI.