ToolsAnalysis ToolsMarket Regime Detection

Market Regime Detection Tools

Market regime detection tools identify different market conditions and phases, helping investors understand the current state of a stock and make informed decisions. These tools are part of the Analysis Tools suite.

Overview

Market regimes represent distinct periods characterized by different statistical properties, trends, and behaviors. Identifying these regimes is crucial for:

  • Risk Management: Adjusting position sizes based on volatility regimes
  • Strategy Selection: Choosing appropriate strategies for different market phases
  • Timing Decisions: Identifying optimal entry and exit points
  • Portfolio Allocation: Adapting asset allocation to market conditions

Detection Methods

Copinance OS supports multiple methodologies for regime detection:

Rule-Based Detection (Current Implementation)

Rule-based tools use technical indicators, moving averages, and threshold-based logic. These are fast, interpretable, and work well for most use cases.

Available Tools:

  • Trend Detection (MA crossovers, momentum)
  • Volatility Detection (rolling volatility with thresholds)
  • Cycle Detection (Wyckoff methodology)
  • Market Regime Indicators (VIX, market breadth, sector rotation)

Statistical Inference (Future)

Statistical methods will use probabilistic models like Hidden Markov Models (HMM) and Hamilton Regime Switching Models for more sophisticated regime inference.

Planned Tools:

  • HMM-based regime detection
  • Hamilton Regime Switching Models
  • Bayesian regime detection

Usage:

# Rule-based tools (default, current)
from copinanceos.infrastructure.tools.analysis import create_market_regime_tools
tools = create_market_regime_tools(provider)
 
# Or explicitly specify rule-based
from copinanceos.infrastructure.tools.analysis.market_regime.registry import (
    create_regime_tools_by_type,
)
rule_tools = create_regime_tools_by_type(provider, "rule_based")
 
# Statistical tools (when implemented)
stat_tools = create_regime_tools_by_type(provider, "statistical")
 
# Get all available tools
from copinanceos.infrastructure.tools.analysis.market_regime.registry import (
    create_all_regime_tools,
)
all_tools = create_all_regime_tools(provider, methods=["rule_based", "statistical"])

Rule-Based Tools

1. Trend Detection Tool (detect_market_trend)

Method: Rule-based using moving averages and momentum indicators

Detects market trend regimes (bull, bear, or neutral) using moving averages and price momentum.

Methodology Improvements:

  • Log-Returns: Uses log-returns (rt = ln(Pt / Pt-1)) instead of simple returns for:
    • Better statistical properties (additivity, symmetry)
    • Improved handling of high-volatility stocks (e.g., MSTR, crypto-related stocks)
    • More accurate multi-period calculations
  • Volatility-Scaled Thresholds: Replaces hard thresholds (±5%, ±20%) with volatility-scaled momentum:
    • AdjMomentum = log_return / σ
    • Thresholds: ±0.25σ (medium confidence), ±1.0σ (high confidence)
    • Prevents penalizing low-volatility stocks while maintaining sensitivity for high-volatility stocks

Parameters:

  • symbol (required): Stock ticker symbol (e.g., ‘AAPL’, ‘MSFT’)
  • lookback_days (optional, default: 200): Number of days to analyze
  • short_ma_period (optional, default: 50): Short-term moving average period in days
  • long_ma_period (optional, default: 200): Long-term moving average period in days

Returns:

  • regime: Classification (“bull”, “bear”, or “neutral”)
  • confidence: Confidence level (“high”, “medium”, or “low”)
  • current_price: Current stock price
  • price_change_pct: Log-return as percentage over the period (for display)
  • log_return: Raw log-return value (r_t = ln(P_t / P_0))
  • volatility_scaled_momentum: Momentum scaled by volatility (AdjMomentum = log_return / σ)
  • recent_volatility: Recent volatility (annualized, as percentage)
  • momentum_20d_pct: 20-day momentum percentage (using log-returns)
  • short_ma: Current short-term moving average value
  • long_ma: Current long-term moving average value
  • ma_relationship: Relationship between MAs (“bullish”, “bearish”, or “neutral”)
  • parameters_adjusted: Boolean indicating if parameters were adapted for limited data
  • methodology: “log_returns_with_volatility_scaling”

