Talk to Your Market Data: Hidden Regime’s MCP Integration Brings HMMs to Claude Desktop

“What’s SPY’s current market regime?”

I type the question into Claude Desktop and lean back. Two seconds later, Claude responds with confidence scores, regime duration analysis, transition probabilities, and a clear assessment: “SPY is in a bearish regime (89% confidence) that started 12 days ago and is approaching expected transition. Despite +17.7% YTD returns, volatility has increased to 8.4% daily, indicating consolidation after the rally…”

This isn’t some simple lookup in a database. Behind that conversational query, Claude just orchestrated a sophisticated Hidden Markov Model analysis: fetching market data, training a multi-state Gaussian HMM with Baum-Welch optimization, running Viterbi inference for regime sequences, and interpreting emission parameters through financial domain knowledge. All from a single natural language question.

Welcome to Hidden Regime 2.0.0 and the magic of the Model Context Protocol.

SPY regime detection in Claude Desktop
Figure 1: Natural language query to Claude Desktop triggers sophisticated HMM analysis with comprehensive regime insights.

The Problem: Quantitative Analysis Requires Coding

Let’s be honest about regime detection. It’s powerful, but it’s traditionally been the domain of quants who can code. You need to:

  1. Write code to fetch and validate market data
  2. Transform prices to log returns for stationarity
  3. Configure and train an HMM (how many states? what initialization?)
  4. Interpret the raw mathematical output (state 0 vs state 1 means what?)
  5. Calculate financial metrics (win rates, drawdowns, transition matrices)
  6. Visualize results and make trading decisions

Even with a well-designed library like Hidden Regime, you’re still writing Python scripts, managing configurations, and understanding the pipeline architecture. That’s a barrier for traders who know markets but don’t want to write code every time they check a regime.

The Solution: Conversational Quantitative Finance

Hidden Regime 2.0.0 includes a complete MCP (Model Context Protocol) server that exposes regime detection capabilities to AI assistants like Claude Desktop. The result? Natural language becomes your interface to sophisticated quantitative analysis.

Instead of this:

1import hidden_regime as hr
2pipeline = hr.create_financial_pipeline('SPY', n_states=3)
3result = pipeline.update()
4print(f"Regime: {result['regime_label'].iloc[-1]}")
5print(f"Confidence: {result['confidence'].iloc[-1]:.1%}")
6# ... more code to extract metrics

You do this:

What's SPY's current market regime?

Claude handles the rest. It calls the appropriate Hidden Regime tools, interprets the results, and presents them in clear, actionable language. You get the same rigorous HMM analysis that data scientists use, packaged in a conversational interface.

What’s Under the Hood: Four MCP Interfaces

The MCP integration implements four of the five core MCP interfaces, each serving a specific purpose:

Hidden Regime MCP Tools
Figure 2: Hidden Regime’s three core MCP tools available in Claude Desktop.

1. Tools (3 core operations)

These are the workhorses that execute regime detection:

detect_regime(ticker, n_states, start_date, end_date)

The flagship tool. Returns comprehensive regime analysis with four categories of information:

  • Basic Regime Information: Current regime name, confidence score, mean return, volatility
  • Temporal Context: Days in regime, expected duration, regime status (early/mid/mature/overdue)
  • Price Context: YTD/30d/7d performance, current price, trend direction
  • Stability & Interpretation: Recent transitions, regime stability, human-readable explanation

The temporal context is particularly powerful. Knowing that a regime is “89% complete and overdue” tells you far more than just “currently bullish.” It tells you to watch for a transition.

get_regime_statistics(ticker, n_states, start_date, end_date)

Detailed historical analysis of all detected regimes:

 1{
 2  "ticker": "SPY",
 3  "regimes": {
 4    "bull": {
 5      "mean_return": 0.03,
 6      "volatility": 0.10,
 7      "duration_days": 45.2,
 8      "win_rate": 0.68,
 9      "observations": 234
10    },
11    "bear": {...},
12    "sideways": {...}
13  }
14}

