You're absolutely right. The standard Merton model implementation often fails in distressed situations where equity value is very low and the firm is near or in default. In these cases, the asset value should indeed be less than debt, and volatility typically spikes. Let me provide an enhanced implementation that handles these edge cases better:
import numpy as np
from scipy.optimize import minimize, differential_evolution, basinhopping
from scipy.stats import norm
import warnings
def merton_model_solver_distressed(equity_value, equity_vol, debt_face_value, risk_free_rate, time_to_maturity,
method='hybrid', initial_guess=None, verbose=False, max_iterations=1000):
"""
Enhanced Merton model solver that handles distressed/near-default situations.
Parameters:
-----------
equity_value : float
Market value of equity (can be very low)
equity_vol : float
Equity volatility (can be very high in distress)
debt_face_value : float
Face value of debt
risk_free_rate : float
Risk-free interest rate
time_to_maturity : float
Time to debt maturity
method : str
'hybrid', 'global', 'bounded', or 'adaptive'
initial_guess : tuple, optional
Initial guess for (V, σ_V)
verbose : bool
Print diagnostic information
max_iterations : int
Maximum iterations for optimization
Returns:
--------
dict : Contains solution and diagnostics
"""
# Input validation
if equity_value <= 0:
raise ValueError("Equity value must be positive")
if equity_vol <= 0:
raise ValueError("Equity volatility must be positive")
if debt_face_value <= 0:
raise ValueError("Debt face value must be positive")
if time_to_maturity <= 0:
raise ValueError("Time to maturity must be positive")
# Detect distressed situation
leverage_indicator = equity_value / debt_face_value
is_distressed = leverage_indicator < 0.2 or equity_vol > 1.0
if verbose:
print(f"Leverage indicator: {leverage_indicator:.3f}")
print(f"Distressed situation detected: {is_distressed}")
print(f"E/D ratio: {equity_value/debt_face_value:.3f}")
# Adaptive bounds based on distress level
if is_distressed:
# In distress, asset value can be much lower than debt
V_lower = equity_value * 0.1 # Asset value can be very low
V_upper = debt_face_value * 1.5 # But not too high
sigma_V_lower = 0.01
sigma_V_upper = min(equity_vol * 2.0, 5.0) # Cap at 500% volatility
else:
# Normal situation bounds
V_lower = equity_value
V_upper = equity_value + debt_face_value * 2
sigma_V_lower = 0.01
sigma_V_upper = equity_vol * 1.5
# Smart initial guess
if initial_guess is None:
if is_distressed:
# For distressed firms, start with low asset value
asset_guess = equity_value + debt_face_value * np.exp(-risk_free_rate * time_to_maturity) * 0.5
# High volatility guess
vol_guess = equity_vol * 0.8
else:
# Standard guess for healthy firms
asset_guess = equity_value + debt_face_value * np.exp(-risk_free_rate * time_to_maturity)
vol_guess = equity_vol * equity_value / asset_guess
initial_guess = (asset_guess, vol_guess)
V0, sigma_V0 = initial_guess
# Ensure initial guess is within bounds
V0 = np.clip(V0, V_lower, V_upper)
sigma_V0 = np.clip(sigma_V0, sigma_V_lower, sigma_V_upper)
if verbose:
print(f"Initial guess: V = {V0:.2f}, σ_V = {sigma_V0:.4f}")
print(f"Bounds: V ∈ [{V_lower:.2f}, {V_upper:.2f}], σ_V ∈ [{sigma_V_lower:.4f}, {sigma_V_upper:.4f}]")
def merton_equations_stable(vars):
"""Numerically stable version of Merton equations"""
V, sigma_V = vars
# Ensure we're within bounds
if V <= 0 or sigma_V <= 0:
return np.array([1e10, 1e10])
try:
# Use log transformation for better numerical stability
log_V_D = np.log(V / debt_face_value)
sqrt_T = np.sqrt(time_to_maturity)
# Calculate d1 and d2 with overflow protection
d1_numerator = log_V_D + (risk_free_rate + 0.5 * sigma_V**2) * time_to_maturity
d1_denominator = sigma_V * sqrt_T
if d1_denominator < 1e-10:
return np.array([1e10, 1e10])
d1 = d1_numerator / d1_denominator
d2 = d1 - sigma_V * sqrt_T
# Cap d1 and d2 to prevent numerical overflow in norm.cdf
d1 = np.clip(d1, -10, 10)
d2 = np.clip(d2, -10, 10)
N_d1 = norm.cdf(d1)
N_d2 = norm.cdf(d2)
# For very distressed situations, use log-space calculations
if is_distressed and V < debt_face_value * 0.5:
# More stable calculation for extreme cases
log_equity_calc = np.log(V) + np.log(N_d1 + 1e-10)
log_debt_calc = np.log(debt_face_value) - risk_free_rate * time_to_maturity + np.log(N_d2 + 1e-10)
if log_equity_calc > log_debt_calc:
equity_calc = np.exp(log_equity_calc) - np.exp(log_debt_calc)
else:
equity_calc = -np.exp(log_debt_calc) + np.exp(log_equity_calc)
else:
# Standard calculation
equity_calc = V * N_d1 - debt_face_value * np.exp(-risk_free_rate * time_to_maturity) * N_d2
# Equation 1: Equity value equation
eq1 = equity_calc - equity_value
# Equation 2: Volatility equation
# Use relative error for better scaling
eq2 = (sigma_V * V * N_d1 - equity_vol * equity_value) / equity_value
return np.array([eq1, eq2])
except (ValueError, OverflowError, ZeroDivisionError) as e:
if verbose:
print(f"Numerical error in equations: {e}")
return np.array([1e10, 1e10])
def objective_function_weighted(vars):
"""Weighted objective function that handles distressed cases better"""
eqs = merton_equations_stable(vars)
# Adaptive weighting based on distress level
if is_distressed:
# In distress, equity equation is more important
weights = np.array([1.0, 0.1])
else:
# Normal weighting
weights = np.array([1.0, 1.0])
# Use relative error for better scaling
rel_error_1 = eqs[0] / (equity_value + 1e-6)
rel_error_2 = eqs[1]
return weights[0] * rel_error_1**2 + weights[1] * rel_error_2**2
# Solution strategies
best_result = None
best_error = float('inf')
if method == 'hybrid' or method == 'adaptive':
# Strategy 1: Bounded optimization with multiple algorithms
bounds = [(V_lower, V_upper), (sigma_V_lower, sigma_V_upper)]
# Try L-BFGS-B first
try:
result = minimize(objective_function_weighted, [V0, sigma_V0],
method='L-BFGS-B', bounds=bounds,
options={'maxiter': max_iterations})
if result.success and result.fun < best_error:
V_sol, sigma_V_sol = result.x
best_error = result.fun
best_result = {
'asset_value': V_sol,
'asset_vol': sigma_V_sol,
'success': True,
'message': f'L-BFGS-B success, error = {result.fun:.2e}',
'method_used': 'L-BFGS-B'
}
except Exception as e:
if verbose:
print(f"L-BFGS-B failed: {e}")
# Try Trust-Region for constrained optimization
if best_error > 1e-6:
try:
from scipy.optimize import NonlinearConstraint
def constraint_func(vars):
return vars # Just ensure positive values
nlc = NonlinearConstraint(constraint_func, [V_lower, sigma_V_lower], [V_upper, sigma_V_upper])
result = minimize(objective_function_weighted, [V0, sigma_V0],
method='trust-constr', constraints=[nlc],
options={'maxiter': max_iterations})
if result.success and result.fun < best_error:
V_sol, sigma_V_sol = result.x
best_error = result.fun
best_result = {
'asset_value': V_sol,
'asset_vol': sigma_V_sol,
'success': True,
'message': f'Trust-constr success, error = {result.fun:.2e}',
'method_used': 'trust-constr'
}
except Exception as e:
if verbose:
print(f"Trust-constr failed: {e}")
if method == 'global' or (method in ['hybrid', 'adaptive'] and best_error > 1e-4):
# Strategy 2: Global optimization for difficult cases
try:
if verbose:
print("Trying global optimization...")
result = differential_evolution(objective_function_weighted, bounds,
maxiter=max_iterations // 10,
popsize=15,
seed=42)
if result.success and result.fun < best_error:
V_sol, sigma_V_sol = result.x
best_error = result.fun
best_result = {
'asset_value': V_sol,
'asset_vol': sigma_V_sol,
'success': True,
'message': f'Differential evolution success, error = {result.fun:.2e}',
'method_used': 'differential_evolution'
}
except Exception as e:
if verbose:
print(f"Differential evolution failed: {e}")
if method == 'bounded' or (best_error > 1e-3 and is_distressed):
# Strategy 3: Basin hopping for very difficult cases
try:
if verbose:
print("Trying basin hopping...")
minimizer_kwargs = {"method": "L-BFGS-B", "bounds": bounds}
result = basinhopping(objective_function_weighted, [V0, sigma_V0],
minimizer_kwargs=minimizer_kwargs,
niter=50)
if result.fun < best_error:
V_sol, sigma_V_sol = result.x
best_error = result.fun
best_result = {
'asset_value': V_sol,
'asset_vol': sigma_V_sol,
'success': True,
'message': f'Basin hopping success, error = {result.fun:.2e}',
'method_used': 'basinhopping'
}
except Exception as e:
if verbose:
print(f"Basin hopping failed: {e}")
# If still no good solution and we're in distress, try grid search
if best_error > 0.01 and is_distressed:
if verbose:
print("Trying grid search for distressed case...")
# Grid search over reasonable ranges
V_grid = np.linspace(V_lower, min(debt_face_value, V_upper), 20)
sigma_V_grid = np.linspace(sigma_V_lower, sigma_V_upper, 20)
for V_try in V_grid:
for sigma_V_try in sigma_V_grid:
error = objective_function_weighted([V_try, sigma_V_try])
if error < best_error:
best_error = error
best_result = {
'asset_value': V_try,
'asset_vol': sigma_V_try,
'success': True,
'message': f'Grid search success, error = {error:.2e}',
'method_used': 'grid_search'
}
# Final validation
if best_result is None:
return {
'asset_value': np.nan,
'asset_vol': np.nan,
'success': False,
'message': 'All optimization methods failed',
'method_used': 'None',
'leverage_ratio': np.nan,
'default_probability': np.nan
}
# Calculate additional metrics
V_final = best_result['asset_value']
sigma_V_final = best_result['asset_vol']
# Calculate default probability
try:
d2_final = (np.log(V_final / debt_face_value) + (risk_free_rate - 0.5 * sigma_V_final**2) * time_to_maturity) / (sigma_V_final * np.sqrt(time_to_maturity))
default_prob = norm.cdf(-d2_final)
except:
default_prob = np.nan
best_result['leverage_ratio'] = debt_face_value / V_final if V_final > 0 else np.nan
best_result['default_probability'] = default_prob
best_result['is_distressed'] = is_distressed
if verbose:
print(f"\nFinal solution:")
print(f"Asset value: {V_final:.2f}")
print(f"Asset volatility: {sigma_V_final:.2%}")
print(f"Leverage ratio: {best_result['leverage_ratio']:.2f}")
print(f"Default probability: {default_prob:.2%}")
return best_result
# Test function for distressed scenarios
def test_distressed_scenarios():
"""Test the solver with various distressed scenarios"""
print("Testing Distressed Scenarios")
print("=" * 60)
# Test cases
test_cases = [
{
'name': 'Highly Distressed',
'equity_value': 10.0,
'equity_vol': 2.0, # 200% volatility
'debt_face_value': 1000.0,
'risk