Read for free here.

Have you ever felt lost in the stock market? Or wished you could ask someone (or something) to make sense of all the financial jargon and its vast data? You are not alone; I am one of you. To simplify my life, I started working on combining two of my interests — finance and conversational AI. My aim is simple: build an AI chatbot that I can ask questions in plain English, and it does all the analysis and gives results in an easy-to-understand form. The current chatbot, StockWise, is in the very early phase, but I’m excited to share what I have learnt and how things are coming together.

The Challenge: Making Sense of Market Madness

The stock market can feel overwhelming; there is continuous new information, from real-time prices to complex financial reports. This creates some of the major challenges —

  • Information Overload: There is just so much data; it's very hard to know where to even start.
  • Jargon Jungle: Financial terms are like a secret language that does not make sense to most people.
  • Analysis Anxiety: Traditional stock market analysis requires many professional tools and knowledge. Most of the time, these tools aren’t even present on a single platform. Due to which most of the investors aren’t able to use the right tool or waste too much time to consolidate all.

I want to build a tool that can break down all these barriers so that anyone can use it and make sense of the stock market, irrespective of their background and knowledge. That’s where the AI Chatbot Agent comes into the picture, which can streamline all the processes related to the market and make it easy to grasp for everyone.

What is an AI agent?

Before we proceed further, let’s quickly understand what an “AI agent” is. You can think of them as an AI system that goes beyond simply answering questions. They can take actions, make decisions, and interact with other systems to achieve specific goals. In my case, the goal is to navigate the stock market. It is done by following:

  • Understand requests: Ask questions in simple, plain English, and the agent will figure out what we are looking for.
  • Gather information: Once it understands the requests, based on need, it can access different data sources, including local and external data sources, to gather all the required information.
  • Analyse and Explain: Once all the required pieces of information are available to it, it does not just give raw data; it analyses all that information and explains it in easy-to-understand language.

How My AI Chatbot Agent Works: A Peek Under the Hood

My AI Chatbot Agent, StockWise, combines multiple technologies and concepts to achieve its goal —

  • Retrieval Augmented Generation (RAG): At its core, the agent uses RAG architecture. This means it doesn’t just rely on its existing knowledge; it actively retrieves relevant information to provide the most accurate and up-to-date answers. It’s like having a super-smart research assistant built in! It fetches information from local and external data sources, combines it with the question and uses a powerful large language model (LLM) to generate a clear and helpful response.
  • Gemini: This is the brain, the core reasoning engine of the agent. It’s a large language model (LLM) that can understand the questions, figure out what information is needed and how to get that required information, and generate an easy-to-understand response.
  • LangGraph: This is the framework that helps me to design the agent’s conversation flow. It makes sure that the agent can follow along, remember what’s already been asked and help the LLM to provide the correct answer that makes sense in that context. At the core, it uses the state machine concept in a graph structure. It uses nodes to represent specific actions (like chatbot response, user input, executing different tools, etc.), and edges represent the flow of control based on conversation state.

Key Capabilities of the AI Agent: Custom Tools Integration

To make this agent, StockWise, truly useful, I have integrated it with several tools. These tools are specialised Python functions/methods that the agent can use to perform several tasks —

  • Database Interaction: In the current agent, I am making use of a simple SQLite database to store historical stock data. This database acts like a simple cache to reduce reliance on external API/datasource and speed up retrieval for previously fetched data. The agent uses different tools like list_tables, describe_table, execute_query etc., to interact with the database. A database integration tool can be very easy to implement, for example —
from langchain_core.tools import tool

@tool
def execute_query(sql: str) -> List[List[Any]]:
"""Executes an SQL query and returns the results."""

print(f' - DB CALL: execute_query({sql})')
conn = connect_db()
try:
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
return cursor.fetchall()
except sqlite3.Error as e:
print(f"Error executing query: {e}")
return []
finally:
if conn:
conn.close()
  • External Data Retrieval: To fetch historical data, the agent needs to make use of an external API using tools like fetch_bse_historical_data. Here I am using the API from Alpha Vantage, but feel free to use any other external data source.
  • News Summarisation: The agent needs to have the latest news about the mentioned company, so it uses fetch_news_summary tool. Here, the tool is not just a simple Python function; it uses Gemini, the LLM, to fetch all the latest developing news and summarise the same. You can easily implement it, which proves that a custom tool doesn’t need to be just a simple Python function; it can be anything —
from langchain_google_genai import ChatGoogleGenerativeAI
from google.genai import types
from google import genai

client = client = genai.Client(api_key=GOOGLE_API_KEY)

config_with_search = types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
temperature=0.0,
)