This is where you learn that bull regimes in SPY typically last 45 days with a 68% win rate. That’s actionable intelligence.

get_transition_probabilities(ticker, n_states)

The crystal ball (well, a probabilistic one):

 1{
 2  "transition_matrix": {
 3    "bull": {"bull": 0.85, "bear": 0.05, "sideways": 0.10},
 4    "bear": {"bull": 0.10, "bear": 0.80, "sideways": 0.10}
 5  },
 6  "expected_durations": {
 7    "bull": 20.0,
 8    "bear": 10.0,
 9    "sideways": 6.7
10  }
11}

Direct bull-to-bear transitions are rare (5%). More common: bull → sideways → bear. That’s useful for risk management.

2. Resources (URI-based access)

Resources provide URI-based access to regime data:

regime://SPY/current       → Current regime state
regime://SPY/transitions   → Transition probabilities

These are perfect for automation scenarios where you want programmatic access without function calls. Claude can reference these URIs directly in conversations.

3. Prompts (7 expert workflows)

This is where MCP really shines. Prompts are pre-configured analysis templates that orchestrate multiple tool calls into sophisticated workflows.

Hidden Regime MCP Prompts
Figure 3: Seven expert-level prompts for comprehensive regime analysis workflows.

Instead of asking Claude to “detect regime and analyze transitions and calculate risk,” you select a prompt and let it execute the entire expert-level analysis:

regime-quick-check - Your daily market health check

Fast 3-4 sentence summary focused on actionable insights. Perfect for morning market reviews before trading.

regime-deep-dive - Comprehensive multi-tool analysis

Calls all three tools (detect_regime, get_regime_statistics, get_transition_probabilities) and synthesizes them into a complete report with current state, historical context, transition dynamics, and trading implications.

Here’s a real example of the regime-deep-dive prompt analyzing QQQ over a 2-year period:

Current Regime State:

  • Regime: Bearish (99.2% confidence)
  • Days in Regime: 7 days (mature, 70% complete)
  • Expected Transition: ~3 days
  • Current Price: $590.07
  • YTD Return: +16.1% (despite bearish classification)
  • Recent Performance: -3.4% (30d), -3.1% (7d)
  • Volatility: 18.9% (elevated, 2x higher than bull regime)

Historical Context:

  • Bull Regime: 72.8% of time (364 days), +0.86% mean return, 8.8% volatility, 72.2% win rate
  • Bear Regime: 27.2% of time (136 days), -1.62% mean return, 18.9% volatility, 25.0% win rate

Transition Dynamics:

  • From Current Bear State:
    • 75.5% probability: Remain in bear regime
    • 24.1% probability: Transition to Bull-2 (transitional state)
    • 0.4% probability: Direct transition to Bull-1

Trading Implications:

  • Defensive posture recommended due to elevated volatility
  • Current regime is overdue (7 days vs 4.1 day expected duration)
  • Monitor for breakdown below $585 support or breakout above $608
  • 75% probability of continued consolidation suggests patience before adding long exposure

This comprehensive analysis demonstrates how the deep-dive prompt orchestrates multiple HMM tools to provide actionable regime intelligence.

regime-strategy-advisor - Trading recommendations based on regime + risk

Maps your risk tolerance (low/medium/high) to appropriate strategies for the current regime:

  • Bull regime + high risk → leveraged long positions, breakout trading
  • Bear regime + low risk → cash positions, defensive sectors
  • Sideways regime + medium risk → mean reversion, pairs trading

regime-multi-asset-comparison - Portfolio diversification analysis

Analyzes regimes across multiple tickers (e.g., “SPY,QQQ,IWM,GLD,TLT”) and shows:

  • Are all your assets in the same regime? (concentration risk)
  • Which holdings are in mature regimes approaching transition?
  • How well diversified is your portfolio across regime types?

regime-risk-assessment - Quantitative risk scoring (0-100)

