Multi-Agent Stock Research with CrewAI + Chart Library
Why Multi-Agent Beats Single-Agent for Stock Research
When you ask a single AI agent to research a stock, it tries to do everything at once: check the chart pattern, assess the market environment, evaluate sector rotation, and synthesize a view. The result is usually a shallow overview that misses the nuances a specialist would catch.
Multi-agent systems solve this by splitting the work across specialists. Each agent has a narrow focus, deep domain expertise, and its own set of tools. A Pattern Analyst looks at the individual stock's historical matches and forward returns. A Regime Analyst evaluates the macro backdrop — SPY, QQQ, sector leadership, and crowding risk. When their findings are combined, you get research that accounts for both the micro and macro picture.
This is how institutional research desks work: sector analysts cover individual names, macro strategists set the context, and a portfolio manager synthesizes both perspectives. CrewAI lets you build the same structure with AI agents and Chart Library's pattern intelligence API.
The Crew Design: Two Specialist Agents
The crew has two agents, each with a distinct role, goal, and backstory that shapes how the LLM approaches the task.
The Pattern Analyst specializes in individual stock chart analysis. It uses Chart Library's intelligence endpoint to find historically similar charts, reads the forward return statistics, and runs scenario stress tests. Its backstory emphasizes quantitative rigor — always citing specific numbers like '7 of 10 similar patterns went up over 5 days, averaging +2.3%' rather than vague language like 'mostly bullish.'
The Regime Analyst specializes in the market-wide environment. It uses Chart Library's regime tracker to assess SPY, QQQ, and all 11 S&P 500 sector ETFs, checks for crowding (many stocks showing the same pattern, which signals systematic risk), and analyzes sector rotation. Its backstory frames everything as historical analogy — 'similar conditions historically led to...' rather than predictions.
Note:Agent backstories matter more than you'd expect. They shape how the LLM formats output, what it prioritizes, and how confident it sounds. A backstory that says 'you never make predictions, you present historical context' produces very different output than one that says 'you are a bold market forecaster.'
Defining the Tools from Chart Library
Each agent gets a curated set of tools. CrewAI uses its own @tool decorator — you define the function, add a docstring, and the agent reads the description to decide when to use it. The Chart Library Python SDK (pip install chartlibrary) handles authentication and API calls.
The Pattern Analyst gets three tools: Chart Pattern Intelligence for full pattern analysis on any ticker, Scenario Stress Test for 'what if the market drops 5%' questions, and Daily Top Picks for screening ideas. The Regime Analyst gets three different tools: Market Regime Snapshot for SPY/QQQ/sector analysis, Crowding Detector for systematic risk, and Sector Rotation Analysis for momentum and relative strength.
- Chart Pattern Intelligence — calls cl.intelligence(symbol, date) to get the 10 most similar historical patterns, forward returns across 1/3/5/10-day horizons, and an AI summary.
- Market Regime Snapshot — calls cl.regime(compact=True) to get regime status for SPY, QQQ, and 11 sector ETFs, ranked by 10-day historical outlook.
- Crowding Detector — calls cl.crowding() to check if many stocks are showing the same pattern, which signals elevated systematic risk.
- Scenario Stress Test — calls cl.scenario(symbol, market_move_pct) to simulate how a stock might react to a hypothetical market move based on historical data.
- Sector Rotation Analysis — calls cl.sector_rotation(lookback) to get sector momentum rankings over the past N days.
- Daily Top Picks — calls cl.discover(limit=10) to get today's top patterns ranked by interest score.
Tip:Get a free Chart Library API key at chartlibrary.io/developers. The free tier includes 200 API calls per day — more than enough for a research crew that runs a few times daily.
Building the Tasks: Regime, Analysis, Synthesis
Tasks are the specific assignments given to agents. The order matters: the regime assessment runs first to establish context, then individual stock analysis uses that context, and finally a synthesis task combines both perspectives into a final briefing.
Task 1 is the Regime Assessment, assigned to the Regime Analyst. It checks SPY and QQQ regime status, identifies leading and lagging sectors, evaluates crowding risk, and sets the macro context. The key instruction: 'Be specific with numbers. Say 7 of 10 matches went up, not mostly bullish.'
Task 2 is the Stock Analysis, assigned to the Pattern Analyst. For each symbol in your watchlist, it reports match count, match quality, forward returns at multiple horizons, and any notable patterns in the matches. Crucially, it receives the regime task's output as context — so it can frame findings like 'NVDA's bullish pattern aligns with the current risk-on regime' or 'TSLA's breakout setup diverges from the bearish sector backdrop.'
Task 3 is the Synthesis, also assigned to the Pattern Analyst (since it needs to weigh both inputs). It produces a structured briefing with four sections: Market Environment, Stock Highlights, Risk Factors, and Bottom Line. The instructions explicitly require the disclaimer that this is historical data analysis, not financial advice.
Running the Crew and Reading the Output
With agents and tasks defined, running the crew is three lines of code. Create the Crew with both agents, pass the tasks, and set Process.sequential so they run in order. Call crew.kickoff() and the agents take over.
- Install dependencies: pip install crewai crewai-tools chartlibrary
- Set environment variables: OPENAI_API_KEY for CrewAI's LLM, CHART_LIBRARY_KEY for the pattern data API.
- Run the crew: result = crew.kickoff() — returns the final synthesis as a string.
Note:With verbose=True, you can watch the agents reason in real time — seeing which tools they call, what data they receive, and how they build their analysis step by step. This is invaluable for debugging and understanding agent behavior.
Example Output
Here is what a typical crew run produces. The Regime Analyst checks SPY and finds that 7 of 10 historically similar regimes gained over 10 days. It notes that Tech (XLK) and Industrials (XLI) are leading while Energy (XLE) is lagging, and flags moderate crowding in large-cap tech names.
The Pattern Analyst then analyzes each symbol. For NVDA, it finds 10 matches with the top match at 94% similarity, 8 of 10 positive over 5 days averaging +3.1%. For AAPL, matches are more mixed — 6 of 10 positive, +0.8% average. For TSLA, the pattern is historically volatile with a wide outcome range.
The synthesis combines these into a briefing: bullish regime supports NVDA's strong pattern, AAPL is neutral, TSLA's wide range means position sizing matters more than direction. Risk factors note the tech crowding and that TSLA diverges from sector trends. The bottom line frames it as historical context for the reader's own decision-making.
Extending the Crew: Risk Manager and Portfolio Optimizer
Two agents is a starting point. Real research workflows benefit from additional specialists.
A Risk Manager agent would use the scenario stress test and crowding tools to evaluate downside risk across the entire watchlist. It could run stress tests for -3%, -5%, and -10% market moves and flag any position where the historical downside exceeds a threshold. Its output feeds into the synthesis as a dedicated risk section.
A Portfolio Optimizer agent could take the pattern analysis and risk assessment as inputs, then suggest position sizes based on conviction (match quality and win rate) and correlation (crowding data). High-conviction, low-correlation ideas get larger allocations; crowded or ambiguous patterns get smaller ones.
CrewAI also supports hierarchical processes where a manager agent delegates tasks dynamically instead of following a fixed sequence. For a more complex crew, you could have a Research Director that decides which stocks need deeper analysis and routes follow-up questions to the right specialist.
Tip:Start with two agents and add complexity only when you hit a real limitation. Multi-agent systems are powerful but harder to debug. Get the basic crew working, then extend it.
Full Code and Next Steps
The complete working example is available in Chart Library's GitHub repository at examples/crewai_tutorial.py. It includes the full crew implementation, a quick single-agent mode for simpler use cases, and ready-to-run examples.
Chart Library's API provides the same pattern intelligence that powers chartlibrary.io — 24 million pre-computed embeddings across 15,000+ symbols and 10 years of history. Every search returns historically similar charts with real outcome data, not predictions. Combined with CrewAI's multi-agent orchestration, you get a research system that thinks like an institutional desk but runs on a single API call.
Get your free API key at chartlibrary.io/developers and build your first research crew today.
Ready to try Chart Library?
Upload a chart screenshot or search any ticker — see what history says about your pattern.
Try it freeRelated Articles
How to Use an MCP Server for Stock Analysis with Claude
Install Chart Library's MCP server and give Claude Desktop access to 24 million historical chart patterns, market regime data, and forward return statistics — all through natural conversation.
What Is a Market Regime Tracker? How Chart Library Identifies Historical Market Parallels
Learn what market regimes are, how Chart Library's regime tracker finds historically similar market conditions, and how to use regime data to inform your trading decisions.
Build a Stock Research Agent with LangChain + Chart Library in 20 Minutes
A hands-on tutorial for building an AI agent that can answer natural-language questions about stock charts, market regimes, and sector rotation using LangChain and Chart Library's pattern intelligence API.