import logging
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Enum
from datetime import datetime
import pandas as pd
import numpy as np
# Configure Logging
logging.basicConfig(level='INFO', format='%(asctime)s - %(levelname)s - %(message)s')
# --- 1. Data Structures & Enums ---
class AssetClass(Enum):
EQUITY_INDEX_VOL = "EQ_VOL"
FX_VOL = "FX_VOL"
RATES_VOL = "RATES_VOL"
COMMODITY_VOL = "COMM_VOL"
class OrderStatus(Enum):
PENDING = "PENDING"
REJECTED = "REJECTED"
EXECUTED = "EXECUTED"
SETTLED = "SETTLED"
@dataclass
class Instrument:
ticker: str
asset_class: AssetClass
vega_per_contract: float # Sensitivity to 1% vol change
currency: str
is_liquid: bool = True
@dataclass
class Position:
instrument: Instrument
quantity: float
entry_price: float
current_price: float
timestamp: datetime
@dataclass
class Mandate:
"""
The Investment Mandate defining constraints for the Volatility Basket.
"""
basket_name: str
max_gross_vega: float # Maximum total absolute vega exposure
max_net_vega: float # Maximum directional vol bias
max_concentration_pct: float # Max % of basket in single asset class
allowed_asset_classes: List[AssetClass]
max_single_trade_notional: float
prohibited_tickers: List[str] # Blacklist (e.g., illiquid tenors)
authorized_traders: List[str]
# --- 2. Governance Engine ---
class GovernanceEngine:
def __init__(self, mandate: Mandate):
self.mandate = mandate
self.audit_log = []
def _log_event(self, event_type: str, details: str):
self.audit_log.append({
"timestamp": datetime.now(),
"event": event_type,
"details": details
})
logging.info(f"GOV EVENT: {event_type} | {details}")
def validate_proposed_trade(self, trade_proposal: dict, current_positions: List[Position]) -> bool:
"""
Pre-trade compliance check.
"""
ticker = trade_proposal['ticker']
quantity = trade_proposal['quantity']
trader = trade_proposal['trader']
instrument = trade_proposal['instrument']
# 1. Authorization Check
if trader not in self.mandate.authorized_traders:
self._log_event("COMPLIANCE_REJECT", f"Trader {trader} not authorized.")
return False
# 2. Blacklist Check
if ticker in self.mandate.prohibited_tickers:
self._log_event("COMPLIANCE_REJECT", f"Ticker {ticker} is blacklisted.")
return False
# 3. Asset Class Check
if instrument.asset_class not in self.mandate.allowed_asset_classes:
self._log_event("COMPLIANCE_REJECT", f"Asset class {instrument.asset_class} not allowed.")
return False
# 4. Exposure Simulation (What happens if we execute?)
projected_gross_vega = sum(abs(p.quantity * p.instrument.vega_per_contract) for p in current_positions)
projected_net_vega = sum(p.quantity * p.instrument.vega_per_contract for p in current_positions)
# Add proposed trade
delta_vega = quantity * instrument.vega_per_contract
projected_net_vega += delta_vega
projected_gross_vega += abs(delta_vega)
if abs(projected_net_vega) > self.mandate.max_net_vega:
self._log_event("RISK_REJECT", f"Net Vega breach. Projected: {projected_net_vega}")
return False
if projected_gross_vega > self.mandate.max_gross_vega:
self._log_event("RISK_REJECT", f"Gross Vega breach. Projected: {projected_gross_vega}")
return False
self._log_event("TRADE_APPROVED", f"Trade {ticker} Qty:{quantity} passed governance.")
return True
def check_intraday_breach(self, current_positions: List[Position]) -> Optional[str]:
"""
Post-trade / Real-time monitoring for drift.
"""
# Calculate Concentration
class_exposure = {ac: 0.0 for ac in AssetClass}
total_vega = 0.0
for p in current_positions:
val = abs(p.quantity * p.instrument.vega_per_contract)
class_exposure[p.instrument.asset_class] += val
total_vega += val
if total_vega == 0: return None
for ac, val in class_exposure.items():
pct = val / total_vega
if pct > self.mandate.max_concentration_pct:
msg = f"CONCENTRATION BREACH: {ac.value} is {pct:.2%} of basket (Max: {self.mandate.max_concentration_pct:.2%})"
self._log_event("MANDATE_BREACH", msg)
return msg
return None
# --- 3. Execution Oversight ---
@dataclass
class ExecutionRecord:
order_id: str
expected_fill: float
actual_fill: float
timestamp: datetime
slippage_bps: float
class ExecutionMonitor:
def __init__(self, max_slippage_bps: float = 50.0):
self.max_slippage_bps = max_slippage_bps
self.execution_history = []
def record_execution(self, order_id: str, expected_price: float, actual_price: float, instrument: Instrument):
# Calculate Slippage (simplified logic)
# For vol, slippage is often measured in vol points or bps of notional
diff = actual_price - expected_price
# Normalize by price to get % move
slippage_bps = (diff / expected_price) * 10000 if expected_price != 0 else 0
record = ExecutionRecord(order_id, expected_price, actual_price, datetime.now(), slippage_bps)
self.execution_history.append(record)
if abs(slippage_bps) > self.max_slippage_bps:
logging.warning(f"EXECUTION ALERT: High Slippage on {order_id} | {slippage_bps:.2f} bps")
# Trigger alert to compliance/trading desk
return "ALERT_HIGH_SLIPPAGE"
return "OK"
# --- 4. Attribution Module ---
class AttributionEngine:
"""
Decomposes returns of the Vol Basket into risk factors.
"""
def calculate_attribution(self, positions: List[Position], market_data_snapshot: Dict[str, dict]) -> dict:
"""
Calculates PnL attribution.
Market Data needs: 'current_vol', 'previous_vol', 'carry' (theta)
"""
attribution = {
"Delta_Vol_PnL": 0.0, # PnL from change in volatility level
"Curve_PnL": 0.0, # PnL from term structure shifts (Variance swap roll-down)
"Carry_Theta": 0.0, # Decay of volatility premium
"Gamma_PnL": 0.0, # PnL from convexity (spot moves)
"Total_PnL": 0.0
}
for p in positions:
ticker = p.instrument.ticker
if ticker not in market_data_snapshot:
continue
mkt = market_data_snapshot[ticker]
vega = p.instrument.vega_per_contract
qty = p.quantity
# 1. Delta Vol (Change in Implied Vol)
vol_change = mkt['current_vol'] - mkt['previous_vol']
delta_vol_pnl = qty * vega * vol_change
# 2. Carry (Simplified as daily decay)
carry_pnl = qty * mkt.get('daily_theta', 0)
# Total logic
attribution["Delta_Vol_PnL"] += delta_vol_pnl
attribution["Carry_Theta"] += carry_pnl
# Estimating Total PnL based on price change in position data
realized_pnl = (p.current_price - p.entry_price) * qty
attribution["Total_PnL"] += realized_pnl
return attribution
# --- 5. Integration & Usage Simulation ---
def main():
# A. Setup Mandate
mandate = Mandate(
basket_name="Global_Macro_Vol_Overlay",
max_gross_vega=1_000_000, # $1M Vega limit
max_net_vega=500_000, # Can't be short more than 500k net
max_concentration_pct=0.40, # Max 40% in any one asset class
allowed_asset_classes=[AssetClass.EQUITY_INDEX_VOL, AssetClass.FX_VOL],
max_single_trade_notional=5_000_000,
prohibited_tickers=["VIX_WK7"], # Prohibit illiquid weekly expiries
authorized_traders=["alpha_trader_01", "hedger_bot"]
)
# B. Initialize Modules
gov_engine = GovernanceEngine(mandate)
exec_monitor = ExecutionMonitor(max_slippage_bps=20.0)
attr_engine = AttributionEngine()
# C. Define Universe & Current Basket
vix_future = Instrument("VIX_FUT1", AssetClass.EQUITY_INDEX_VOL, vega_per_contract=1000, currency="USD")
eurusd_vol = Instrument("EURUSD_1M", AssetClass.FX_VOL, vega_per_contract=500, currency="USD")
illiquid_asset = Instrument("VIX_WK7", AssetClass.EQUITY_INDEX_VOL, vega_per_contract=2000, currency="USD")
# Current portfolio state
current_basket = [
Position(vix_future, 50, 20.0, 21.0, datetime.now()), # Long 50 VIX Futures
]
print("--- 1. GOVERNANCE TEST: Valid Trade ---")
valid_trade = {
"ticker": "EURUSD_1M",
"quantity": 100, # Adding 100 FX Vol contracts
"trader": "alpha_trader_01",
"instrument": eurusd_vol
}
if gov_engine.validate_proposed_trade(valid_trade, current_basket):
# Simulate Execution
exec_status = exec_monitor.record_execution("ORD_001", expected_price=8.50, actual_price=8.51, instrument=eurusd_vol)
current_basket.append(Position(eurusd_vol, 100, 8.51, 8.55, datetime.now()))
print("\n--- 2. GOVERNANCE TEST: Unauthorized Trader ---")
bad_auth_trade = {
"ticker": "EURUSD_1M",
"quantity": 10,
"trader": "rogue_trader",
"instrument": eurusd_vol
}
gov_engine.validate_proposed_trade(bad_auth_trade, current_basket)
print("\n--- 3. GOVERNANCE TEST: Blacklisted Instrument ---")
blacklist_trade = {
"ticker": "VIX_WK7",
"quantity": 10,
"trader": "alpha_trader_01",
"instrument": illiquid_asset
}
gov_engine.validate_proposed_trade(blacklist_trade, current_basket)
print("\n--- 4. RISK ATTRIBUTION ---")
# Mock Market Data Update
# VIX moved from 20 to 21 (prev_vol vs current_vol in points, mapped to % for Vega calc)
# Simplification: Vega PnL = Qty * Vega * (VolEnd - VolStart)
market_data = {
"VIX_FUT1": {"current_vol": 21.0, "previous_vol": 20.0, "daily_theta": -50},
"EURUSD_1M": {"current_vol": 8.55, "previous_vol": 8.50, "daily_theta": -5}
}
performance = attr_engine.calculate_attribution(current_basket, market_data)
print(f"Total PnL: ${performance['Total_PnL']:,.2f}")
print(f"Vol Delta PnL: ${performance['Delta_Vol_PnL']:,.2f}")
print(f"Carry/Theta: ${performance['Carry_Theta']:,.2f}")
print("\n--- 5. CONCENTRATION BREACH CHECK ---")
# VIX Position is 50 * 1000 = 50,000 Vega
# FX Position is 100 * 500 = 50,000 Vega
# Total Gross = 100,000. 50% VIX.
# Breach is 40%. This should trigger.
gov_engine.check_intraday_breach(current_basket)
if __name__ == "__main__":
main()