Example:

from copinanceos.infrastructure.tools.analysis import MarketRegimeDetectTrendTool
from copinanceos.infrastructure.data_providers import YFinanceMarketProvider
 
provider = YFinanceMarketProvider()
tool = MarketRegimeDetectTrendTool(provider)
result = await tool.execute(symbol="AAPL", lookback_days=200)
 
if result.success:
    print(f"Regime: {result.data['regime']}")
    print(f"Confidence: {result.data['confidence']}")

Academic Foundation:

  • Faber (2007): A Quantitative Approach to Tactical Asset Allocation. Journal of Wealth Management, 9(4), 69-79. This tool implements the 10-month MA regime filter methodology adapted for shorter timeframes.
  • Brock, Lakonishok, & LeBaron (1992): Simple Technical Trading Rules and the Stochastic Properties of Stock Returns. Journal of Finance, 47(5), 1731-1764. Validates the effectiveness of MA crossovers for trend detection.
  • Moskowitz, Ooi, & Pedersen (2012): Time Series Momentum. Journal of Financial Economics, 104(2), 228-250. Provides the theoretical foundation for momentum-based trend alignment.

2. Volatility Regime Detection Tool (detect_volatility_regime)

Method: Rule-based using rolling volatility with statistical thresholds

Detects volatility regimes (high, normal, or low) using rolling volatility analysis.

Why Rolling Volatility vs GARCH: While GARCH models are theoretically superior, we use rolling volatility because:

  • More stable on individual stocks (GARCH can be unstable)
  • Easier to explain and interpret for users
  • Less prone to overfitting on retail investment horizons
  • Robust and reliable for practical applications

Current Implementation:

  • Rolling volatility using log-returns (simple moving average)
  • Classification using μ ± σ thresholds

Future Improvements:

  • EWMA Volatility (RiskMetrics style): More responsive to recent changes
    • Formula: σ²t = λ * σ²t-1 + (1 - λ) * r²t
    • Decay factor λ = 0.94 for daily data (RiskMetrics standard)
  • Percentile-Based Regimes: More robust to outliers
    • Top 80% → High volatility
    • Bottom 20% → Low volatility
    • Middle → Normal volatility

Parameters:

  • symbol (required): Stock ticker symbol
  • lookback_days (optional, default: 252): Number of days to analyze (typically 1 trading year)
  • volatility_window (optional, default: 20): Window size for volatility calculation in days

Returns:

  • regime: Classification (“high”, “normal”, or “low”)
  • current_volatility: Current volatility as percentage
  • mean_volatility: Mean volatility over the period
  • max_volatility: Maximum volatility observed
  • min_volatility: Minimum volatility observed
  • volatility_percentile: Current volatility percentile
  • parameters_adjusted: Boolean indicating if parameters were adapted

Example:

from copinanceos.infrastructure.tools.analysis import MarketRegimeDetectVolatilityTool
 
tool = MarketRegimeDetectVolatilityTool(provider)
result = await tool.execute(symbol="AAPL", lookback_days=252)
 
if result.success:
    print(f"Volatility Regime: {result.data['regime']}")
    print(f"Current Volatility: {result.data['current_volatility']}%")

Academic Foundation:

  • Andersen & Bollerslev (1998): Answering the Skeptics: Yes, Standard Volatility Models Do Provide Accurate Forecasts. International Economic Review, 39(4), 885-905. Validates the use of realized volatility models for forecasting.
  • RiskMetrics Technical Document (J.P. Morgan, 1996): Provides the methodology for rolling volatility calculations with annualization for daily data.

How It Works: The tool calculates rolling volatility as the standard deviation of log-returns over a specified window. Volatility is annualized assuming 252 trading days per year.

