How to Build an AI Investment Analyst Agent?

Introduction

Investing in stocks and other assets is an interesting affair but it can be very challenging and hectic even for the better of us. Now, imagine having a personal analyst who follows news, and trends, and advises financial strategy based on his observation. Sounds great, right? But let’s be honest most of us are not blessed enough to hire a personal financial analyst. But what if you have an intelligent financial analyst who works round the clock and keeps you updated with trends? Thanks to the recent advancement in AI technologies, you can create a personal financial analyst within a few minutes.

This article demonstrates how to build an AI investment analyst using CrewAI, Gemini models, and Composio.

Learning Objectives

  • Learn about the basics of CrewAI and Composio.
  • Understand the workflow of the AI investment analyst.
  • Build an AI investment analyst agent with CrewAI and Composio.

What is CrewAI?

CrewAI is an open-source framework for building collaborative multi-agent systems. It allows developers to build complex agentic automation workflows where interaction among multiple agents is paramount. CrewAI allows individual AI agents to assume roles, delegate tasks, and share goals akin to a real-world crew. CrewAI mainly consists of five core features Agents, Tasks, Tools, Processes, and Tasks.

  • Agents: Agents operate as autonomous entities tasked with reasoning, delegating tasks, and communicating with fellow agents, much like a team in the real world.
  • Tasks: Tasks are precise assignments allocated to agents. They outline the steps and actions required for an agent to achieve a specific goal.
  • Tools: Tools equip agents to carry out tasks that exceed the capabilities of LLMs, such as web scraping, email responses, and task scheduling.
  • Process: In CrewAI, processes manage the execution of tasks by agents, ensuring that tasks are allocated and performed effectively and systematically. These processes can be sequential, where tasks are completed one after another, or hierarchical, where tasks are carried out based on a tiered authority structure.
  • Crews: Crews within CrewAI consist of collaborative agents equipped with tasks and tools, all working together to tackle complex tasks.

Here is a mind map for CrewAI.

What is Composio?

Composio is an open-source production-ready tooling solution for AI agents. It enables developers to seamlessly integrate external tools and applications with AI agents while handling OAuth and other authentication mechanisms crucial for deploying AI agents in real-world scenarios.

Composio has over 150 tools and integrations in its repertoire to accommodate a range of functionalities. These tools enable developers to customize AI agents for specific tasks, for instance, automating user feedback collection with Typeform, managing data flows with Google Sheets for CRM integration and trend analysis, or coordinating projects effectively using Jira and Trello. This versatility allows for highly customized and efficient workflows tailored to meet specific operational demands. For more information check out the documentation page.

This tutorial will use Composio’s SerpAPI tool for web search and information gathering.

Agent Workflow

Now, let’s explore the workflow of our AI investment analyst. We will use CrewAI to build a collaborative crew of agents. The crew will have a researcher, an analyst, and a recommender agent. Individual agents will have goals and backstories to give more context to the LLM about the agent before doing the task. The agents will have access to the necessary tools. We will equip the agents with a web search tool in this case. We will use SerpApi, so grab an API key.

And for LLM, we will use Google Gemini Pro. So, get your API key from Google AI Studio. You can use any other LLM as well.

The workflow starts with the user sending the query to the crew. The researcher agent picks up the query and searches the web to gather resources regarding the query. The search results are passed to the analyst agent to analyze the information and prepare a report. Finally, the report is sent to the recommender agent to give well-rounded advice on whether to invest or not.

Building the Agent

Now, that you know the workflow, the next step is to code the agent. First, as with any Python project, create a virtual environment and install the necessary dependencies. We will need CrewAI, Langchain, Composio, and SerpApi.

pip install composio-langchain
pip install composio-core
pip install langchain-community
pip install google-search-results
pip install python-dotenv

Add Gemini API key and SerpApi key to a .env file.

SERP_API_KEY = "Your Key"
GOOGLE_API_KEY = "Your Key"

Add the SerpApi to your Composio account.

# Connect your serpapi so agents can use it.

composio add serpapi

Import the necessary modules.

from crewai import Agent, Task, Crew, Process
from composio_langchain import ComposioToolSet, Action, App
from langchain_google_genai import ChatGoogleGenerativeAI
from dotenv import load_dotenv
import os
load_dotenv()

Now initialize the language model.

llm = ChatGoogleGenerativeAI(
model="gemini-pro", verbose=True, temperature=0.9, google_api_key=os.getenv("GOOGLE_API_KEY")
)

Define tools for the agents.

composio_toolset = ComposioToolSet()
tools = composio_toolset.get_actions(actions=[Action.SERPAPI_SEARCH])

Defining the Agent

