Making a Financial Conversation Agent using Agno & Maxim

Making a Financial Conversation Agent using Agno & Maxim

In today's fast-paced financial world, having instant access to market data, company information, and financial insights is crucial for investors, analysts, and financial professionals. In this comprehensive tutorial, we'll build a sophisticated financial conversational agent that combines the power of multiple AI models with real-time financial data and web search capabilities.

What We'll Build

By the end of this tutorial, you'll have created a multi-agent financial assistant that can:

  • Fetch real-time stock prices and financial data using YFinance
  • Search the web for the latest financial news and information
  • Provide analyst recommendations and company insights
  • Handle complex financial queries through natural conversation
  • Display data in well-formatted tables and reports

Prerequisites

Before we begin, ensure you have:

  • Python 3.8 or higher installed
  • Basic knowledge of Python programming
  • OpenAI API key (or Google Gemini API key)
  • Understanding of financial markets (helpful but not required)

Required Libraries

We'll be using several powerful libraries:

  • Agno: A framework for building AI agents with tool integration
  • Maxim AI: For enhanced observability and logging
  • YFinance: For fetching financial data
  • Google Search Tools: For web search capabilities
  • OpenAI/Gemini: For language model integration

The code of this agent can be accessed here - Maxim Cookbook

Step 1: Setting Up the Environment

First, let's install the required packages and set up our environment:

You can pip or uv to install the following dependencies or add them in pyproject.toml -

dependencies = [
    "agno",
    "openai",
    "google-genai",
    "python-dotenv",
    "ddgs",
    "yfinance",
    "googlesearch-python",
    "pycountry",
    "maxim-py",
]

Create a .env file in your project directory with your API keys:

GOOGLE_API_KEY=

Now, let's import all the necessary libraries:

from dotenv import load_dotenv
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.googlesearch import GoogleSearchTools
from agno.tools.yfinance import YFinanceTools
from maxim import Maxim
from maxim.logger.agno import instrument_agno

Step 2: Loading Environment Variables and Setting Up Logging

The first step in our application is to load environment variables and set up enhanced logging with Maxim:

# Load environment variables from .env file
load_dotenv()

# Instrument agno with Maxim's logger for enhanced observability
instrument_agno(Maxim().logger())

Why this matters:

  • Environment variables keep your API keys secure
  • Maxim's logging provides detailed insights into agent interactions
  • Enhanced observability helps debug and monitor agent performance

Step 3: Creating the Web Search Agent

Our first agent specializes in searching the web for financial information:

# Web Search Agent: Fetches financial information from the web
web_search_agent = Agent(
    name="Web Agent",
    role="Search the web for information",
    model=OpenAIChat(id="gpt-4o"),
    tools=[GoogleSearchTools()],
    instructions="Always include sources",
    show_tool_calls=True,
    markdown=True,
)

Key features:

  • Uses GPT-4o for intelligent query processing
  • Integrated with Google Search through GoogleSearchTools
  • Always includes sources for transparency
  • Outputs responses in markdown format

Step 4: Creating the Finance Agent

Our second agent focuses on retrieving structured financial data:

finance_agent = Agent(
    name="Finance Agent",
    role="Get financial data",
    model=OpenAIChat(id="gpt-4o"),
    tools=[YFinanceTools(
        stock_price=True,
        analyst_recommendations=True,
        company_info=True
    )],
    instructions="Use tables to display data",
    markdown=True,
)

Capabilities:

  • Real-time stock price data
  • Analyst recommendations and ratings
  • Comprehensive company information
  • Data presented in clean, readable tables

Step 5: Creating the Multi-Agent System

Now we'll combine both agents into a unified system:

# Aggregate both agents into a multi-agent system
multi_ai_agent = Agent(
    team=[web_search_agent, finance_agent],
    model=OpenAIChat(id="gpt-4o"),
    instructions="You are a helpful financial assistant. Answer user questions about stocks, companies, and financial data.",
    show_tool_calls=True,
    markdown=True
)

