Correlation Regime Switcher
import pandas as pd
import numpy as np
class CorrelationRegimeSwitcher:
REGIME_STRATEGIES = {
"normal_correlation": {
"description": "Correlations at historical norms",
"strategies": ["trend_following", "carry_trade", "mean_reversion_pairs"],
"risk_level": "NORMAL",
},
"correlation_breakdown": {
"description": "Historical correlations breaking down",
"strategies": ["single_pair_momentum", "volatility_selling"],
"risk_level": "ELEVATED — reduce correlated positions",
},
"correlation_spike": {
"description": "All assets moving together (crisis mode)",
"strategies": ["safe_haven_only", "volatility_buying", "cash"],
"risk_level": "HIGH — correlation=1 means no diversification benefit",
},
"decorrelation": {
"description": "Assets becoming uncorrelated — dispersion rising",
"strategies": ["pairs_trading", "relative_value", "basket_trades"],
"risk_level": "OPPORTUNITY — dispersion creates relative value trades",
},
}
@staticmethod
def detect_regime(correlation_matrix: pd.DataFrame, historical_avg_corr: float) -> dict:
"""Classify current correlation regime."""
upper_tri = correlation_matrix.values[np.triu_indices_from(correlation_matrix.values, k=1)]
current_avg = np.mean(np.abs(upper_tri))
deviation = current_avg - abs(historical_avg_corr)
if current_avg > 0.8:
regime = "correlation_spike"
elif deviation > 0.15:
regime = "correlation_spike"
elif deviation < -0.15:
regime = "decorrelation"
elif abs(deviation) < 0.05:
regime = "normal_correlation"
else:
regime = "correlation_breakdown"
strategies = CorrelationRegimeSwitcher.REGIME_STRATEGIES[regime]
return {
"regime": regime,
"current_avg_correlation": round(current_avg, 4),
"historical_avg": round(abs(historical_avg_corr), 4),
"deviation": round(deviation, 4),
**strategies,
}
@staticmethod
def transition_detector(rolling_corr: pd.Series, window: int = 20) -> dict:
"""Detect regime transitions from rolling correlation data."""
recent = rolling_corr.tail(window)
prior = rolling_corr.iloc[-(window*2):-window]
change = recent.mean() - prior.mean()
return {
"transition_detected": abs(change) > 0.2,
"direction": "CONVERGING" if change > 0.2 else "DIVERGING" if change < -0.2 else "STABLE",
"magnitude": round(abs(change), 4),
"action": "Switch strategy set — correlation regime changing" if abs(change) > 0.2 else "Hold current strategies",
}
1---2name: correlation-regime-switcher3description: Automatically switches strategy sets when correlation regimes change. Use this skill whenever the user asks about "correlation regime change", "adaptive strategy switching", "when correlations break", "regime-based strategy selection", "correlation breakdown trading", "dynamic strategy switching", "auto-switch strategy", or any question about adapting to changing inter-market relationships. Works with pair-correlation-engine and market-regime-classifier.4---56# Correlation Regime Switcher78```python9import pandas as pd10import numpy as np1112class CorrelationRegimeSwitcher:1314 REGIME_STRATEGIES = {15 "normal_correlation": {16 "description": "Correlations at historical norms",17 "strategies": ["trend_following", "carry_trade", "mean_reversion_pairs"],18 "risk_level": "NORMAL",19 },20 "correlation_breakdown": {21 "description": "Historical correlations breaking down",22 "strategies": ["single_pair_momentum", "volatility_selling"],23 "risk_level": "ELEVATED — reduce correlated positions",24 },25 "correlation_spike": {26 "description": "All assets moving together (crisis mode)",27 "strategies": ["safe_haven_only", "volatility_buying", "cash"],28 "risk_level": "HIGH — correlation=1 means no diversification benefit",29 },30 "decorrelation": {31 "description": "Assets becoming uncorrelated — dispersion rising",32 "strategies": ["pairs_trading", "relative_value", "basket_trades"],33 "risk_level": "OPPORTUNITY — dispersion creates relative value trades",34 },35 }3637 @staticmethod38 def detect_regime(correlation_matrix: pd.DataFrame, historical_avg_corr: float) -> dict:39 """Classify current correlation regime."""40 upper_tri = correlation_matrix.values[np.triu_indices_from(correlation_matrix.values, k=1)]41 current_avg = np.mean(np.abs(upper_tri))42 deviation = current_avg - abs(historical_avg_corr)4344 if current_avg > 0.8:45 regime = "correlation_spike"46 elif deviation > 0.15:47 regime = "correlation_spike"48 elif deviation < -0.15:49 regime = "decorrelation"50 elif abs(deviation) < 0.05:51 regime = "normal_correlation"52 else:53 regime = "correlation_breakdown"5455 strategies = CorrelationRegimeSwitcher.REGIME_STRATEGIES[regime]56 return {57 "regime": regime,58 "current_avg_correlation": round(current_avg, 4),59 "historical_avg": round(abs(historical_avg_corr), 4),60 "deviation": round(deviation, 4),61 **strategies,62 }6364 @staticmethod65 def transition_detector(rolling_corr: pd.Series, window: int = 20) -> dict:66 """Detect regime transitions from rolling correlation data."""67 recent = rolling_corr.tail(window)68 prior = rolling_corr.iloc[-(window*2):-window]69 change = recent.mean() - prior.mean()70 return {71 "transition_detected": abs(change) > 0.2,72 "direction": "CONVERGING" if change > 0.2 else "DIVERGING" if change < -0.2 else "STABLE",73 "magnitude": round(abs(change), 4),74 "action": "Switch strategy set — correlation regime changing" if abs(change) > 0.2 else "Hold current strategies",75 }76```