Current Classification (μ ± σ): Regime classification is based on statistical deviation from the historical mean:

  • High: Current volatility > mean + 1 standard deviation
  • Low: Current volatility < mean - 1 standard deviation
  • Normal: Within one standard deviation of the mean

Future: Percentile-Based Classification: A more robust alternative using percentiles:

  • High: Current volatility ≥ 80th percentile
  • Low: Current volatility ≤ 20th percentile
  • Normal: Between 20th and 80th percentile

The percentile-based approach is more robust to outliers and provides clearer regime boundaries.

3. Market Cycle Detection Tool (detect_market_cycles)

Method: Rule-based using Wyckoff methodology

Detects market cycles and regime transitions, identifying accumulation, markup, distribution, and markdown phases.

Parameters:

  • symbol (required): Stock ticker symbol
  • lookback_days (optional, default: 252): Number of days to analyze

Returns:

  • current_phase: Cycle phase (“accumulation”, “markup”, “distribution”, “markdown”, or “transition”)
  • phase_description: Human-readable description of the phase
  • price_position_pct: Current price position within the period’s range (0-100%)
  • volume_ratio: Recent volume relative to average volume
  • current_price: Current stock price
  • ma_20: 20-day moving average value
  • ma_50: 50-day moving average value
  • recent_trend: Short-term trend direction
  • longer_trend: Longer-term trend direction
  • potential_regime_change: Boolean indicating potential regime transition
  • parameters_adjusted: Boolean indicating if parameters were adapted

Example:

from copinanceos.infrastructure.tools.analysis import MarketRegimeDetectCyclesTool
 
tool = MarketRegimeDetectCyclesTool(provider)
result = await tool.execute(symbol="AAPL", lookback_days=252)
 
if result.success:
    print(f"Current Phase: {result.data['current_phase']}")
    print(f"Description: {result.data['phase_description']}")
    print(f"Regime Change Signal: {result.data['potential_regime_change']}")

Academic Foundation:

  • Hamilton (1989): A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle. Econometrica, 57(2), 357-384. Provides the theoretical foundation for regime switching models in financial time series.
  • Wyckoff Method (1930s, modernized): A technical analysis methodology that identifies four distinct market phases:
    • Accumulation: Price near lows, low volume, smart money buying
    • Markup: Price rising, increasing volume, public participation
    • Distribution: Price near highs, high volume, smart money selling
    • Markdown: Price falling, decreasing volume, public selling
  • Lo (2004): The Adaptive Markets Hypothesis: Market Efficiency from an Evolutionary Perspective. Journal of Portfolio Management, 30(5), 15-29. Explains why market regimes exist and change over time through an evolutionary perspective.

Cycle Phases Explained:

  1. Accumulation Phase

    • Price position: Bottom 30% of range
    • Volume: Below average
    • Characteristics: Smart money accumulates positions, price stabilizes near lows
    • Investment implication: Potential buying opportunity for long-term investors
  2. Markup Phase

    • Price position: Rising, above moving averages
    • Volume: Increasing, above average
    • Characteristics: Strong uptrend, public participation increases
    • Investment implication: Trend-following strategies perform well
  3. Distribution Phase

    • Price position: Top 70% of range
    • Volume: Elevated
    • Characteristics: Smart money distributes holdings, price may stall
    • Investment implication: Consider taking profits, prepare for potential reversal
  4. Markdown Phase

    • Price position: Falling, below moving averages
    • Volume: Decreasing
    • Characteristics: Downtrend, public selling pressure
    • Investment implication: Defensive positioning, avoid catching falling knives

Market Regime Indicators Tool (get_market_regime_indicators)

Method: Market-wide indicators using VIX, sector ETFs, and market breadth analysis

Provides comprehensive market regime indicators including VIX (volatility index), market breadth analysis, and sector rotation signals. This tool complements individual stock regime detection by providing broader market context.

