DEV Community

grahammccain
grahammccain

Posted on • Originally published at chartlibrary.io

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

Most AI trading agents 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.

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

Setting Up

You need three packages and two API keys:

pip install langchain langchain-openai chartlibrary
Enter fullscreen mode Exit fullscreen mode
  • 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-...

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 chart_intelligence Tool

Here's the core tool that powers most agent interactions:

@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
Enter fullscreen mode Exit fullscreen mode

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.

Market Regime and Sector Tools

Beyond individual stocks, agents need market context:

  • market_regime -- calls the /regime endpoint for SPY, QQQ, and all 11 S&P sector ETFs with historical pattern matching
  • sector_rotation -- sector momentum rankings
  • crowding_detector -- checks if many stocks are trading the same pattern (signals systematic risk)
  • scenario_analysis -- stress-tests a stock against a hypothetical market move

Building the Agent

With the tools defined, assembling the agent takes about 10 lines:

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
)
Enter fullscreen mode Exit fullscreen mode

Example Conversation

Here's what a real session looks like:

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

User: "What about the broader market? Is there anything concerning?"

Agent calls: market_regime(), crowding_detector()

Agent: "SPY's 30-day change is 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, which historically signals higher correlation risk."

Extending the Agent

The five tools above cover the core use cases, but Chart Library's API has more endpoints you can wrap:

  • 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
  • Multi-timeframe: Search across 5min, 15min, 30min, 1hr, or multi-day windows

The full tutorial code is on GitHub at github.com/grahammccain/chart-library-mcp in the examples/ directory.

What's Next: Multi-Agent Workflows

A single agent is useful. The next level is multi-agent workflows where specialized agents collaborate -- a Pattern Analyst, a Regime Strategist, and a Risk Manager that discuss, debate, and produce a unified research brief.

Chart Library's MCP server (pip install chartlibrary-mcp) works with any MCP-compatible agent framework -- including Claude Desktop, Cursor, and Windsurf.


Get a free API key at chartlibrary.io/developers and start building. 24 million chart pattern embeddings, 10 years of history, one API call.

Top comments (0)