Multi-Agent AI Development: Building Intelligent Financial Advisory Systems with Phidata

Kshitij Kutumbe
5 min readDec 28, 2024

--

Introduction

The field of Artificial Intelligence (AI) has evolved far beyond simple chatbots. Modern AI systems now have the capacity to reason, recall context, and even interact with external tools. These advancements empower developers to create sophisticated, task-oriented systems tailored to various domains.

Enter Phidata — an open-source platform designed to simplify the creation, deployment, and management of AI agents. By leveraging Phidata’s robust agentic framework, developers can create AI systems that are modular, scalable, and capable of handling complex tasks.

In this blog, we’ll walk through the process of building a financial advisory system using Phidata. By the end, you’ll understand how to:

  1. Define specialized AI agents for tasks like portfolio analysis, sentiment assessment, and risk evaluation.
  2. Coordinate these agents using a Master Agent.
  3. Generate a comprehensive financial report that combines insights from all agents.

Let’s get started!

What is Phidata?

Phidata is a framework for building multi-modal agents, use phidata to: Build multi-modal agents with memory, knowledge, tools and reasoning.

  1. Memory Integration
    Retain and use context from past interactions to provide coherent and personalized responses.
  2. Knowledge Integration
    Access domain-specific or external knowledge to enhance accuracy and relevance.
  3. Tool Usage
    Interface with external APIs or tools (e.g., financial data sources) to augment functionality.
  4. Reasoning Abilities
    Apply step-by-step logic to solve problems, making agents suitable for complex tasks like risk analysis or portfolio management.

Phidata’s modular approach allows developers to build systems where multiple agents collaborate, each specializing in a specific task. This eliminates the need for a monolithic AI model and ensures efficiency, maintainability, and scalability.

Understanding the Agentic Framework

Agents and Collaboration

In Phidata, an agent is an autonomous entity designed to perform a specific task. By combining multiple specialized agents, developers can create multi-agent systems capable of solving complex problems through collaboration.

For example, instead of relying on a single model to analyze stock portfolios, assess market sentiment, and evaluate risks, we can divide these responsibilities among three dedicated agents.

The Master Agent

The Master Agent acts as a coordinator. It delegates tasks to specialized agents and consolidates their outputs into a cohesive result. This architecture mirrors real-world team dynamics, where specialists handle distinct tasks, and a manager synthesizes their findings.

Building the Financial Advisory System

Our goal is to create a financial advisory system with the following capabilities:

  1. Portfolio Analysis: Evaluate stock portfolios to identify risks and opportunities.
  2. Sentiment Assessment: Fetch real-time news and analyze its sentiment for portfolio stocks.
  3. Risk Evaluation: Flag stocks with high volatility or downward trends.
  4. Comprehensive Reporting: Generate a consolidated report summarizing all insights.

Link for the data

Step 1: Setting Up the Environment

Start by installing the required libraries:

pip install --quiet openai pandas matplotlib phidata duckduckgo-search

Set your OpenAI API key to authenticate requests:

OPENAI_API_KEY = "your_openai_api_key"
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY

Step 2: Defining Individual Agents

We’ll define three specialized agents:

1. Portfolio Analysis Agent

  • Purpose: Analyze stock portfolios for risks and opportunities.
  • Tools Used: Yahoo Finance API for real-time stock data.
  • Tasks:
  • Calculate profit/loss for each stock.
  • Provide diversification insights.

2. News Sentiment Agent

  • Purpose: Fetch real-time news and analyze sentiment for portfolio stocks.
  • Tools Used: DuckDuckGo for news search.
  • Tasks:
  • Fetch the latest news articles for each stock.
  • Classify sentiment as Positive, Negative, or Neutral.

3. Risk Analysis Agent

  • Purpose: Identify high-volatility stocks and those with downward trends.
  • Tools Used: Yahoo Finance API.
  • Tasks:
  • Flag stocks with significant volatility.
  • Highlight stocks with negative performance trends.

Here’s the Python code to define these agents:

from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.tools.yfinance import YFinanceTools
from phi.tools.duckduckgo import DuckDuckGo
from dotenv import load_dotenv
from IPython.display import Markdown, display

# Portfolio Analysis Agent
portfolio_analysis_agent = Agent(
name="Portfolio Analysis Agent",
role="Analyze stock portfolios for risks and opportunities.",
model=OpenAIChat(id="gpt-4"),
tools=[YFinanceTools(stock_price=True, analyst_recommendations=True)],
instructions=[
"Analyze the portfolio and calculate profit/loss for each stock.",
"Provide diversification and risk insights."
],
show_tool_calls=True
)
# News Sentiment Agent
news_analysis_agent = Agent(
name="News Sentiment Agent",
role="Fetch real-time news and analyze sentiment for portfolio stocks.",
model=OpenAIChat(id="gpt-4"),
tools=[DuckDuckGo()],
instructions=[
"Fetch the latest news for each stock and classify sentiment as Positive, Negative, or Neutral."
],
show_tool_calls=True
)
# Risk Analysis Agent
risk_prediction_agent = Agent(
name="Risk Analysis Agent",
role="Identify high-volatility or downward-trending stocks.",
model=OpenAIChat(id="gpt-4"),
tools=[YFinanceTools()],
instructions=["Flag stocks with high volatility or downward trends."],
show_tool_calls=True
)

Step 3: Workflow Functions

To streamline the process, define utility functions for tasks like loading the portfolio, calculating profit/loss, and generating the final report.

def load_portfolio(file_path: str):
"""Load the user's investment portfolio from a CSV file."""
return pd.read_csv(file_path)

def calculate_profit_loss(portfolio_df):
"""Calculate profit/loss for each stock."""
portfolio_df["Profit/Loss"] = (portfolio_df["Current_Price"] - portfolio_df["Purchase_Price"]) * portfolio_df["Shares"]
return portfolio_df

def display_report(report: str):
"""Display a formatted report in Jupyter Notebook."""
display(Markdown(report))

def generate_report(portfolio_df):
"""Generate a comprehensive report."""

portfolio_analysis = portfolio_analysis_agent.run(f"""
Analyze the following portfolio:
{portfolio_df.to_dict(orient="records")}
""")

print("\n################################# Portfolio Analysis #################################")
display_report(portfolio_analysis.content)
print("########################################################################################")

# Step 2: News Sentiment Analysis
news_sentiment = news_analysis_agent.run(f"""
Fetch and analyze news for the following stocks:
{portfolio_df['Stock'].tolist()}
""")

# Display News Sentiment
print("\n################################# News Sentiment #####################################")
display_report(news_sentiment.content)
print("########################################################################################")
final_report = smart_financial_advisor.run(f"Prepare portfolio report for the following portfolio {portfolio_df.to_dict('records')}")
print("####################################### Final Report ###################################")
display_report(final_report.content)

Step 4: Executing the Analysis

Let’s bring it all together:

portfolio_file = "portfolio.csv"
# Load and process the portfolio
portfolio = load_portfolio(portfolio_file)
portfolio = calculate_profit_loss(portfolio)
# Generate and display the report
generate_report(portfolio)

Results:

Conclusion

By leveraging Phidata’s agentic framework, we’ve created a robust multi-agent financial advisory system. Each agent specializes in a distinct task, and together they generate a comprehensive financial report. This modular approach ensures scalability and adaptability for future needs.

Phidata’s emphasis on modularity and tool integration empowers developers to build systems that are efficient, maintainable, and highly extensible.

Found this guide helpful? Share it with your network, save it for future reference and let’s connect and explore more exciting agentic frameworks and their use case in real world business problems.

To connect with me on this and other AI related topics:

kshitijkutumbe@gmail.com

References:

--

--

Kshitij Kutumbe
Kshitij Kutumbe

Written by Kshitij Kutumbe

Data Scientist | NLP | GenAI | RAG | AI agents | Knowledge Graph | Neo4j kshitijkutumbe@gmail.com www.linkedin.com/in/kshitijkutumbe/

No responses yet