What It Provides:

  1. VIX (Volatility Index): Measures market fear and complacency
  2. Market Breadth: Analyzes sector participation in market moves
  3. Sector Rotation: Identifies which sectors are gaining/losing momentum

Parameters:

  • market_index (optional, default: “SPY”): Market index symbol for comparison
  • lookback_days (optional, default: 252): Number of days to analyze (~1 trading year)
  • include_vix (optional, default: true): Include VIX volatility index data
  • include_market_breadth (optional, default: true): Include market breadth analysis
  • include_sector_rotation (optional, default: true): Include sector rotation signals

Returns:

The tool returns a dictionary with three main sections:

VIX Data (when include_vix=true):

  • available: Boolean indicating if VIX data is available
  • current_vix: Current VIX level
  • recent_average_20d: 20-day average VIX level
  • recent_max_20d: Maximum VIX in last 20 days
  • recent_min_20d: Minimum VIX in last 20 days
  • regime: VIX regime classification (“low”, “normal”, “high”, “very_high”)
    • low: VIX < 15 (complacent market)
    • normal: 15 ≤ VIX < 25 (normal volatility)
    • high: 25 ≤ VIX < 30 (fearful market)
    • very_high: VIX ≥ 30 (panic)
  • sentiment: Market sentiment (“complacent”, “normal”, “fearful”, “panic”)
  • data_points: Number of data points used

Market Breadth (when include_market_breadth=true):

  • available: Boolean indicating if breadth data is available
  • breadth_ratio: Percentage of sectors above 50-day moving average
  • participation_ratio: Percentage of sectors outperforming the market
  • sectors_above_50ma: Count of sectors above their 50-day MA
  • sectors_outperforming: Count of sectors outperforming the market
  • total_sectors_analyzed: Total number of sectors analyzed
  • regime: Breadth regime classification (“strong”, “moderate”, “weak”)
    • strong: ≥70% of sectors above MA and outperforming
    • moderate: 40-70% participating
    • weak: <40% participating
  • sector_details: Dictionary with detailed performance for each sector ETF:
    • name: Sector name
    • current_price: Current sector ETF price
    • above_50ma: Boolean indicating if above 50-day MA
    • relative_performance_pct: Sector return vs. market return
    • sector_return_pct: Sector return percentage
    • market_return_pct: Market return percentage

Sector Rotation (when include_sector_rotation=true):

  • available: Boolean indicating if rotation data is available
  • rotation_theme: Overall rotation theme (“defensive”, “growth”, “value”, “mixed”)
    • defensive: Utilities (XLU) or Consumer Staples (XLP) leading
    • growth: Technology (XLK) or Consumer Discretionary (XLY) leading
    • value: Financials (XLF) or Industrials (XLI) leading
    • mixed: No clear theme
  • leading_sectors: Top 3 sectors by momentum score (list of sector dictionaries)
  • lagging_sectors: Bottom 3 sectors by momentum score (list of sector dictionaries)
  • all_sectors_ranked: All sectors sorted by momentum score (highest first)
  • market_return_20d: Market return over last 20 days (percentage)
  • market_return_60d: Market return over last 60 days (percentage)

Each sector in the rotation data includes:

  • symbol: Sector ETF symbol (e.g., “XLK”)
  • name: Sector name (e.g., “Technology”)
  • momentum_score: Weighted momentum score (20d: 60%, 60d: 40%)
  • relative_momentum_20d: Sector momentum vs. market (20-day)
  • relative_momentum_60d: Sector momentum vs. market (60-day)
  • sector_return_20d: Sector return over last 20 days
  • sector_return_60d: Sector return over last 60 days

Example:

from copinanceos.infrastructure.tools.analysis import MarketRegimeIndicatorsTool
from copinanceos.infrastructure.data_providers import YFinanceMarketProvider
 
provider = YFinanceMarketProvider()
tool = MarketRegimeIndicatorsTool(provider)
 
# Get all indicators
result = await tool.execute(market_index="SPY", lookback_days=252)
 
