Build a Financial Agent with LangGraph: Beginner's Tutorial

Updated on Jul 27,2025

Table of Contents

In today's rapidly evolving financial landscape, accessing and analyzing real-time data is crucial for making informed investment decisions. This tutorial provides a comprehensive guide on building a sophisticated financial agent using LangGraph, a powerful framework for creating AI-powered applications. This financial agent will be capable of retrieving stock prices, gathering the latest news, accessing detailed financial reports, and tracking historical price data. This guide is tailored for beginners and will walk you through each step with clear explanations and practical examples.

Key Points

Building a financial agent using LangGraph for beginners.

Capabilities: stock price checks, latest news, financial reports, historic prices.

Using LangGraph and the Polygon API for financial data.

Creating tools, assigning them to an agent, and building a graph.

Integrating a user interface with Gradio.

Creating a Financial Agent with LangGraph

Introduction to Financial Agents and LangGraph

A financial agent is an AI-powered tool that can automate financial tasks such as gathering information, analyzing data, and generating reports. These agents can be incredibly helpful for investors, analysts, and anyone who needs to stay on top of the market.

LangGraph is a framework designed for building conversational AI applications. It allows developers to create complex, multi-step workflows where different components of the AI system can interact and collaborate. LangGraph simplifies the development process by providing a modular and extensible architecture.

This Tutorial focuses on building a financial agent capable of:

  • Checking stock prices: Retrieving current stock prices for a given company.
  • Getting the latest news: Accessing recent news articles related to a specific company.
  • Accessing financial reports: Obtaining detailed financial reports, such as income statements, balance sheets, and cash flow statements.
  • Getting historical prices: Tracking historical price data for a company's stock.

Setting Up Your Development Environment

Before diving into the code, it's essential to set up your development environment. This involves installing the necessary software and libraries, and configuring your API keys.

  1. Install Anaconda: If you haven't already, download and install Anaconda, a popular Python distribution that includes conda, a package and environment management system. Anaconda can be downloaded from the Anaconda website.

  2. Create a Conda Environment: Use conda to create a virtual environment for your LangGraph project. This helps isolate your project's dependencies from other projects on your system.

    conda create -n langgraph python=3.11
    conda activate langgraph

    This command creates an environment named 'langgraph' with Python 3.11.

  3. Install Required Packages: Install the necessary Python packages using pip:

    pip install langgraph langchain langchain_openai langchainhub polygon-api-client gradio

    This command installs LangGraph, Langchain, OpenAI integration, Langchain Hub, Polygon API client, and Gradio.

  4. Set Up API Keys: To access financial data, you'll need API keys from OpenAI and Polygon. Sign up for free accounts on their respective websites and obtain your API keys. Then, set these keys as environment variables:

    export OPENAI_API_KEY=YOUR_OPENAI_API_KEY
    export POLYGON_API_KEY=YOUR_POLYGON_API_KEY

    Replace YOUR_OPENAI_API_KEY and YOUR_POLYGON_API_KEY with your actual API keys. Polygon is the API service providing financial information.

Building the Financial Agent: Step-by-Step

Now, let's start building the financial agent. This process involves several key steps:

  1. Defining the Tools: The first step is to define the tools our agent can use. These tools will be responsible for fetching financial data from external sources.

    import os
    from langchain import hub
    from langchain.agents import create_openai_functions_agent
    from langchain_openai import ChatOpenAI
    from langchain_community.utilities.polygon import PolygonAPIWrapper
    from langchain_community.tools import PolygonLastQuote, PolygonTickerNews, PolygonFinancials, PolygonAggregates
    
    prompt = hub.pull("hwchase17/openai-functions-agent")
    llm = ChatOpenAI(model="gpt-4-turbo-preview")
    polygon = PolygonAPIWrapper()
    tools = [
        PolygonLastQuote(api_wrapper=polygon),
        PolygonTickerNews(api_wrapper=polygon),
        PolygonFinancials(api_wrapper=polygon),
        PolygonAggregates(api_wrapper=polygon)
    ]

    Here, we import the necessary libraries and define the tools our agent will use: PolygonLastQuote, PolygonTickerNews, PolygonFinancials, and PolygonAggregates. These tools leverage the Polygon API to retrieve real-time stock quotes, news articles, financial statements, and aggregated data. The code imports the required modules and sets up the prompt template from LangChain Hub, which can be found at hwchase17/openai-functions-agent. This Prompt template defines the system message and user input structure for the AI agent.

    • os: Provides a way of using operating system dependent functionality.
    • langchain: Framework for developing applications powered by language models.
    • hub: Langchain Hub for accessing pre-built prompts and chains.
    • create_openai_functions_agent: Utility to create an OpenAI functions agent.
    • ChatOpenAI: Integrates OpenAI's chat models.
    • PolygonAPIWrapper: Wrapper for the Polygon.io API.
    • PolygonLastQuote: Tool to fetch the last quote of a stock.
    • PolygonTickerNews: Tool to fetch news about a ticker.
    • PolygonFinancials: Tool to retrieve financial data for a ticker.
    • PolygonAggregates: Tool to aggregate data for a ticker.
  2. Defining the Agent: Now, we define the agent itself. This involves specifying the language model, tools, and prompt template that the agent will use.

    from langchain_core.runnables import RunnablePassThrough
    from langchain_core.agents import AgentFinish
    
    agent_runnable = create_openai_functions_agent(llm, tools, prompt)
    agent = RunnablePassThrough.assign(agent_outcome=agent_runnable)
    
    def execute_tools(data):
        agent_action = data.pop("agent_outcome")
        tool_to_use = {t.name: t for t in tools}[agent_action.tool]
        observation = tool_to_use.invoke(agent_action.tool_input)
        data["intermediate_steps"].append((agent_action, observation))
        return data
    
    def should_continue(data):
        if isinstance(data["agent_outcome"], AgentFinish):
            return "exit"
        else:
            return "continue"

    This section defines the agent's behavior and how it interacts with the tools. The create_openai_functions_agent function creates an agent that uses OpenAI's function-calling capability. RunnablePassThrough assigns the agent's outcome for processing. The execute_tools function is responsible for executing the tools based on the agent's decisions. The should_continue function determines whether the agent should continue its workflow or exit, based on whether a final answer has been reached.

  3. Defining the LangGraph: LangGraph uses graphs to define the flow of execution. We will add our agent and tools as nodes in the graph and define the transitions between them.

    from langgraph.graph import END, Graph
    
    workflow = Graph()
    workflow.add_node("agent", agent)
    workflow.add_node("tools", execute_tools)
    workflow.set_entry_point("agent")
    workflow.add_conditional_edges(
        "agent",
        should_continue,
        {
            "continue": "tools",
            "exit": END
        }
    )
    workflow.add_edge("tools", "agent")
    chain = workflow.compile()

    The LangGraph part involves constructing the graph that dictates how the agent and tools interact. Nodes are added for the agent and the tools execution. An entry point is set to begin with the agent. Conditional edges are defined to determine whether the agent should continue to use tools or exit. A standard edge connects the tools back to the agent, creating a loop.
    The should_continue function defines the logic that will be used to determine which conditional edge to go down. If the agent_outcome data instance is AgentFinish, then exit, else continue to the tools. The add_conditional_edges use the agent for the step and the should_continue to choose which route it’s going to take between the continue and the tools. If it requires tools, it executes, otherwise it exits. This ensures the tool's output should be sent to the agent.

  4. Running the Agent: With the graph defined, we can now run the agent and get a response.

    result = chain.invoke({"input": "What has been ABNB's daily closing price between March 7, 2024 and March 14, 2024?", "intermediate_steps": []})
    output = result["agent_outcome"].return_values["output"]
    print(output)

    This code invokes the LangGraph chain and asks for ABNB’s daily closing price between the specified dates. This invokes function provides the financial summary. The agent and the tool will get the output from the large language model. The Large Language Models need to get the stock price and return the real-time stock price value. The data then returns.

