File size: 2,501 Bytes
d96a847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

# file: agent_system/perception_tuned.py
import pandas as pd
import numpy as np

class RegimeClassifierTuned:
    def __init__(self, fast_window=10, slow_window=50, vol_window=14):
        # We shortened the windows: 20/50 -> 10/50 for faster reaction
        self.fast_w = fast_window
        self.slow_w = slow_window
        self.vol_w = vol_window

    def get_current_regime(self, df_slice: pd.DataFrame) -> dict:
        tags = set()
        metrics = {}
        
        if len(df_slice) < self.slow_w:
            return {"tags": {"calculating"}, "metrics": {}}

        prices = df_slice['close']
        
        # 1. USE EMA (Exponential Moving Average) FOR SPEED
        # EMA weights recent prices higher, reducing lag significantly
        ema_fast = prices.ewm(span=self.fast_w, adjust=False).mean().iloc[-1]
        ema_slow = prices.ewm(span=self.slow_w, adjust=False).mean().iloc[-1]
        current_price = prices.iloc[-1]

        # Calculate Delta (Percentage spread between EMAs)
        ema_delta = (ema_fast - ema_slow) / ema_slow
        metrics['ema_delta'] = ema_delta
        metrics['ema_fast'] = ema_fast
        metrics['ema_slow'] = ema_slow

        # 2. INSTANT VOLATILITY TRIGGER (The "Panic Button")
        # Instead of waiting for a long-term trend change, check immediate RSI-like stress
        returns = prices.pct_change()
        daily_vol = returns.std()
        recent_vol = returns.tail(5).std() # Look at just the last 5 days
        metrics['volatility_ratio'] = recent_vol / daily_vol if daily_vol > 0 else 1.0
        
        # 3. LOGIC GATES
        
        # A. TREND GATES (EMA Cross)
        if ema_fast > ema_slow:
            tags.add("bull_trend")
            tags.add("momentum")
        else:
            tags.add("bear_trend")
            tags.add("defensive") # This triggers the "Cash" force earlier

        # B. CRASH GATE (Price vs EMA)
        # If Price is significantly below the Fast EMA, it's a "Free Fall"
        if current_price < (ema_fast * 0.95): # 5% drop below fast average
            tags.add("crash")
            tags.add("high_vol")
            tags.discard("momentum") # Kill momentum immediately

        # C. VOLATILITY GATE
        # If the last 5 days are 2x more volatile than usual -> PANIC
        if recent_vol > (daily_vol * 2.0):
             tags.add("high_vol")
             tags.add("aggressive_risk") # Or "risk_off" depending on your strategy setup

        return {"tags": tags, "metrics": metrics}