if result.success:
    # VIX data
    if result.data.get("vix", {}).get("available"):
        print(f"Current VIX: {result.data['vix']['current_vix']}")
        print(f"VIX Regime: {result.data['vix']['regime']}")
        print(f"Market Sentiment: {result.data['vix']['sentiment']}")
    
    # Market breadth
    if result.data.get("market_breadth", {}).get("available"):
        breadth = result.data["market_breadth"]
        print(f"Breadth Ratio: {breadth['breadth_ratio']}%")
        print(f"Breadth Regime: {breadth['regime']}")
        print(f"Sectors Above MA: {breadth['sectors_above_50ma']}/{breadth['total_sectors_analyzed']}")
    
    # Sector rotation
    if result.data.get("sector_rotation", {}).get("available"):
        rotation = result.data["sector_rotation"]
        print(f"Rotation Theme: {rotation['rotation_theme']}")
        print(f"Leading Sectors: {[s['name'] for s in rotation['leading_sectors']]}")
        print(f"Lagging Sectors: {[s['name'] for s in rotation['lagging_sectors']]}")
 
# Get only VIX data
vix_result = await tool.execute(include_market_breadth=False, include_sector_rotation=False)

Use Cases:

  1. Risk Assessment: VIX levels help assess overall market risk and fear levels
  2. Market Health: Market breadth indicates whether market moves are broad-based or narrow
  3. Sector Allocation: Sector rotation signals help identify which sectors to overweight/underweight
  4. Regime Confirmation: Use alongside individual stock regime tools to confirm broader market context

Interpretation Guide:

VIX Levels:

  • VIX < 15: Low volatility, complacent market. Often precedes volatility spikes.
  • VIX 15-25: Normal volatility range. Healthy market conditions.
  • VIX 25-30: Elevated fear. Market stress, potential buying opportunities for contrarians.
  • VIX > 30: Panic levels. Extreme fear, often marks market bottoms.

Market Breadth:

  • Strong Breadth (≥70%): Healthy market with broad participation. Bull markets typically show strong breadth.
  • Moderate Breadth (40-70%): Mixed signals. Some sectors leading, others lagging.
  • Weak Breadth (<40%): Narrow market. Few sectors driving gains, potential weakness ahead.

Sector Rotation Themes:

  • Defensive Rotation: Utilities and staples leading. Often occurs during market uncertainty or downturns.
  • Growth Rotation: Technology and discretionary leading. Typical in risk-on environments and bull markets.
  • Value Rotation: Financials and industrials leading. Often signals economic recovery or reflation.
  • Mixed Rotation: No clear theme. Market in transition or uncertain phase.

Data Sources:

  • All data is fetched using free sources via the yfinance provider
  • VIX: CBOE Volatility Index (^VIX)
  • Market Breadth: 11 sector ETFs (XLK, XLE, XLI, XLV, XLF, XLP, XLY, XLU, XLB, XLC, XLRE)
  • Sector Rotation: Same sector ETFs with momentum analysis

Note: This tool analyzes market-wide indicators, not individual stocks. Use it in combination with individual stock regime detection tools for comprehensive analysis.

Adaptive Data Handling

All market regime detection tools include adaptive parameter adjustment for stocks with limited trading history. This is particularly important for:

  • Newly listed stocks: IPOs and recent listings
  • Low-volume stocks: Stocks with irregular trading
  • International stocks: May have different trading calendars

How It Works:

  • Tools automatically adjust moving average periods and analysis windows based on available data
  • Minimum data requirements are enforced (10-20 data points depending on the tool)
  • Results include a parameters_adjusted flag and explanatory notes when adaptation occurs
  • Confidence levels are adjusted to reflect data limitations

Example:

result = await tool.execute(symbol="NEWLY_LISTED", lookback_days=200)
 
if result.data.get('parameters_adjusted'):
    print(f"Note: {result.data.get('note')}")
    print(f"Adjusted parameters used: {result.data.get('short_ma_period_used')}/{result.data.get('long_ma_period_used')}")