Adding a User Interface with Gradio

Creating the Gradio Interface

To make our financial agent more accessible, we can create a user interface using Gradio. Gradio provides a simple way to build and share machine learning interfaces.

```python
import gradio as gr

def get_abnb_closing_prices(input_text):
    result = chain.invoke({"input": input_text, "intermediate_steps": []})
    output = result["agent_outcome"].return_values["output"]
    return output

iface = gr.Interface(
    fn=get_abnb_closing_prices,
    inputs=gr.Textbox(lines=2, placeholder="Enter your query here..."),
    outputs=gr.Markdown(),
    title="Financial Agent",
    description="Financial Data Explorer: Leveraging Advanced API Tools for Market Insights"
)
iface.launch()
```

Here, we define the financial agent function taking the input text, running it to get the details. Now using the Gradio Interface which gives a textbox with input text and Markdown which gives the actual result. Finally, launching the interface will give the website result. This code snippet creates a Gradio interface with a textbox for user input and a markdown output for displaying the results. This enables users to interact with the financial agent through a web-based interface.

How to Use Your Financial Agent

Step-by-Step Guide to Get Financial Insights

Now that your financial agent is built and running, here’s how to use it:

  1. Launch the Application: Run the Python script containing the Gradio interface. This will start a local web server.

  2. Access the Interface: Open a web browser and navigate to the URL provided in the terminal (usually http://127.0.0.1:7860).

  3. Enter Your Query: In the textbox, enter your financial query. For example:

    • “What is the latest financial report for NVDA (NVIDIA)?”
    • “Can you show me the most recent news about Google (GOOGL)?”
    • “Track the historical performance of Microsoft (MSFT)”
    • “What has been ABNB's daily closing price between March 7, 2024 and March 14, 2024?”
  4. Submit the Query: Click the “Submit” button.

  5. View the Results: The results will be displayed in the markdown output area, providing you with the financial data you requested.

Financial Agent with LangGraph: Pros and Cons

👍 Pros

Automated Financial Tasks

Comprehensive Financial Data

Simplifies Complex Workflow

Easy-to-Use Interface via Gradio

👎 Cons

Requires API Keys

Dependency on External APIs

Initial Setup Required

Limited Customization

FAQ

What is LangGraph?
LangGraph is a framework for building conversational AI applications. It enables developers to create complex, multi-step workflows where different components of the AI system can interact and collaborate, simplifying the development process through a modular and extensible architecture.
What financial data can this agent access?
This financial agent is capable of retrieving stock prices, gathering the latest news, accessing detailed financial reports, and tracking historical price data. It uses the Polygon API to access all this financial information.
Do I need to pay for Polygon API?
You should be able to sign up to polygon for free, and get your API keys from developers. It provides free as well as paid plans for financial data access.

Related Questions

What are the benefits of using LangGraph over traditional methods?
LangGraph offers a modular and extensible architecture, simplifying the development of complex, multi-step workflows in AI systems. It allows different components to interact and collaborate effectively, making the development process more manageable and efficient compared to traditional methods.
How can I contribute to the LangGraph community?
There are many ways to contribute to the LangGraph community. Join their forum discussions, attend relevant meetups and conferences to share insights, and make a donation to support ongoing development. By actively participating in these activities, you'll help drive LangGraph innovation and provide valuable support to fellow enthusiasts.

Most people like