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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event Risk Guard v1.0 — Pre-Trade Risk Overlay
|
| 2 |
+
Checks for earnings, FOMC, macro releases, and other event risk before execution.
|
| 3 |
+
Reduces position size dynamically based on event proximity and severity.
|
| 4 |
+
Based on: Lo & MacKinlay (1999) event study methodology
|
| 5 |
+
"""
|
| 6 |
+
import re
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
+
from typing import Dict, Optional, List, Tuple
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
# Event severity multipliers (0.0 = full halt, 1.0 = no impact)
|
| 12 |
+
EVENT_IMPACT = {
|
| 13 |
+
'earnings': {'same_day': 0.00, 'd1': 0.30, 'd3': 0.60, 'd7': 0.80, 'd14': 0.90},
|
| 14 |
+
'fed_meeting': {'same_day': 0.00, 'd1': 0.25, 'd3': 0.55, 'd7': 0.75, 'd14': 0.90},
|
| 15 |
+
'cpi_release': {'same_day': 0.15, 'd1': 0.40, 'd3': 0.65, 'd7': 0.85, 'd14': 1.00},
|
| 16 |
+
'jobs_report': {'same_day': 0.10, 'd1': 0.35, 'd3': 0.60, 'd7': 0.80, 'd14': 0.95},
|
| 17 |
+
'gdp': {'same_day': 0.20, 'd1': 0.45, 'd3': 0.70, 'd7': 0.90, 'd14': 1.00},
|
| 18 |
+
'options_expiry': {'same_day': 0.20, 'd1': 0.50, 'd3': 0.80, 'd7': 1.00, 'd14': 1.00},
|
| 19 |
+
'dividend': {'same_day': 0.50, 'd1': 0.70, 'd3': 0.85, 'd7': 1.00, 'd14': 1.00},
|
| 20 |
+
'analyst_day': {'same_day': 0.30, 'd1': 0.55, 'd3': 0.75, 'd7': 0.90, 'd14': 1.00},
|
| 21 |
+
'product_launch': {'same_day': 0.20, 'd1': 0.40, 'd3': 0.65, 'd7': 0.85, 'd14': 1.00},
|
| 22 |
+
'conference': {'same_day': 0.30, 'd1': 0.60, 'd3': 0.80, 'd7': 1.00, 'd14': 1.00},
|
| 23 |
+
'lawsuit_hearing': {'same_day': 0.15, 'd1': 0.35, 'd3': 0.55, 'd7': 0.75, 'd14': 0.90},
|
| 24 |
+
'merger_vote': {'same_day': 0.05, 'd1': 0.20, 'd3': 0.45, 'd7': 0.70, 'd14': 0.90},
|
| 25 |
+
'macro_general': {'same_day': 0.25, 'd1': 0.50, 'd3': 0.70, 'd7': 0.85, 'd14': 1.00},
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
# Minimum days between events to consider them distinct (avoid double-counting)
|
| 29 |
+
EVENT_CLUSTER_WINDOW = 3
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class EventRiskGuard:
|
| 33 |
+
"""Pre-trade event risk overlay with dynamic size reduction."""
|
| 34 |
+
|
| 35 |
+
def __init__(self, impact_table: Optional[Dict] = None):
|
| 36 |
+
self.impact = impact_table or dict(EVENT_IMPACT)
|
| 37 |
+
self._earnings_cache = {}
|
| 38 |
+
self._macro_cache = {}
|
| 39 |
+
|
| 40 |
+
def classify_event(self, headline_or_title: str) -> Tuple[str, float]:
|
| 41 |
+
"""Classify text into event type and confidence (0-1)."""
|
| 42 |
+
text = headline_or_title.lower()
|
| 43 |
+
|
| 44 |
+
patterns = {
|
| 45 |
+
'earnings': ['earnings', 'quarterly', 'revenue', 'eps', 'profit', 'q1', 'q2', 'q3', 'q4', 'fiscal', 'guidance'],
|
| 46 |
+
'fed_meeting': ['fomc', 'federal reserve', 'fed meeting', 'fed rate', 'interest rate decision', 'powell'],
|
| 47 |
+
'cpi_release': ['cpi', 'consumer price', 'inflation data', 'core pce', 'inflation report'],
|
| 48 |
+
'jobs_report': ['jobs report', 'unemployment', 'nonfarm payroll', 'nfp', 'labor market'],
|
| 49 |
+
'gdp': ['gdp', 'economic growth', 'recession', 'economic output'],
|
| 50 |
+
'options_expiry': ['options expiry', 'options expiration', 'op-ex', 'triple witching', 'quadruple witching'],
|
| 51 |
+
'dividend': ['dividend', 'ex-dividend', 'dividend date', 'buyback'],
|
| 52 |
+
'analyst_day': ['analyst day', 'investor day', 'management presentation'],
|
| 53 |
+
'product_launch': ['product launch', 'new product', 'iphone', 'ai model', 'release date', 'unveil'],
|
| 54 |
+
'conference': ['conference call', 'shareholder meeting', 'annual meeting'],
|
| 55 |
+
'lawsuit_hearing': ['court hearing', 'trial date', 'lawsuit', 'sec hearing', 'doj'],
|
| 56 |
+
'merger_vote': ['merger vote', 'shareholder vote', 'acquisition vote'],
|
| 57 |
+
'macro_general': ['macro', 'economic data', 'pmi', 'retail sales', 'housing data'],
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
for etype, keywords in patterns.items():
|
| 61 |
+
count = sum(1 for kw in keywords if kw in text)
|
| 62 |
+
if count > 0:
|
| 63 |
+
confidence = min(1.0, count * 0.3 + 0.1)
|
| 64 |
+
return etype, confidence
|
| 65 |
+
return 'unknown', 0.1
|
| 66 |
+
|
| 67 |
+
def get_event_multiplier(self, event_type: str, days_until: int) -> float:
|
| 68 |
+
"""Get size multiplier (0.0-1.0) based on event type and proximity."""
|
| 69 |
+
table = self.impact.get(event_type, self.impact.get('macro_general'))
|
| 70 |
+
if table is None:
|
| 71 |
+
return 1.0
|
| 72 |
+
|
| 73 |
+
if days_until <= 0:
|
| 74 |
+
return table.get('same_day', 0.25)
|
| 75 |
+
elif days_until <= 1:
|
| 76 |
+
return table.get('d1', 0.35)
|
| 77 |
+
elif days_until <= 3:
|
| 78 |
+
# Linear interpolation between d1 and d3
|
| 79 |
+
d1_mult = table.get('d1', 0.35)
|
| 80 |
+
d3_mult = table.get('d3', 0.60)
|
| 81 |
+
return d1_mult + (d3_mult - d1_mult) * (days_until - 1) / 2
|
| 82 |
+
elif days_until <= 7:
|
| 83 |
+
d3_mult = table.get('d3', 0.60)
|
| 84 |
+
d7_mult = table.get('d7', 0.80)
|
| 85 |
+
return d3_mult + (d7_mult - d3_mult) * (days_until - 3) / 4
|
| 86 |
+
elif days_until <= 14:
|
| 87 |
+
d7_mult = table.get('d7', 0.80)
|
| 88 |
+
d14_mult = table.get('d14', 0.95)
|
| 89 |
+
return d7_mult + (d14_mult - d7_mult) * (days_until - 7) / 7
|
| 90 |
+
else:
|
| 91 |
+
return 1.0
|
| 92 |
+
|
| 93 |
+
def check_events(self, events: List[Dict], base_exposure: float) -> Dict:
|
| 94 |
+
"""Check all upcoming events and compute adjusted exposure.
|
| 95 |
+
|
| 96 |
+
events: List of dicts with keys: 'type', 'date' (ISO), 'severity' (1-5, optional)
|
| 97 |
+
base_exposure: 0.0-1.0 proposed position size
|
| 98 |
+
|
| 99 |
+
Returns adjusted exposure + reasoning.
|
| 100 |
+
"""
|
| 101 |
+
today = datetime.now().date()
|
| 102 |
+
multipliers = []
|
| 103 |
+
reasons = []
|
| 104 |
+
|
| 105 |
+
for ev in events:
|
| 106 |
+
event_type = ev.get('type', 'macro_general')
|
| 107 |
+
event_date = ev.get('date')
|
| 108 |
+
if not event_date:
|
| 109 |
+
continue
|
| 110 |
+
try:
|
| 111 |
+
ev_date = datetime.strptime(event_date, '%Y-%m-%d').date()
|
| 112 |
+
except:
|
| 113 |
+
continue
|
| 114 |
+
|
| 115 |
+
days_until = (ev_date - today).days
|
| 116 |
+
if days_until < -1: # Already happened yesterday, minimal impact
|
| 117 |
+
continue
|
| 118 |
+
if days_until > 30: # Too far, ignore
|
| 119 |
+
continue
|
| 120 |
+
|
| 121 |
+
mult = self.get_event_multiplier(event_type, max(0, days_until))
|
| 122 |
+
# Severity override
|
| 123 |
+
severity = ev.get('severity', 3)
|
| 124 |
+
severity_adj = 1.0 - (severity - 3) * 0.1 # Adjust ±20%
|
| 125 |
+
mult *= severity_adj
|
| 126 |
+
mult = max(0.0, min(1.0, mult))
|
| 127 |
+
|
| 128 |
+
multipliers.append(mult)
|
| 129 |
+
reasons.append({
|
| 130 |
+
'event': event_type,
|
| 131 |
+
'date': event_date,
|
| 132 |
+
'days_until': days_until,
|
| 133 |
+
'severity': severity,
|
| 134 |
+
'raw_multiplier': mult,
|
| 135 |
+
'severity_adj': severity_adj,
|
| 136 |
+
})
|
| 137 |
+
|
| 138 |
+
if not multipliers:
|
| 139 |
+
return {
|
| 140 |
+
'can_trade': True,
|
| 141 |
+
'adjusted_exposure': base_exposure,
|
| 142 |
+
'reduction': 0.0,
|
| 143 |
+
'reason': 'No significant events in next 30 days',
|
| 144 |
+
'events': [],
|
| 145 |
+
'is_halted': False,
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
# Use minimum multiplier (most restrictive event dominates)
|
| 149 |
+
min_mult = min(multipliers)
|
| 150 |
+
adjusted = base_exposure * min_mult
|
| 151 |
+
reduction = 1 - min_mult
|
| 152 |
+
is_halted = min_mult < 0.05
|
| 153 |
+
|
| 154 |
+
# Find the binding event
|
| 155 |
+
binding = reasons[multipliers.index(min_mult)]
|
| 156 |
+
|
| 157 |
+
return {
|
| 158 |
+
'can_trade': not is_halted,
|
| 159 |
+
'adjusted_exposure': round(adjusted, 4),
|
| 160 |
+
'reduction': round(reduction, 2),
|
| 161 |
+
'reason': (f"{binding['event'].upper()} on {binding['date']} "
|
| 162 |
+
f"({binding['days_until']} days). "
|
| 163 |
+
f"Size reduced by {reduction*100:.0f}%"),
|
| 164 |
+
'binding_event': binding,
|
| 165 |
+
'events': reasons,
|
| 166 |
+
'is_halted': is_halted,
|
| 167 |
+
'all_multipliers': multipliers,
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
def check_ticker(self, ticker: str, base_exposure: float,
|
| 171 |
+
custom_events: Optional[List[Dict]] = None) -> Dict:
|
| 172 |
+
"""Full event risk check for a specific ticker.
|
| 173 |
+
|
| 174 |
+
Uses built-in event calendar + any custom events provided.
|
| 175 |
+
"""
|
| 176 |
+
# Build default events based on ticker
|
| 177 |
+
default_events = []
|
| 178 |
+
|
| 179 |
+
# Check if it's a known stock with known earnings window
|
| 180 |
+
# For demo, we use a simple heuristic: estimate next quarterly window
|
| 181 |
+
# In production, this connects to earnings API
|
| 182 |
+
|
| 183 |
+
# Quarterly earnings: next ~30-90 days from now
|
| 184 |
+
today = datetime.now()
|
| 185 |
+
# Simplified: assume earnings within next quarter
|
| 186 |
+
next_q_end = today + timedelta(days=30)
|
| 187 |
+
default_events.append({
|
| 188 |
+
'type': 'earnings',
|
| 189 |
+
'date': next_q_end.strftime('%Y-%m-%d'),
|
| 190 |
+
'severity': 4,
|
| 191 |
+
})
|
| 192 |
+
|
| 193 |
+
# Fed meetings
|
| 194 |
+
from macro_overlay import FED_MEETINGS
|
| 195 |
+
for m in FED_MEETINGS:
|
| 196 |
+
m_date = datetime.strptime(m, '%Y-%m-%d').date()
|
| 197 |
+
delta = (m_date - today.date()).days
|
| 198 |
+
if 0 <= delta <= 14:
|
| 199 |
+
default_events.append({
|
| 200 |
+
'type': 'fed_meeting',
|
| 201 |
+
'date': m,
|
| 202 |
+
'severity': 5,
|
| 203 |
+
})
|
| 204 |
+
break # Only the next one
|
| 205 |
+
|
| 206 |
+
all_events = default_events + (custom_events or [])
|
| 207 |
+
return self.check_events(all_events, base_exposure)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__ == '__main__':
|
| 211 |
+
guard = EventRiskGuard()
|
| 212 |
+
|
| 213 |
+
# Example: MSFT with earnings in 5 days + Fed meeting in 2 days
|
| 214 |
+
events = [
|
| 215 |
+
{'type': 'earnings', 'date': '2025-05-15', 'severity': 4},
|
| 216 |
+
{'type': 'fed_meeting', 'date': '2025-05-12', 'severity': 5},
|
| 217 |
+
]
|
| 218 |
+
|
| 219 |
+
result = guard.check_events(events, base_exposure=1.0)
|
| 220 |
+
print(f"Can Trade: {result['can_trade']}")
|
| 221 |
+
print(f"Adjusted Exposure: {result['adjusted_exposure']*100:.1f}%")
|
| 222 |
+
print(f"Reduction: {result['reduction']*100:.0f}%")
|
| 223 |
+
print(f"Reason: {result['reason']}")
|
| 224 |
+
if result['is_halted']:
|
| 225 |
+
print("⚠️ TRADING HALTED — Event risk too high")
|