import numpy as np
import pandas as pd
from scipy.optimize import linprog, OptimizeResult
from typing import List, Dict, Tuple
import itertools
# ---------------------------------------------------------
# 1. CONFIGURATION & DATA MODELS
# ---------------------------------------------------------
class Instrument:
def __init__(self, name: str, ccy: str, tenor: int, typ: str,
base_spread_bps: float, regulatory_weight: float,
max_issuance_usd: float):
self.name = name
self.ccy = ccy
self.tenor = tenor
self.typ = typ # 'Senior' or 'Subordinated'
self.base_spread_bps = base_spread_bps
self.regulatory_weight = regulatory_weight # 1.0 for TLAC eligible, 0.0 for standard senior
self.max_issuance_usd = max_issuance_usd
def __repr__(self):
return f"{self.name} ({self.ccy}-{self.tenor}Y)"
class StressScenario:
def __init__(self, name: str, spread_shock_map: Dict[str, float], fx_shock_map: Dict[str, float]):
self.name = name
self.spread_shock_map = spread_shock_map # Instrument Name -> Additive bps
self.fx_shock_map = fx_shock_map # CCY -> Multiplicative factor vs USD
# ---------------------------------------------------------
# 2. OPTIMIZATION ENGINE
# ---------------------------------------------------------
class TLACOptimizer:
def __init__(self, instruments: List[Instrument], scenarios: List[StressScenario],
target_tlac_usd: float, min_subordination_ratio: float = 0.25):
self.instruments = instruments
self.scenarios = scenarios
self.target_tlac_usd = target_tlac_usd
self.min_subordination_ratio = min_subordination_ratio
self.results = []
def optimize_for_scenario(self, scenario: StressScenario) -> OptimizeResult:
"""
Minimize Cost function: Sum(Amount_i * Spread_i)
Subject to:
1. Sum(Amount_i * RegWeight_i) >= Target_TLAC
2. Sum(Amount_i * SubordinationWeight_i) >= Target_TLAC * SubRatio
3. Amount_i <= Max_Issuance_i
4. Amount_i >= 0
"""
n = len(self.instruments)
# --- Objective Function (Cost Vectors) ---
# Cost = Amount * (Base_Spread + Shock)
# We convert everything to USD equivalent for cost comparison,
# though usually issuance is localized, we assume a USD-centric HQ view.
costs = []
for inst in self.instruments:
shock = scenario.spread_shock_map.get(inst.name, 0)
total_spread = inst.base_spread_bps + shock
# FX Translation logic (simplified):
# If issuing in EUR, cost is EUR spread. If we want USD comparability,
# we might add cross-currency basis swap costs, but for simplicity
# we treat the spread as the raw cost of capital.
costs.append(total_spread)
c = np.array(costs)
# --- Inequality Constraints (A_ub * x <= b_ub) ---
# Constraint 1: Max Issuance per line
# A_ub is identity matrix, b_ub is max limits
A_ub_max = np.identity(n)
b_ub_max = np.array([inst.max_issuance_usd for inst in self.instruments])
# --- Equality/Inequality Constraints for Regulatory Buffers ---
# Constraint 2: Total TLAC Requirement (Sum(weights * amount) >= Target)
# Formatted as: -Sum(weights * amount) <= -Target
reg_weights = np.array([inst.regulatory_weight for inst in self.instruments])
A_ub_tlac = -reg_weights.reshape(1, -1)
b_ub_tlac = np.array([-self.target_tlac_usd])
# Constraint 3: Subordination Requirement (Basel III / MREL)
# Sub debt must be at least X% of total TLAC
# Sum(SubWeight * amount) >= Target * Ratio
sub_weights = np.array([1.0 if inst.typ == 'Subordinated' else 0.0 for inst in self.instruments])
A_ub_sub = -sub_weights.reshape(1, -1)
b_ub_sub = np.array([-self.target_tlac_usd * self.min_subordination_ratio])
# Combine all Upper Bound constraints
A_ub = np.vstack([A_ub_max, A_ub_tlac, A_ub_sub])
b_ub = np.concatenate([b_ub_max, b_ub_tlac, b_ub_sub])
# --- Bounds ---
bounds = [(0, None) for _ in range(n)]
# --- Solve Linear Program ---
# method='highs' is efficient for this scale
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='highs')
return res
def run_all_scenarios(self):
print(f"Running Optimizer for {len(self.scenarios)} Permutations...\n")
summary_data = []
for scenario in self.scenarios:
res = self.optimize_for_scenario(scenario)
if res.success:
allocation = res.x
total_cost = res.fun
# Metrics for dashboard
total_issuance = np.sum(allocation)
sub_issuance = np.sum([amt for amt, inst in zip(allocation, self.instruments) if inst.typ == 'Subordinated'])
# Currency mix
ccy_mix = {}
for amt, inst in zip(allocation, self.instruments):
ccy_mix[inst.ccy] = ccy_mix.get(inst.ccy, 0) + amt
summary_data.append({
'Scenario': scenario.name,
'Status': 'Optimal',
'Est. Cost (bps)': round(total_cost, 2),
'Total Issuance ($B)': round(total_issuance / 1000, 2), # Assuming inputs in millions
'Sub Ratio (%)': round((sub_issuance / total_issuance) * 100, 1) if total_issuance > 0 else 0,
**{f"Issue_{inst.name}": round(amt, 1) for amt, inst in zip(allocation, self.instruments)}
})
else:
summary_data.append({
'Scenario': scenario.name,
'Status': 'Failed',
'Est. Cost (bps': np.nan
})
self.results = pd.DataFrame(summary_data)
return self.results
# ---------------------------------------------------------
# 3. SIMULATION SETUP (The "Bank")
# ---------------------------------------------------------
# Define the Universe of Bonds
# Args: Name, CCY, Tenor, Type, Spread(bps), TLAC_Weight, Max_Issue($M)
instruments = [
# USD Senior Non-Preferred (SNP) - Cheap, eligible for TLAC
Instrument("USD-SNP-5Y", "USD", 5, "Senior", 120, 1.0, 5000),
Instrument("USD-SNP-10Y", "USD", 10, "Senior", 140, 1.0, 4000),
# EUR Senior Non-Preferred - Diversifies investor base
Instrument("EUR-SNP-5Y", "EUR", 5, "Senior", 130, 1.0, 3000),
# Subordinated (Tier 2 / Restricted Tier 1) - Expensive, high regulatory value
Instrument("USD-T2-10Y", "USD", 10, "Subordinated", 250, 1.0, 2000),
Instrument("EUR-T2-7Y", "EUR", 7, "Subordinated", 270, 1.0, 1500),
# GBP Senior - Niche market
Instrument("GBP-SNP-3Y", "GBP", 3, "Senior", 150, 1.0, 1000)
]
# Define Stress Permutations
scenarios = [
StressScenario("Base_Case", {}, {}),
# Market Stress: USD Spreads widen, Investors prefer short duration
StressScenario("USD_Credit_Shock",
{"USD-SNP-5Y": 50, "USD-SNP-10Y": 80, "USD-T2-10Y": 120},
{}),
# EU Stress: EUR investors retreat (Capacity constraint implied by higher spread)
StressScenario("EUR_Demand_Crunch",
{"EUR-SNP-5Y": 100, "EUR-T2-7Y": 150},
{}),
# FX Shock: EUR depreciates (Impacts translation of capital, though simplified here)
StressScenario("Cross_Currency_Vol",
{"USD-SNP-5Y": 20, "EUR-SNP-5Y": 20},
{"EUR": 1.10}) # EUR weakens
]
# Target: Need $15 Billion TLAC capacity
optimizer = TLACOptimizer(instruments, scenarios, target_tlac_usd=15000, min_subordination_ratio=0.20)
# ---------------------------------------------------------
# 4. EXECUTION & VISUALIZATION
# ---------------------------------------------------------
df_results = optimizer.run_all_scenarios()
# Display Logic
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 200)
# Calculate an 'Efficiency Score': Cost per unit of TLAC (normalized)
df_results['Cost_per_$B_TLAC'] = df_results['Est. Cost (bps)'] / (df_results['Total Issuance ($B)'])
print(df_results[['Scenario', 'Est. Cost (bps)', 'Total Issuance ($B)', 'Sub Ratio (%)', 'Cost_per_$B_TLAC']])