@tool
def fetch_news_summary(company_name: str) -> str:
"""
Uses Gemini to search for and summarize news about a given company.

Args:
company_name: The name of the company (e.g., "Reliance Industries").

Returns:
A string containing a summary of the latest news for the given company.
Returns an error message if news retrieval fails.

Raises:
Exception: If any error occurs during the Gemini API call.
"""

print(f' - Tool CALL: fetch_news_summary for {company_name}')

try:
response = client.models.generate_content(
model='gemini-2.0-flash',
contents=f"""You are StockWise, a helpful and knowledgeable chatbot that provides stock analysis and recommendations for the Bombay Stock Exchange (BSE).
Please provide a summary of the following, based on the latest news for {company_name}:
* Key events impacting the stock price
* Changes in analyst ratings
* Significant company announcements
""",
config=config_with_search,
)

response_content = ""
if response and response.candidates and response.candidates[0].content.parts:
for part in response.candidates[0].content.parts:
if part.text:
response_content += part.text
return response_content
else:
return f"Could not retrieve news summary for {company_name}"

except Exception as e:
error_message = f"Error retrieving news summary for {company_name}: {str(e)}"
return error_message

Keeping the Conversation Going: Maintaining Context

LangGraph’s state management capabilities are crucial for creating a natural and intuitive conversational experience. They help agents to remember the context of the conversation. This means if we ask about a specific stock, the agent will remember it, and we don’t need to mention the same information again and again, which makes conversation much smoother and natural.

In my case, I am using a simple TypedDict to maintain conversation state across different steps —

from typing import Annotated, List, Dict, Any, Optional
from typing_extensions import TypedDict
from langgraph.graph.message import add_messages

# --- State Definition ---
class StockAnalysisState(TypedDict):
"""
Represents the state of the stock analysis conversation.
"""
messages: Annotated[list, add_messages]
finished: Optional[bool]
api_outputs: Dict[str, List[Dict[str, Any]]] | None

Crafting the Agent’s Personality: Prompt Engineering

I’ve also spent quite some time crafting the agent’s “persona” through prompt engineering. This involves carefully providing specific instructions to tune its behaviours, communication style, creativity, and other aspects. You can imagine it like training a puppy or a human baby.

For example, the system prompts instruct the agent to —

  • Behave as a “helpful and knowledgeable chatbot”
  • Provide “stock analysis and recommendations”
  • Focus on the “Bombay Stock Exchange (BSE)”

These careful prompt engineering helps the chatbot agent to communicate effectively and only focus on information related to the specific goal, instead of running its thoughts across and deviating from the actual task at hand.

Why This Chatbot Agent Matters: The Real-World Impact

I believe this AI Chatbot Agent, StockWise, can make real-life difference for investors in several ways —

  • Democratising Access: By simplifying complex financial information, it lowers the barriers for, but is not limited to, new and part-time investors and helps everyone to participate in the stock market with better confidence.
  • Unlocking Efficiency: Investors can quickly gather information and make informed decisions without wasting time juggling between multiple platforms and mountains of raw data, which overall saves valuable time and effort.
  • Fueling Smarter Decisions: Contextual insights and clear explanations help investors to truly understand the data, which leads to better-informed decisions.
  • Personalised Financial Advisory: It can analyse and recommend stocks based on personal risk tolerance, investment goals, and financial circumstances.
  • Scalable Growth: The modular architecture of the system allows seamless expansions to cover global markets and different investment segments.

The Journey Ahead: A Glimpse into the Future

I’m very excited about the journey ahead with StockWise. There are uncapped possibilities, and I see it evolving in several key directions —

  • Global Market Expansion: Even though the current agent implementation focuses on the Bombay Stock Exchange (BSE), it can be very easily extended to global markets like NYSE, NASDAQ, Euronext etc. This would help investors to have better knowledge across markets.
  • Multi-Asset Class Analysis: Beyond stocks, it can be easily extended to analyse other assets, including Bonds, ETFs, Mutual Funds, commodities, and even cryptocurrencies. This would make it a truly versatile tool for portfolio management.
  • Integrate real-time data: Current implementation uses historical data (till last market date) to analyse and recommend; in the future, it can be easily integrated with a real-time data feed to have real-time analysis.
  • Enhanced Predictive Capabilities: In the long term, it can grow towards better predictive analysis, thus improving its recommendations and more accurate forecasts. This would require careful consideration of ethical implications and potential biases.

These are just the tip of the iceberg; here the limit is our imagination.

Conclusion

Building this AI chatbot agent, StockWise, is just more than a simple hobby project; it can help individuals to take control of their future finances. By combining the power of AI with a conversational approach, I believe we can easily lower the financial background barriers for everyone, democratise access to financial information, and create a more informed and confident investing community. The journey is ongoing, and I’m eager to find out what lies in the future.

You can find the working Chatbot Agent on Kaggle.

P.S: Feel free to reach out to me if you have any questions or feedback 😄.

Originally posted on medium.com.