The next step is to define the agents, with goals, and backstories. As mentioned earlier, there are three agents, a researcher, an analyst, and a recommender. We will define the agents using CrewAI.

 # Define the Investment Researcher agent
 researcher = Agent(
     role='Investment Researcher',
     goal='Use SERP to research the top 2 results based on the input given to you and provide a report',
     backstory="""
     You are an expert Investment researcher. Using the information given to you, conduct comprehensive research using
     various sources and provide a detailed report. Don't pass in location as an argument to the tool
     """,
     verbose=True,
     allow_delegation=True,
     tools=tools,
     llm=llm
 )
 # Define the Investment Analyst agent
 analyser = Agent(
     role='Investment Analyst',
     goal='Analyse the stock based on information available to it, use all the tools',
     backstory="""
     You are an expert Investment Analyst. Your research on the given topic and analyze your research for insights.
     Note: Do not use SERP when you're writing the report
     """,
     verbose=True,
     tools=tools,
     llm=llm
 )

 # Define the Investment Recommender agent
 recommend = Agent(
     role='Investment Recommendation',
     goal='Based on the analyst insights, you offer recommendations',
     backstory="""
     You are an expert Investment Recommender. You understand the analyst insights and with your expertise suggest and offer
     advice on whether to invest or not. List the Pros and Cons as bullet points
     """,
     verbose=True,
     tools=tools,
     llm=llm
 )

Each agent has a defined role, goal, tools, and a backstory. This provides LLMs with extra information about the agent, which aids in grounding the responses of the LLM.

Defining Task and Kickoff the Process

Now, define the task for the analyst agent.

# Get user input for the research topic
user_input = input("Please provide a topic: ")

# Define the task for the analyst agent
analyst_task = Task(
    description=f'Research on {user_input}',
    agent=analyser,
    expected_output="When the input is well researched, thoroughly analyzed and recommendation is offered"
)

# Create the crew with the defined agents and task
investment_crew = Crew(
    agents=[researcher, analyser, recommend],
    tasks=[analyst_task],
    verbose=1,
    full_output=True,
)

# Execute the process

res = investment_crew.kickoff()

Putting it all together.

from crewai import Agent, Task, Crew, Process
from composio_langchain import ComposioToolSet, Action, App
from langchain_google_genai import ChatGoogleGenerativeAI
import os

# Environment Setup
os.environ["SERPAPI_API_KEY"] = os.getenv("SERPAPI_API_KEY")

# Initialize the language model
llm = ChatGoogleGenerativeAI(
    model="gemini-pro", verbose=True, temperature=0.9, google_api_key=os.getenv("GOOGLE_API_KEY")
)

# Define tools for the agents
composio_toolset = ComposioToolSet()
tools = composio_toolset.get_actions(actions=[Action.SERPAPI_SEARCH])

# Define the Investment Researcher agent
researcher = Agent(
    role='Investment Researcher',
    goal='Use SERP to research the top 2 results based on the input given to you and provide a report',
    backstory="""
    You are an expert Investment researcher. Using the information given to you, conduct comprehensive research using
    various sources and provide a detailed report. Don't pass in location as an argument to the tool
    """,
    verbose=True,
    allow_delegation=True,
    tools=tools,
    llm=llm
)

# Define the Investment Analyst agent
analyser = Agent(
    role='Investment Analyst',
    goal='Analyse the stock based on information available to it, use all the tools',
    backstory="""
    You are an expert Investment Analyst. You research the given topic and analyze your research for insights.
    Note: Do not use SERP when you're writing the report
    """,
    verbose=True,
    tools=tools,
    llm=llm
)

# Define the Investment Recommender agent
recommend = Agent(
    role='Investment Recommendation',
    goal='Based on the analyst insights, you offer recommendations',
    backstory="""
    You are an expert Investment Recommender. You understand the analyst insights and with your expertise suggest and offer
    advice on whether to invest or not. List the Pros and Cons as bullet points
""",
verbose=True,
tools=tools,
llm=llm
)

# Get user input for the research topic
user_input = input("Please provide a topic: ")

# Define the task for the analyst agent
analyst_task = Task(
    description=f'Research on {user_input}',
    agent=analyser,
    expected_output="When the input is well researched, thoroughly analyzed and recommendation is offered"
)

# Create the crew with the defined agents and task
investment_crew = Crew(
    agents=[researcher, analyser, recommend],
    tasks=[analyst_task],
    verbose=1,
    full_output=True,
)

# Execute the process
res = investment_crew.kickoff()

Once you execute the script, the agent workflow will kick start and you can see the logs in your terminal.

Conclusion

In this tutorial, you developed an AI investment analyst utilizing CrewAI, Gemini, and Composio. We initially implemented a basic web search tool. To enhance the agent’s capabilities, consider integrating a tool like Yahoo Finance, which provides detailed financial data. Additionally, incorporating a code interpreter with the Yahoo Finance tool will enable the agent to conduct sophisticated data analysis and create visual representations. This expansion allows for a more diverse and robust analysis capability, adapting to various financial scenarios and data requirements.

For additional tutorials, explore Composio’s collection of example use cases.

Resources