
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.
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.

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
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
User Input: User enters natural language query (e.g., 'Invest $10k in AAPL and MSFT since Jan 2023')
Query Analysis: AI extracts ticker symbols, amounts, investment date, and strategy (single-shot vs DCA)
Stock Data Gathering: Downloads historical prices from Yahoo Finance for specified period
Portfolio Allocation: Simulates stock purchases, calculates shares bought, remaining cash, and current value
Benchmark Comparison: Simulates equivalent SPY investment for performance comparison
Insights Generation: AI analyzes each stock to generate bull case (positive) and bear case (negative) insights
Results Display: Renders allocation charts, performance metrics, transaction logs, and insights in real-time UI

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
About the Author
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.