Calculates a composite risk score from four components:

  • Confidence risk (30 pts): Lower confidence = higher risk
  • Transition risk (30 pts): Mature/overdue regimes = higher risk
  • Stability risk (20 pts): Frequent transitions = higher risk
  • Adverse transition risk (20 pts): High probability of unfavorable outcome

You get a concrete number (e.g., “67/100 - High Risk”) with specific mitigation strategies.

regime-historical-analogs - Pattern matching for outcome prediction

Finds similar historical regime episodes and analyzes what happened next. If the current bull regime is 23 days old, this prompt tells you:

  • This regime type occurred 8 times previously
  • Average duration: 51 days (current episode: 23 days, 45% complete)
  • 62% transitioned to sideways, 25% to bear, 13% extended beyond expected
  • Expected transition in ~28 days (±10 days)

regime-portfolio-review - Portfolio-wide rebalancing recommendations

Pass in your portfolio (e.g., {"SPY": 0.5, "QQQ": 0.3, "GLD": 0.2}) and get:

  • Weighted regime exposure breakdown
  • Concentration risk alerts (>60% in one regime)
  • Diversification score (0-100)
  • Specific rebalancing suggestions to improve regime diversity

4. Logging (Structured transparency)

Every operation is logged so you know exactly what’s happening:

[INFO] Cache miss for SPY - running fresh regime analysis
[INFO] Fetching data for SPY from Yahoo Finance...
[INFO] Training 3-state HMM model for SPY...
[INFO] Downloaded 500 observations for SPY (2023-01-01 to 2024-12-31)
[INFO] Model training completed for SPY
[INFO] Regime detection completed for SPY - result cached

This transparency is critical when you’re making trading decisions based on model output. You can see when data is fetched vs cached, when models are trained, and how much data was used.

Real Example: Understanding Regime vs Price Action

One of the most striking examples of what regime detection actually measures came from a recent NVDA analysis. The quick-check prompt revealed something that perfectly illustrates why regimes aren’t just about “up or down”:

NVDA Crisis Bear Regime
Figure 4: NVDA showing Crisis Bear regime despite +29.4% YTD gains - regime detection focuses on statistical behavior patterns, not just price direction.

The apparent paradox:

  • YTD Performance: +29.4% (strong gains)
  • Current Regime: Crisis Bear (62% confidence)
  • Volatility: 69.6% (extreme)
  • Recent Action: Down 5.9% (7 days), down 1.8% (30 days)

What the regime is actually telling you:

The HMM isn’t saying “NVDA is a bad investment” or “the uptrend is over.” It’s detecting that the statistical characteristics of price behavior have shifted dramatically:

  • Extreme volatility (69.6%) suggests unpredictable price swings - nearly 7x higher than typical bull regime levels
  • Regime overdue (21 days vs 10 expected) indicates the current turbulent pattern is extended
  • Transition imminent - the model expects a regime change, but the direction is uncertain

This is valuable risk intelligence. Despite the strong YTD gains, NVDA’s recent behavior shows:

  • High uncertainty (extreme volatility)
  • Downward momentum in recent windows
  • A behavior pattern that historically precedes either resolution back to bullish conditions or further deterioration

The key insight: Regimes detect how an asset is moving (volatility, consistency, momentum patterns), not just where it’s moving (price direction). A stock can be up for the year but in a crisis regime if recent behavior shows extreme volatility and uncertainty. This is exactly the kind of risk management insight that makes regime detection valuable - it tells you when the character of price action has changed, even if the overall trend remains positive.

The Technical Magic: How MCP Bridges AI and Quant Tools

For the technically curious, here’s what makes this possible:

Model Context Protocol (MCP) is Anthropic’s open protocol for connecting AI assistants to external tools and data sources. It defines a standardized interface for:

  • Tools: Functions the AI can call (like our detect_regime)
  • Resources: URI-addressable data the AI can read
  • Prompts: Pre-configured workflows the AI can execute