Using Tools in Workflows

Agentic Workflows

Tools are automatically available in agentic workflows when a market data provider is configured. The LLM will automatically select and use the appropriate tools based on your question.

Individual Stock Analysis:

# Analyze trend and volatility for a specific stock
copinance research ask AAPL "What is the current market trend and volatility regime?"
 
# Analyze market cycles
copinance research ask TSLA "What market cycle phase is this stock in?"
 
# Comprehensive regime analysis
copinance research ask MSFT "Analyze the market regime for this stock including trend, volatility, and cycle phases"

Market-Wide Indicators:

# Get market-wide context with VIX and sector analysis
copinance research ask SPY "What is the current market sentiment and which sectors are leading?"
 
# Analyze market breadth
copinance research ask "What is the current market breadth and sector rotation?"
 
# VIX and volatility analysis
copinance research ask "What is the current VIX level and market fear sentiment?"
 
# Sector rotation analysis
copinance research ask "Which sectors are currently outperforming and what rotation theme is active?"

Combined Analysis:

# Combine individual stock and market-wide analysis
copinance research ask AAPL "Analyze this stock's regime and compare it to the broader market conditions including VIX and sector rotation"

The LLM will automatically use the appropriate tools (detect_market_trend, detect_volatility_regime, detect_market_cycles, or get_market_regime_indicators) based on your question.

Programmatic Usage

from copinanceos.infrastructure.tools.analysis import (
    create_market_regime_tools,
    MarketRegimeIndicatorsTool,
)
from copinanceos.infrastructure.data_providers import YFinanceMarketProvider
 
# Create rule-based detection tools
provider = YFinanceMarketProvider()
tools = create_market_regime_tools(provider)
 
# Use individual detection tools
trend_tool = tools[0]
result = await trend_tool.execute(symbol="AAPL")
 
# Create and use indicators tool
indicators_tool = MarketRegimeIndicatorsTool(provider)
indicators_result = await indicators_tool.execute(market_index="SPY")

Tool Registry

Tools can also be registered in a tool registry for centralized management:

from copinanceos.infrastructure.tools import ToolRegistry
from copinanceos.infrastructure.tools.analysis import create_market_regime_tools
 
registry = ToolRegistry()
tools = create_market_regime_tools(provider)
registry.register_many(tools)
 
# Get a tool by name
trend_tool = registry.get("detect_market_trend")

Academic References

Complete Bibliography

  1. Andersen, T. G., & Bollerslev, T. (1998). Answering the Skeptics: Yes, Standard Volatility Models Do Provide Accurate Forecasts. International Economic Review, 39(4), 885-905.

  2. Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple Technical Trading Rules and the Stochastic Properties of Stock Returns. Journal of Finance, 47(5), 1731-1764.

  3. Faber, M. T. (2007). A Quantitative Approach to Tactical Asset Allocation. Journal of Wealth Management, 9(4), 69-79.

  4. Hamilton, J. D. (1989). A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle. Econometrica, 57(2), 357-384.

  5. Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. Journal of Finance, 48(1), 65-91.

  6. Lo, A. W. (2004). The Adaptive Markets Hypothesis: Market Efficiency from an Evolutionary Perspective. Journal of Portfolio Management, 30(5), 15-29.

  7. Moskowitz, T. J., Ooi, Y. H., & Pedersen, L. H. (2012). Time Series Momentum. Journal of Financial Economics, 104(2), 228-250.

  8. RiskMetrics Technical Document (J.P. Morgan, 1996). RiskMetrics—Technical Document (4th ed.). J.P. Morgan/Reuters.

  9. Wyckoff, R. D. (1930s). The Wyckoff Method. (Modernized by various practitioners including David H. Weis, Tom Williams, and others).

