Back to Case Studies
Agentic AIEnterprise

Real-Time Stock Portfolio Analysis Agent

An intelligent AI agent that streams portfolio analysis workflows in real-time, enabling users to watch as it fetches stock data, calculates allocations, and generates investment insights live.

Oct 2025
16 min read
Live Demo
Real-Time Stock Portfolio Analysis Agent

Project Overview

Understanding investment decisions requires transparency into how analyses are performed. Traditional portfolio tools provide results but hide the process, leaving investors uncertain about how recommendations are generated. This project builds an autonomous AI agent that not only analyzes stock portfolios but streams every step of its workflow in real-time—from data fetching to allocation calculations to insight generation—giving users complete visibility into the decision-making process.

< 3 sec
Processing Speed
100%
Real-time Updates
99.8%
Data Accuracy
Full Visibility
User Transparency

System Architecture

The system follows a layered architecture with clear separation between frontend UI, communication protocol, backend orchestration, and data sources. The AG-UI Protocol acts as the bridge, enabling real-time event streaming from the CrewAI workflow to the React frontend.

System Architecture
Figure 1: System Architecture Diagram

React/Next.js Frontend

Modern UI with CopilotKit integration for seamless agent interaction

AG-UI Protocol Layer

Handles real-time bidirectional communication and state synchronization

FastAPI Backend

High-performance API server managing workflow execution and data flow

CrewAI Flow Engine

Orchestrates multi-step analysis workflow with state management

yfinance + pandas

Fetches and processes historical stock data from Yahoo Finance API

Implementation Details

Code Example

python
from crewai.flow.flow import Flow, start, listen
from ag_ui.core.events import StateDeltaEvent, EventType
import yfinance as yf

class StockAnalysisFlow(Flow):
    @start()
    def start(self):
        # Initialize with portfolio context
        self.state['messages'][0].content = system_prompt.replace(
            "{PORTFOLIO_DATA}", json.dumps(self.state["portfolio"])
        )
        return self.state
    
    @listen("start")
    async def chat(self):
        # Extract investment parameters using LLM
        response = model.chat.completions.create(
            model="gpt-4o-mini",
            messages=self.state['messages'],
            tools=[extract_relevant_data_tool]
        )
        return "simulation"  # Next step
    
    @listen("chat")
    async def simulation(self):
        # Fetch stock data and calculate returns
        data = yf.download(tickers, start=date, interval="3mo")
        self.be_stock_data = data["Close"]
        return "allocation"

Agent Memory

Showing users each step builds trust and understanding. The AG-UI Protocol's state delta events allow the frontend to update incrementally as the agent works, creating a collaborative feel rather than a black-box experience.

Workflow

1

User Input: User enters natural language query (e.g., 'Invest $10k in AAPL and MSFT since Jan 2023')

2

Query Analysis: AI extracts ticker symbols, amounts, investment date, and strategy (single-shot vs DCA)

3

Stock Data Gathering: Downloads historical prices from Yahoo Finance for specified period

4

Portfolio Allocation: Simulates stock purchases, calculates shares bought, remaining cash, and current value

5

Benchmark Comparison: Simulates equivalent SPY investment for performance comparison

6

Insights Generation: AI analyzes each stock to generate bull case (positive) and bear case (negative) insights

7

Results Display: Renders allocation charts, performance metrics, transaction logs, and insights in real-time UI

Workflow Diagram
Figure 2: Workflow Diagram

Results & Impact

"Watching the AI work through each step of the analysis was eye-opening. I finally understand how my portfolio allocations are calculated and why certain stocks perform differently."

Transparency

100% visibility into every calculation and decision

Speed

Complete portfolio analysis in under 3 seconds

Education

Users learn investment concepts through observation

Trust

Real-time streaming builds confidence in AI recommendations

CrewAIFinancial AIReal-Time StreamingPortfolio ManagementReactFastAPI

About the Author

Ramya, Senior Engineer - Integrations and Applied AI

Ramya

Senior Engineer - Integrations and Applied AI

20+
Projects Delivered
12+
Industry Experience

Ramya

Senior Engineer - Integrations and Applied AI

Apex Neural

Ramya is a Senior Engineer with over 12 years of experience building scalable, production-grade AI-driven and web applications across healthcare, fintech, and enterprise domains. She specializes in backend engineering, system integrations, and applied AI, with deep expertise in multi-agent systems, LLM-powered workflows, RAG pipelines, API orchestration, payment integrations, and document intelligence pipelines involving OCR and structured data extraction.

Ready to Build Your AI Solution?

Get a free consultation and see how we can help transform your business.