FastMCP is the Python framework we use to implement the MCP server. It provides decorator-based registration:

 1from fastmcp import FastMCP
 2
 3mcp = FastMCP(name="Hidden Regime")
 4
 5@mcp.tool()
 6async def detect_regime(ticker: str, n_states: int = 3) -> dict:
 7    """Detect current market regime with HMM analysis"""
 8    pipeline = create_financial_pipeline(ticker, n_states=n_states)
 9    result = pipeline.update()
10    return format_result(result)
11
12@mcp.prompt()
13async def regime_quick_check(ticker: str) -> str:
14    """Quick market health check"""
15    return f"""Perform a quick market health check for {ticker}:
16    1. Call detect_regime for {ticker}
17    2. Focus on regime, confidence, and maturity
18    3. Provide 3-4 sentence actionable summary
19    """

When you ask Claude a question about regimes:

  1. Claude recognizes the query relates to market regimes
  2. Claude identifies which Hidden Regime tools/prompts are relevant
  3. Claude calls the MCP tool (via STDIO transport, locally on your machine)
  4. Our MCP server executes the Hidden Regime pipeline
  5. Results flow back to Claude
  6. Claude interprets and presents results in natural language

All of this happens locally. Your data never leaves your machine. The MCP server runs as a subprocess of Claude Desktop, communicating via standard input/output.

Getting Started: 5 Minutes to Conversational Regime Detection

1. Install Hidden Regime with MCP extras

1pip install hidden-regime[mcp]

This installs the core library plus FastMCP and dependencies.

2. Find your server path

1python -c "import hidden_regime_mcp; print(hidden_regime_mcp.__file__.replace('/__init__.py', ''))"

3. Configure Claude Desktop

Add this to your Claude Desktop configuration file:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Linux: ~/.config/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json

 1{
 2  "mcpServers": {
 3    "hidden-regime": {
 4      "command": "/path/to/your/python",
 5      "args": [
 6        "-m",
 7        "fastmcp",
 8        "run",
 9        "/path/from/step2/server.py"
10      ]
11    }
12  }
13}

Replace /path/to/your/python with your Python path (run which python to find it).

4. Restart Claude Desktop

Completely quit Claude Desktop (Cmd+Q on Mac, not just close window) and restart.

5. Try it out

Ask Claude:

What's SPY's current market regime?

If everything is configured correctly, Claude will automatically call the Hidden Regime tools and provide analysis. You should see logs showing data fetching and model training.

What This Means for Regime Detection

The MCP integration fundamentally changes who can use sophisticated regime detection:

Before: Quantitative analysts, data scientists, developers who can write Python After: Anyone who can have a conversation with Claude

This democratization doesn’t sacrifice rigor. The same Hidden Regime pipeline that data scientists use in production backtests is powering these conversational queries. You get:

  • Baum-Welch training for parameter estimation
  • Viterbi inference for most-likely regime sequences
  • Forward-backward probabilities for confidence scores
  • Temporal isolation for backtesting (when you use the full Python library)
  • Data-driven regime interpretation (not hardcoded thresholds)

The difference is the interface. Instead of writing pipeline.update(), you ask “What’s the current regime?” The math doesn’t change. The accessibility does.

Real-World Use Cases

Morning Market Review

Instead of opening a Python notebook, traders can ask Claude:

  • “Quick check on SPY, QQQ, and IWM regimes”
  • “Any of my watchlist stocks in transition zones?” (if you’ve set up a watchlist)
  • “Compare today’s regime confidence to yesterday” (when Claude has conversation history)

Strategy Selection

Active traders can get instant strategy recommendations:

  • “What strategies suit QQQ’s current regime with medium risk tolerance?”
  • “I’m trading AAPL - should I use trend-following or mean reversion?”

Risk Management

Portfolio managers can assess regime-based risk:

  • “Run a risk assessment on my portfolio: SPY 40%, QQQ 30%, GLD 20%, TLT 10%”
  • “Which of my holdings are in mature regimes approaching transition?”
  • “What’s the concentration risk in my current allocations?”

Research and Education

Students and researchers can explore regime concepts:

  • “Show me how SPY’s regimes behaved during the 2008 financial crisis”
  • “Compare regime stability in tech stocks vs broad market”
  • “What’s the typical duration of bull regimes in QQQ?”