Best Practices

  1. Data Quality: Ensure sufficient historical data for reliable regime detection
  2. Multiple Timeframes: Use different lookback periods to confirm regime signals
  3. Combined Analysis: Use all tools together for comprehensive market assessment:
    • Individual stock tools (trend, volatility, cycles) for stock-specific analysis
    • Market indicators tool for broader market context
  4. Confidence Levels: Pay attention to confidence indicators, especially with limited data
  5. Regime Transitions: Monitor potential_regime_change signals for early warning of shifts
  6. Adaptive Parameters: Be aware when parameters are adjusted and interpret results accordingly
  7. Market Context: Always consider market-wide indicators when analyzing individual stocks

Limitations

  • Historical Data Dependency: Tools require sufficient historical data for accurate detection
  • Market-Specific: Results may vary across different markets and asset classes
  • Lagging Indicators: Moving averages and volatility are lagging indicators
  • False Signals: No tool is perfect; combine with other analysis methods
  • Data Quality: Results depend on the quality of data from the underlying provider

Package Structure & Extensibility

The market regime detection tools are organized in a modular structure to support multiple detection methodologies and future extensions.

Current Structure

infrastructure/tools/analysis/market_regime/
├── __init__.py          # Public API exports (backward compatible)
├── base.py              # Common interfaces and base classes
├── rule_based.py        # Rule-based detection (current implementation)
├── indicators.py        # Market regime indicators (VIX, breadth, rotation)
├── statistical.py       # Statistical inference (future: HMM, Hamilton models)
└── registry.py          # Factory functions for unified tool creation

Design Principles

  1. Separation of Concerns: Each detection method is in its own module
  2. Common Interface: All tools implement the Tool interface via BaseRegimeDetectionTool
  3. Extensibility: Easy to add new methods without breaking existing code
  4. Backward Compatibility: Existing code continues to work with default imports

Adding New Detection Methods

To add a new detection method (e.g., machine learning-based):

  1. Create a new module (e.g., machine_learning.py):
from copinanceos.infrastructure.tools.analysis.market_regime.base import (
    BaseRegimeDetectionTool,
)
 
class MLRegimeDetectionTool(BaseRegimeDetectionTool):
    def get_detection_method(self) -> str:
        return "machine_learning"
    
    async def _detect_regime(self, symbol: str, **kwargs: Any) -> dict[str, Any]:
        # Your ML-based detection logic
        pass
    
    async def _execute_impl(self, **kwargs: Any) -> ToolResult:
        # Implementation
        pass
  1. Add factory function:
def create_ml_regime_tools(provider: MarketDataProvider) -> list[Tool]:
    return [MLRegimeDetectionTool(provider)]
  1. Update registry.py to include the new method in create_all_regime_tools()

  2. Update __init__.py to export the new tools

Using Different Methods

# Rule-based tools (default, current)
from copinanceos.infrastructure.tools.analysis import (
    create_market_regime_tools,
    MarketRegimeIndicatorsTool,
)
tools = create_market_regime_tools(provider)
 
# Market regime indicators tool (separate from detection tools)
indicators_tool = MarketRegimeIndicatorsTool(provider)
 
# Explicitly specify method type
from copinanceos.infrastructure.tools.analysis.market_regime.registry import (
    create_regime_tools_by_type,
)
rule_tools = create_regime_tools_by_type(provider, "rule_based")
stat_tools = create_regime_tools_by_type(provider, "statistical")  # When implemented
 
# Get all available tools from multiple methods
from copinanceos.infrastructure.tools.analysis.market_regime.registry import (
    create_all_regime_tools,
)
all_tools = create_all_regime_tools(
    provider, 
    methods=["rule_based", "statistical"]  # Add more as they're implemented
)
# Note: MarketRegimeIndicatorsTool is separate and must be created explicitly

Future Extensions

The structure is designed to accommodate:

  • Statistical Methods: Hidden Markov Models (HMM), Hamilton Regime Switching Models
  • Machine Learning: LSTM, transformers, ensemble methods
  • Real-time Detection: Streaming regime detection
  • Multi-asset: Cross-asset regime correlation
  • Probabilistic Models: Bayesian inference, transition probabilities

See Also