Benefits of the multi-agent approach:

  • Specialized agents handle specific tasks efficiently
  • Seamless coordination between different data sources
  • Improved response quality through task specialization
  • Better error handling and fallback mechanisms

Step 6: Building the Interactive Interface

Finally, let's create the main interactive loop:

if __name__ == "__main__":
    print("Welcome to the Financial Conversational Agent! Type 'exit' to quit.")
    messages = []

    while True:
        print("********************************")
        user_input = input("You: ")

        if user_input.strip().lower() in ["exit", "quit"]:
            print("Goodbye!")
            break

        # Add user message to conversation history
        messages.append({"role": "user", "content": user_input})

        # Build conversation context
        conversation = "\\n".join([
            ("User: " + m["content"]) if m["role"] == "user"
            else ("Agent: " + m["content"])
            for m in messages
        ])

        # Get response from multi-agent system
        response = multi_ai_agent.run(
            f"Conversation so far:\\n{conversation}\\n\\nRespond to the latest user message."
        )

        agent_reply = getattr(response, "content", response)
        print("---------------------------------")
        print("Agent:", agent_reply)

        # Add agent response to conversation history
        messages.append({"role": "agent", "content": str(agent_reply)})

How It Works

Agent Coordination

The multi-agent system intelligently routes queries to the appropriate agent:

  1. Stock price queries → Finance Agent (YFinance)
  2. News and analysis → Web Search Agent (Google Search)
  3. Complex queries → Both agents working together

Conversation Memory

The system maintains conversation history, allowing for:

  • Follow-up questions
  • Contextual responses
  • Reference to previous queries

Error Handling

Built-in error handling ensures:

  • Graceful degradation when APIs are unavailable
  • Informative error messages
  • Fallback to alternative data sources

Example Usage

Here are some example queries you can try:

You: What's the current stock price of Apple?
Agent: [Fetches real-time AAPL data with price, volume, and key metrics]

You: Give me the latest news about Tesla
Agent: [Searches web for recent Tesla news with sources]

You: Compare Microsoft and Google's financial performance
Agent: [Combines financial data and recent analysis for both companies]

Advanced Features

Custom Instructions

You can customize agent behavior by modifying the instructions parameter:

finance_agent = Agent(
    # ... other parameters
    instructions="Focus on risk analysis and provide conservative investment advice. Always include disclaimer about financial risks."
)

Model Flexibility

The system supports multiple LLM providers:

# OpenAI
model=OpenAIChat(id="gpt-4o")

# Google Gemini (commented in original code)
# model=Gemini(id="gemini-2.0-flash-001")

Enhanced Observability

Maxim provides detailed logging for:

  • Agent interactions
  • Tool usage
  • Performance metrics
  • Error tracking
0:00
/0:12

Extending the System

Adding New Agents

You can easily add specialized agents:

news_agent = Agent(
    name="News Agent",
    role="Financial news analysis",
    model=OpenAIChat(id="gpt-4o"),
    tools=[NewsAPITools()],
    instructions="Provide sentiment analysis for financial news"
)

Custom Tools

Create custom tools for specific financial APIs:

class CustomFinancialTool:
    def get_crypto_data(self, symbol: str):
        # Custom implementation
        pass

Web Interface

Consider building a web interface using Flask or FastAPI:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/query', methods=['POST'])
def handle_query():
    user_query = request.json['query']
    response = multi_ai_agent.run(user_query)
    return jsonify({'response': str(response)})

Conclusion

We've successfully built a sophisticated financial conversational agent that combines multiple AI models with real-time data sources. The system can handle complex financial queries, provide up-to-date market information, and maintain conversational context.

Key Takeaways

  1. Multi-agent architecture provides better specialization and performance
  2. Agno framework simplifies AI agent development and tool integration
  3. Maxim logging offers valuable insights into agent behavior
  4. Modular design makes the system easy to extend and maintain

Disclaimer: This tutorial is for educational purposes only. Always consult with qualified financial advisors before making investment decisions.