Limitations and Disclaimers

Let’s be clear about what this is and isn’t:

This is an educational tool. Hidden Regime is designed for learning about regime detection, exploring market dynamics, and understanding Hidden Markov Models in finance. It is not financial advice.

Data quality matters. We use yfinance for free market data. It’s great for educational purposes and generally reliable for major indices, but it can have gaps, delays, or missing data. Professional applications should use professional data sources.

Regimes are probabilistic. When we say “89% confidence in bearish regime,” that’s a statistical statement about model certainty, not a guarantee about future price action. Markets are stochastic. Regimes can change abruptly.

Past patterns don’t guarantee future outcomes. Historical regime analysis is informative but not predictive. The fact that bull regimes historically lasted 45 days doesn’t mean the current one will.

Gaussian emissions have limitations. Our HMMs use Gaussian emission distributions, which can underestimate tail risk. Black swan events may not fit neatly into detected regime structures.

Always validate. If you’re going to make real trading decisions based on regime analysis (educational disclaimer aside), validate the methodology on your specific instruments, timeframes, and market conditions first.

What’s Next: The MCP Roadmap

The 2.0.0 release completes four of the five MCP interfaces (Tools, Resources, Prompts, Logging). Here’s what’s coming:

Enhanced Prompts (Phase 2):

  • Sector-specific regime analysis
  • Options strategy recommendations based on regime + volatility
  • Historical backtesting of regime-based strategies
  • Educational prompts explaining HMM mathematics

Multi-Timeframe Support:

  • Analyze daily, weekly, and monthly regimes simultaneously
  • Detect regime alignment across timeframes (high-conviction signals)
  • Currently available in Python library, coming to MCP

Streaming Updates:

  • Real-time regime updates as markets move (when MCP supports server-initiated messages)
  • Alerts when regimes transition

Advanced Analytics:

  • Regime strength scoring (how “pure” is this regime?)
  • Regime divergence detection (one asset’s regime diverging from correlated assets)
  • Regime-based correlation analysis

See the MCP Roadmap for full details and implementation timeline.

Try It Yourself

The MCP integration is live in Hidden Regime 2.0.0. If you have Claude Desktop, you can set this up in 5 minutes and start exploring regime detection through conversation.

Installation:

1pip install hidden-regime[mcp]

Documentation:

Get Help:

Stay Updated:

  • Star the repo on GitHub to follow development
  • Watch for 2.1.0 release with enhanced prompts and multi-timeframe support

Final Thoughts: The Intersection of AI and Quantitative Finance

The Model Context Protocol represents something genuinely new: a standardized way to expose sophisticated quantitative tools to AI assistants. This isn’t just a chatbot with canned responses. It’s genuine orchestration of complex analytical workflows through natural language.

Hidden Regime’s MCP integration demonstrates what becomes possible when you combine:

  • Rigorous quantitative methods (Hidden Markov Models with proper statistical inference)
  • Clean software architecture (pipeline pattern with temporal isolation)
  • Modern AI assistants (Claude’s reasoning and natural language understanding)
  • Open protocols (MCP as a standardized integration layer)

The result is something that would have seemed like science fiction just a few years ago: having a conversation with your trading data, asking sophisticated questions about regime dynamics, and getting back analysis grounded in actual statistical models.

We’re excited to see what the community builds with this. If you create interesting prompts, discover valuable workflows, or have ideas for enhancements, please share them. This is an open-source educational project, and it gets better when the community contributes.

Now if you’ll excuse me, I have a question for Claude: “What’s the regime risk score for my portfolio right now?”


Hidden Regime is an open-source educational project for exploring market regime detection using Hidden Markov Models. It is not financial advice and should not be used as the sole basis for investment decisions. Always consult with qualified financial professionals before making investment decisions.

The Model Context Protocol (MCP) is an open protocol developed by Anthropic for connecting AI assistants to external tools and data sources. Learn more at modelcontextprotocol.io.