DEV Community

Dennis Peter Munyao
Dennis Peter Munyao

Posted on

How to Build an AI-Powered Portfolio Analyzer Using LangGraph and LangChain (Step-by-Step Guide)

Artificial Intelligence agents are no longer science fiction—they're here, and they're transforming how we work. From personal assistants to decision-making bots, AI agents are rapidly becoming integral to modern workflows, especially in areas that demand high cognitive effort and multitasking.

One compelling use case? Financial analysis.

What Are AI Agents?

AI agents are autonomous systems capable of perceiving their environment, reasoning about it, and taking actions to achieve specific goals. Think of them like digital co-workers that operate without you constantly feeding them instructions. They can gather data, assess situations, make decisions, and even adapt over time.

You might have heard of Jarvis from Iron Man or TARS from Interstellar. While we're not quite there yet, today's AI agents—powered by Large Language Models (LLMs)—are incredibly effective at completing complex digital tasks. These can range from summarizing documents and interacting with APIs to analyzing trends and generating strategic insights.

Image description

Real-World Application: Portfolio Analysis in Finance

In financial markets, analysts traditionally rely on various perspectives—technical analysis, fundamental analysis, and sentiment evaluation—to make informed investment decisions. This often involves:

  • Reviewing price trends
  • Studying technical indicators
  • Analyzing company fundamentals
  • Monitoring market sentiment

Doing all this manually can be time-consuming and error-prone. But what if an AI agent could handle all that for you?

Introducing LangGraph: The AI Agent Framework

In this tutorial, we'll walk through how to build a Portfolio Analysis Agent using Python and LangChain's powerful LangGraph framework.

LangGraph allows you to structure workflows composed of multiple AI-powered chains or agents. Think of it like assembling a team of specialized analysts—each responsible for a specific area (fundamental, technical, sentiment)—and orchestrating their collaboration through a portfolio manager agent that synthesizes their findings into a final analysis.

What This Agent Will Do

  • Fetch real-time price data
  • Run technical analysis using indicators
  • Pull fundamental data from financial APIs
  • Optionally analyze market sentiment
  • Generate actionable insights from all the above

Why Use LangGraph?

LangGraph offers a flexible and structured way to build agentic workflows with:

  • State persistence
  • Memory between steps
  • Branching and decision-making logic
  • Easy integration with tools and APIs

Prerequisites

To follow this tutorial, you should be familiar with:

  • Python
  • The LangChain ecosystem
  • Basic financial concepts

What You'll Learn

By the end of this guide, you'll be able to:

  • Set up a LangChain + LangGraph development environment
  • Create modular agent components for different analysis types
  • Implement an orchestration layer that mimics a financial analyst team
  • Interpret and present final analysis in a human-readable format

Why This Matters

AI agents aren't just smart—they're scalable, consistent, and tireless. By building a portfolio analysis agent, you're not just automating tasks—you're building a digital analyst that works 24/7, integrates diverse data sources, and provides decision-grade outputs. That's a game-changer for investors, fintech startups, and even financial educators.

Step 1: Set Up a Python Environment

It's a best practice to create a dedicated virtual environment to manage dependencies cleanly.

# Create a new virtual environment named 'portfolio-agent-env'
python3 -m venv portfolio-agent-env

# Activate the environment (macOS/Linux)
source portfolio-agent-env/bin/activate

# Or on Windows
.\portfolio-agent-env\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Required Packages

Core Dependencies Installation

Install the essential packages using pip:

pip install langchain langgraph yfinance pandas matplotlib
Enter fullscreen mode Exit fullscreen mode

Package Descriptions:

  • langchain: Core framework for building LLM applications

  • langgraph: For creating multi-agent workflows

  • yfinance: Yahoo Finance market data downloader

  • pandas: Data manipulation and analysis

  • matplotlib: Charting and visualization

Optional Packages

For advanced functionality

pip install newsapi-python tweepy alpha_vantage
Enter fullscreen mode Exit fullscreen mode
  • newsapi-python: News API client for sentiment analysis
  • tweepy: Twitter API access
  • alpha_vantage: Alternative financial data API

Step 3: Verify Your Installation

Create Verification Script

Create verify_install.py with:

#!/usr/bin/env python3
# Installation Verification Script

import yfinance as yf
from langchain.llms import OpenAI

def test_finance_data():
    """Test financial data connectivity"""
    try:
        data = yf.Ticker("AAPL").history(period="1d")
        print("✓ Yahoo Finance connection successful")
        print(f"Retrieved {len(data)} records")
        return True
    except Exception as e:
        print(f"✗ Finance data failed: {e}")
        return False

def test_llm_setup():
    """Test LangChain/LLM availability""" 
    try:
        llm = OpenAI(temperature=0)
        print("✓ LangChain setup correct")
        return True
    except Exception as e:
        print(f"✗ LLM setup failed: {e}")
        return False

if __name__ == "__main__":
    print("🔍 Running Installation Checks...\n")

    tests = [
        ("Financial Data", test_finance_data),
        ("LLM Setup", test_llm_setup)
    ]

    results = []
    for name, test in tests:
        print(f"## Testing {name}")
        results.append(test())
        print()

    print("📊 Test Summary:")
    for (name, _), result in zip(tests, results):
        print(f"- {name}: {'✅ PASSED' if result else '❌ FAILED'}")

    if all(results):
        print("\n🎉 All systems go! Environment ready for development.")
    else:
        print("\n⚠️  Some tests failed. Check installation before proceeding.")
Enter fullscreen mode Exit fullscreen mode

Run Verification

Execute the test script:

python verify_install.py
Enter fullscreen mode Exit fullscreen mode

Expected Successful Output:

🔍 Running Installation Checks...

## Testing Financial Data
 Yahoo Finance connection successful
Retrieved 1 records

## Testing LLM Setup
 LangChain setup correct

📊 Test Summary:
- Financial Data:  PASSED
- LLM Setup:  PASSED

🎉 All systems go! Environment ready for development.
Enter fullscreen mode Exit fullscreen mode

Troubleshooting

If tests fail:

  • Verify virtual environment activation

  • Check internet connection

  • Ensure API keys are properly set

  • Re-run pip install with --upgrade flag

Top comments (0)