Chart Library logo
TutorialLangChainAI AgentsPython

Build a Stock Research Agent with LangChain + Chart Library in 20 Minutes

Chart Library Team··8 min read

Why Agents Need Historical Pattern Data

Most AI trading agents today work with raw price data: OHLCV bars, moving averages, maybe some technical indicators. They can tell you what the price is, but not what it means. When a chart forms a pattern that has appeared thousands of times before, the interesting question is not 'what is the pattern?' but 'what happened next?'

Chart Library's API gives agents something they can't get anywhere else: pre-computed pattern similarity across 24 million embeddings spanning 10 years and 19,000+ symbols. Instead of asking 'what's the price of NVDA?', your agent can ask 'find the 10 most similar historical charts to NVDA right now and tell me how those patterns resolved.'

This turns a basic chatbot into something genuinely useful for research. The agent can cross-reference pattern intelligence with market regime data, sector rotation, crowding signals, and scenario analysis — all through natural language.

Setting Up

You need three packages and two API keys. The Chart Library Python SDK wraps our REST API so you don't have to manage HTTP requests yourself.

  • Install dependencies: pip install langchain langchain-openai chartlibrary
  • Get a free Chart Library API key at chartlibrary.io/developers (200 calls/day on the free tier)
  • Set your environment variables: CHART_LIBRARY_KEY=cl_... and OPENAI_API_KEY=sk-... (or use any LangChain-supported LLM)

Note:You can swap OpenAI for Anthropic, Groq, Ollama, or any LangChain-compatible model. Just change the LLM initialization — the tools stay the same.

Creating the Tools

LangChain agents work by selecting from a set of tools based on the user's question. Each tool wraps one or more API calls and returns a formatted string the LLM can reason over. We define five tools that cover Chart Library's core capabilities.

The first and most important tool is chart_intelligence. It takes a ticker and optional date, calls the /intelligence endpoint, and returns the top matches, forward return statistics, and an AI summary. The docstring is critical — it's what the LLM reads to decide when to use the tool.

The chart_intelligence Tool

Here's the core tool that powers most agent interactions. It wraps Chart Library's intelligence endpoint and formats the response for the LLM:

@tool def chart_intelligence(symbol: str, date: str = "") -> str: """Get full pattern intelligence for a stock ticker. Returns the 10 most similar historical chart patterns, what happened after those patterns (1/3/5/10-day forward returns), and an AI-generated summary.""" data = cl.intelligence(symbol, date=date or None, compact=True) # Format matches, forward returns, and summary # into a readable string for the LLM return formatted_result

The tool extracts the top 3 matches with similarity scores, forward return statistics (average return, win rate) for each horizon, and the AI-generated summary. This gives the LLM everything it needs to answer questions like 'How did stocks with similar patterns perform?'

Market Regime and Sector Tools

Beyond individual stocks, agents need market context. The market_regime tool calls the /regime endpoint and returns a snapshot of SPY, QQQ, and all 11 S&P sector ETFs — each with historical pattern matching data showing how similar conditions played out.

The sector_rotation tool provides momentum rankings across sectors, helping the agent answer 'which sector is leading right now?' The crowding_detector checks whether the market is showing elevated correlation — many stocks trading the same pattern simultaneously, which can signal systematic risk.

Finally, scenario_analysis lets the agent stress-test a stock against a hypothetical market move. Ask 'how might TSLA react if the market drops 5%?' and the tool uses historical pattern data to project outcomes.

Building the Agent

With the tools defined, assembling the agent takes about 10 lines. The system prompt tells the LLM it's a research assistant that presents historical data, not a financial advisor making predictions:

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) tools = [chart_intelligence, market_regime, crowding_detector, scenario_analysis, sector_rotation] agent = create_tool_calling_agent(llm, tools, prompt) executor = AgentExecutor( agent=agent, tools=tools, verbose=True, max_iterations=5 )

The agent automatically decides which tools to call based on the user's question. Ask about NVDA and it calls chart_intelligence. Ask about the market and it calls market_regime. Ask a multi-part question and it chains multiple tool calls together.

Example Conversation

Here's what a real session looks like. The agent decides which tools to call, interprets the results, and responds in plain English.

User: "What does NVDA's chart look like right now? How did similar patterns play out?" Agent calls: chart_intelligence("NVDA") Agent: "NVDA's current chart pattern matches 10 historical patterns with high similarity. The top match is AMD from 2023-08-14 at 94% similarity. Looking at what happened after these patterns: over 5 days, the average return was +1.8% with 7 of 10 matches moving higher. Over 10 days, the average was +2.4% with 6 of 10 positive. The AI summary notes this resembles a consolidation pattern after a strong run, with historical precedent favoring continuation."

User: "What about the broader market? Is there anything concerning?" Agent calls: market_regime(), crowding_detector() Agent: "The current market regime shows SPY's 30-day change at +3.2%, with 8 of 10 similar historical regimes seeing positive 10-day returns. However, the crowding detector is showing elevated readings — many stocks are trading in lockstep right now, which historically signals higher correlation risk. Tech (XLK) and Discretionary (XLY) are leading sectors; Utilities and Staples are lagging."

Adding More Tools

The five tools above cover the core use cases, but Chart Library's API has more endpoints you can wrap. Here are some ideas for extending the agent:

  • Alerts: Let the agent set up pattern alerts ('tell me when a chart similar to AAPL 2024-01-15 appears again')
  • Portfolio analysis: Connect the agent to a user's portfolio for nightly pattern monitoring
  • Historical backtest: Run pattern-based backtests to validate strategies over longer time periods
  • Multi-timeframe: Search across 5min, 15min, 30min, 1hr, or multi-day windows for different trading horizons

Tip:The full tutorial code is on GitHub at github.com/grahammccain/chart-library-mcp in the examples/ directory. It includes interactive mode with conversation history.

What's Next: Multi-Agent Workflows

A single agent with Chart Library tools is already useful for research. The next level is multi-agent workflows where specialized agents collaborate.

For example, a CrewAI setup might have a Pattern Analyst agent (uses chart_intelligence to evaluate individual stocks), a Regime Strategist agent (uses market_regime and sector_rotation to assess macro conditions), and a Risk Manager agent (uses crowding_detector and scenario_analysis to flag concerns). The agents discuss, debate, and produce a unified research brief.

We're working on a CrewAI tutorial that demonstrates exactly this. In the meantime, Chart Library's MCP server (pip install chartlibrary-mcp) works with any MCP-compatible agent framework — including Claude Desktop, Cursor, and Windsurf — so you can start building multi-agent workflows today.

Get a free API key at chartlibrary.io/developers and start building. The full tutorial code is at github.com/grahammccain/chart-library-mcp.

Ready to try Chart Library?

Upload a chart screenshot or search any ticker — see what history says about your pattern.

Try it free