# # file: agent_system/regime.py import numpy as np from dataclasses import dataclass @dataclass class MarketContext: price: float volatility: float trend_strength: float active_tags: set[str] class RegimeDetector: def __init__(self, vol_lookback=30, trend_lookback=60): self.vol_lookback = vol_lookback self.trend_lookback = trend_lookback def detect(self, price_history: np.ndarray) -> MarketContext: """ Analyzes price history to return the 'Field' (Context + Tags). """ if len(price_history) < self.trend_lookback: return MarketContext(0, 0, 0, {"neutral"}) current_price = price_history[-1] # 1. Calculate Volatility (Annualized Std Dev) returns = np.diff(price_history) / price_history[:-1] daily_vol = np.std(returns[-self.vol_lookback:]) annualized_vol = daily_vol * np.sqrt(365) # 2. Calculate Trend (Simple Moving Average Distance) sma = np.mean(price_history[-self.trend_lookback:]) trend_strength = (current_price - sma) / sma # 3. Generate Tags (The "Field Mask") tags = set() # --- Volatility Logic --- if annualized_vol > 0.80: # > 80% Vol tags.add("high_vol") tags.add("defensive") # High vol usually requires defensive posturing elif annualized_vol < 0.30: tags.add("low_vol") tags.add("leverage_friendly") else: tags.add("mid_vol") # --- Trend Logic --- if trend_strength > 0.05: # Price is 5% above SMA tags.add("bull_trend") tags.add("momentum") elif trend_strength < -0.05: tags.add("bear_trend") tags.add("short") else: tags.add("chop") tags.add("mean_reversion") # --- Domain Logic --- # (Mock: If volatility is insane, tag as 'crypto_winter') if annualized_vol > 1.0 and trend_strength < -0.2: tags.add("crypto_winter") return MarketContext(current_price, annualized_vol, trend_strength, tags) # Example Usage # prices = np.random.normal(100, 2, 100) # detector = RegimeDetector() # ctx = detector.detect(prices) # print(ctx.active_tags)