Altman / plot_generator.py
thisisbbln's picture
Add plot_generator.py
66fe6a5 verified
Raw History Blame
20 kB
"""
plot_generator.py
High-Impact Publication-Quality Matplotlib Visualizations for:
1. Altman Z''-Score vs Accounting Surplus Divergence (Delek & Africa Israel)
2. BSM Executive Option Valuation, Protection Asymmetry & Vega Expansion
3. Multi-Parameter Sensitivity Heatmaps (Moneyness vs Volatility Shocks)
Output Files:
- /home/dcor/omerazoulay/nini/altman_vs_accounting_surplus.png
- /home/dcor/omerazoulay/nini/option_value_vega_gain.png
- /home/dcor/omerazoulay/nini/sensitivity_heatmap.png
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
# Import local analysis engines
from data_collector import get_company_data
from altman_model import calculate_altman_z_double_prime, analyze_company_solvency
from bsm_engine import black_scholes_call, simulate_dividend_impact, run_sensitivity_grid
# Configure global matplotlib aesthetics for academic publication quality
plt.rcParams.update({
'font.sans-serif': 'DejaVu Sans',
'font.family': 'sans-serif',
'font.size': 11,
'axes.titlesize': 13,
'axes.titleweight': 'bold',
'axes.labelsize': 11,
'axes.labelweight': 'bold',
'xtick.labelsize': 10,
'ytick.labelsize': 10,
'legend.fontsize': 10,
'figure.titlesize': 15,
'figure.titleweight': 'bold',
'figure.autolayout': False,
'savefig.dpi': 300,
'savefig.bbox': 'tight',
'axes.edgecolor': '#333333',
'axes.linewidth': 1.0,
'grid.color': '#E0E0E0',
'grid.linestyle': '--',
'grid.alpha': 0.7
})
OUTPUT_DIR = "/home/dcor/omerazoulay/nini"
def generate_altman_vs_accounting_surplus():
"""
Figure 1: altman_vs_accounting_surplus.png
Compares the apparent legal accounting surplus against the true economic solvency
(Altman Z''-Score) for Delek Real Estate and Africa Israel Investments.
Demonstrates the structural failure of the statutory profit test.
"""
dataset = get_company_data()
events = [
{"label": "Delek Real Estate\n2007 (Apr 10)", "company": "Delek_Group", "idx": 0, "surplus": 850.0, "div": 220.0},
{"label": "Delek Real Estate\n2008 (Apr 15)", "company": "Delek_Group", "idx": 1, "surplus": 420.0, "div": 180.0},
{"label": "Africa Israel\n2007 (Jun 30)", "company": "Africa_Israel", "idx": 0, "surplus": 2100.0, "div": 580.0},
{"label": "Africa Israel\n2008 (Mar 31)", "company": "Africa_Israel", "idx": 1, "surplus": 980.0, "div": 350.0}
]
z_scores = []
surpluses = []
dividends = []
labels = []
for ev in events:
div_data = dataset[ev["company"]]["dividends"][ev["idx"]]
z_res = calculate_altman_z_double_prime(
wc=div_data["working_capital_nis_m"],
total_assets=div_data["total_assets_nis_m"],
retained_earnings=div_data["retained_earnings_nis_m"],
ebit=div_data["ebit_nis_m"],
bv_equity=div_data["bv_equity_nis_m"],
total_liabilities=div_data["total_liabilities_nis_m"]
)
z_scores.append(z_res["Z_Score"])
surpluses.append(ev["surplus"])
dividends.append(ev["div"])
labels.append(ev["label"])
x = np.arange(len(labels))
width = 0.35
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6.2), gridspec_kw={'width_ratios': [1.1, 1.2]})
fig.suptitle("Empirical Solvency Divergence: Accounting Surplus vs. Altman Z''-Score\nDelek Real Estate & Africa Israel Distributions (2007โ€“2008)", fontsize=14, y=0.98)
# --- Subplot 1: Accounting Surplus & Dividend Distributed (NIS M) ---
bars1 = ax1.bar(x - width/2, surpluses, width, label='Accounting Surplus (ืžื‘ื—ืŸ ื”ืจื•ื•ื—)', color='#1F77B4', edgecolor='#0D47A1', alpha=0.9)
bars2 = ax1.bar(x + width/2, dividends, width, label='Dividend Paid (ืกื›ื•ื ื”ื—ืœื•ืงื”)', color='#FF7F0E', edgecolor='#E65100', alpha=0.9)
ax1.set_title("A. Accounting Profit Test (Passed)\nStatutory Distributable Surplus & Dividend", fontsize=11, pad=10)
ax1.set_ylabel("NIS Millions (ืžื™ืœื™ื•ื ื™ ืฉ\"ื—)")
ax1.set_xticks(x)
ax1.set_xticklabels(labels, fontsize=9.5)
ax1.legend(loc='upper right', frameon=True, facecolor='white', framealpha=0.9)
ax1.grid(axis='y', linestyle='--', alpha=0.6)
ax1.set_ylim(0, 2400)
# Annotate bar values
for bar in bars1:
h = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., h + 30, f"{int(h):,}M", ha='center', va='bottom', fontsize=8.5, fontweight='bold', color='#0D47A1')
for bar in bars2:
h = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., h + 30, f"{int(h):,}M", ha='center', va='bottom', fontsize=8.5, fontweight='bold', color='#E65100')
# Status badges
for i in range(len(x)):
ax1.text(x[i], 120, "PASSED\nProfit Test", ha='center', va='center', fontsize=8, fontweight='bold',
bbox=dict(boxstyle="round,pad=0.3", fc="#E8F5E9", ec="#2E7D32", lw=1.2))
# --- Subplot 2: Altman Z''-Score Economic Solvency & Distress Zones ---
# Shaded Zones
ax2.axhspan(-1.5, 1.1, color='#FFCDD2', alpha=0.5, label='Distress Zone (Z\'\' < 1.1) [ื—ื“ืœื•ืช ืคื™ืจืขื•ืŸ]')
ax2.axhspan(1.1, 2.6, color='#FFF9C4', alpha=0.5, label='Grey Zone (1.1 โ‰ค Z\'\' โ‰ค 2.6) [ืื–ื•ืจ ืืคื•ืจ]')
ax2.axhspan(2.6, 4.0, color='#C8E6C9', alpha=0.5, label='Safe Zone (Z\'\' > 2.6) [ืื–ื•ืจ ื‘ื˜ื•ื—]')
# Threshold reference lines
ax2.axhline(1.1, color='#C62828', linestyle='--', linewidth=1.5)
ax2.axhline(2.6, color='#2E7D32', linestyle='--', linewidth=1.5)
# Plot Altman values as connected points with bars/markers
colors = ['#D32F2F' if z < 1.1 else '#FBC02D' for z in z_scores]
bar_z = ax2.bar(x, z_scores, width=0.45, color=colors, edgecolor='#555555', linewidth=1.2, zorder=3)
ax2.plot(x, z_scores, color='#212121', marker='o', markersize=8, linewidth=2, zorder=4)
ax2.set_title("B. Economic Solvency Test (Failed)\nAltman Z''-Score for Emerging / Non-Manufacturing", fontsize=11, pad=10)
ax2.set_ylabel("Altman Z''-Score")
ax2.set_xticks(x)
ax2.set_xticklabels(labels, fontsize=9.5)
ax2.set_ylim(-1.2, 3.5)
ax2.grid(True, linestyle='--', alpha=0.6)
# Value annotations on Altman plot
for i, z in enumerate(z_scores):
va = 'bottom' if z >= 0 else 'top'
y_offset = 0.12 if z >= 0 else -0.12
ax2.text(x[i], z + y_offset, f"Z'' = {z:.3f}\n(CRITICAL DISTRESS)", ha='center', va=va,
fontsize=8.5, fontweight='bold', color='#B71C1C',
bbox=dict(boxstyle="round,pad=0.2", fc="#FFEBEE", ec="#D32F2F", lw=1))
ax2.text(3.4, 1.15, "Distress Threshold (1.1)", fontsize=8, color='#C62828', fontweight='bold', ha='right')
ax2.text(3.4, 2.65, "Safe Threshold (2.6)", fontsize=8, color='#2E7D32', fontweight='bold', ha='right')
ax2.legend(loc='upper right', frameon=True, facecolor='white', framealpha=0.9, fontsize=8.5)
plt.tight_layout(rect=[0, 0.03, 1, 0.94])
output_path = os.path.join(OUTPUT_DIR, "altman_vs_accounting_surplus.png")
plt.savefig(output_path, dpi=300)
plt.close()
print(f" Successfully saved: {output_path}")
def generate_option_value_vega_gain():
"""
Figure 2: option_value_vega_gain.png
Visualizes Black-Scholes-Merton option pricing dynamics under dividend protection
and leverage-induced volatility expansion. Highlights the agency risk-shifting payoff.
"""
dataset = get_company_data()
# Extract case studies
delek_d0 = dataset["Delek_Group"]["dividends"][0]
delek_opt = dataset["Delek_Group"]["executive_options"][0]
afr_d0 = dataset["Africa_Israel"]["dividends"][0]
afr_opt = dataset["Africa_Israel"]["executive_options"][0]
# Simulation 1: Delek Real Estate 2007 Event
sim_delek = simulate_dividend_impact(
S_0=delek_d0["stock_price_pre"],
K_0=delek_opt["strike_k0"],
T=delek_opt["maturity_years"],
r=delek_d0["risk_free_rate"],
sigma_0=delek_d0["pre_div_volatility"],
dividend=delek_d0["dividend_per_share"],
sigma_increase=delek_d0["post_div_volatility"] - delek_d0["pre_div_volatility"]
)
# Simulation 2: Africa Israel 2007 Event
sim_afr = simulate_dividend_impact(
S_0=afr_d0["stock_price_pre"],
K_0=afr_opt["strike_k0"],
T=afr_opt["maturity_years"],
r=afr_d0["risk_free_rate"],
sigma_0=afr_d0["pre_div_volatility"],
dividend=afr_d0["dividend_per_share"],
sigma_increase=afr_d0["post_div_volatility"] - afr_d0["pre_div_volatility"]
)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6.8), gridspec_kw={'width_ratios': [1.1, 1.2]})
fig.suptitle("Executive Compensation Asymmetry: Dividend Protection & Vega Expansion\nBSM Option Value Shift under Leverage-Induced Volatility", fontsize=14, y=0.98)
# --- Subplot 1: 4-Stage State Comparison per Share (Delek Real Estate & Africa Israel) ---
stages = [
"1. Pre-Dividend\nBaseline (T0)",
"2. Post-Dividend\nUnprotected\n(S - D, K)",
"3. Post-Dividend\nProtected\n(S - D, K - D)",
"4. Protected +\nVol Expansion\n(Vega Gain)"
]
delek_vals = [
sim_delek["Value_Pre_Div"],
sim_delek["Value_Unprotected"],
sim_delek["Value_Protected_Same_Vol"],
sim_delek["Value_Protected_Higher_Vol"]
]
afr_vals_norm = [
(v / sim_afr["Value_Pre_Div"]) * 100 for v in [
sim_afr["Value_Pre_Div"],
sim_afr["Value_Unprotected"],
sim_afr["Value_Protected_Same_Vol"],
sim_afr["Value_Protected_Higher_Vol"]
]
]
delek_vals_norm = [(v / sim_delek["Value_Pre_Div"]) * 100 for v in delek_vals]
x = np.arange(len(stages))
width = 0.35
b1 = ax1.bar(x - width/2, delek_vals_norm, width, label='Delek Real Estate (Indexed 100)', color='#1E88E5', edgecolor='#1565C0', alpha=0.9)
b2 = ax1.bar(x + width/2, afr_vals_norm, width, label='Africa Israel (Indexed 100)', color='#FB8C00', edgecolor='#E65100', alpha=0.9)
ax1.axhline(100, color='#555555', linestyle=':', linewidth=1.2)
ax1.set_title("A. Option Value Evolution Across Distribution States\n(Indexed to Pre-Dividend Value = 100)", fontsize=11, pad=10)
ax1.set_ylabel("Option Value Index (% of Baseline T0)")
ax1.set_xticks(x)
ax1.set_xticklabels(stages, fontsize=8.5)
ax1.set_ylim(60, 135)
ax1.grid(axis='y', linestyle='--', alpha=0.6)
ax1.legend(loc='upper left', frameon=True, facecolor='white', framealpha=0.9)
# Annotate percent changes
for bar, val, abs_v in zip(b1, delek_vals_norm, delek_vals):
ax1.text(bar.get_x() + bar.get_width()/2., val + 1.5, f"{val:.1f}%\n({abs_v:.2f}โ‚ช)", ha='center', va='bottom', fontsize=7.8, fontweight='bold', color='#0D47A1')
for bar, val, abs_v in zip(b2, afr_vals_norm, [sim_afr["Value_Pre_Div"], sim_afr["Value_Unprotected"], sim_afr["Value_Protected_Same_Vol"], sim_afr["Value_Protected_Higher_Vol"]]):
ax1.text(bar.get_x() + bar.get_width()/2., val + 1.5, f"{val:.1f}%\n({abs_v:.1f}โ‚ช)", ha='center', va='bottom', fontsize=7.8, fontweight='bold', color='#E65100')
# --- Subplot 2: Vega Gain Curve - Option Value vs Post-Dividend Volatility ---
vol_range = np.linspace(0.20, 0.70, 100)
# Continuous BSM curves for Delek Real Estate
S_post_delek = delek_d0["stock_price_pre"] - delek_d0["dividend_per_share"]
K_post_delek = delek_opt["strike_k0"] - delek_d0["dividend_per_share"]
K_unprot_delek = delek_opt["strike_k0"]
c_protected = [black_scholes_call(S_post_delek, K_post_delek, delek_opt["maturity_years"], delek_d0["risk_free_rate"], v)[0] for v in vol_range]
c_unprotected = [black_scholes_call(S_post_delek, K_unprot_delek, delek_opt["maturity_years"], delek_d0["risk_free_rate"], v)[0] for v in vol_range]
ax2.plot(vol_range * 100, c_protected, color='#2E7D32', linewidth=2.8, label='Protected Option ($K \\to K - D$)')
ax2.plot(vol_range * 100, c_unprotected, color='#D32F2F', linewidth=2.2, linestyle='--', label='Unprotected Option ($K$ Unchanged)')
# Highlight specific volatility points
sigma_pre = delek_d0["pre_div_volatility"] * 100
sigma_post = delek_d0["post_div_volatility"] * 100
v_unprot_at_pre = sim_delek["Value_Unprotected"]
v_prot_at_post = sim_delek["Value_Protected_Higher_Vol"]
ax2.scatter([sigma_pre], [v_unprot_at_pre], color='#D32F2F', s=90, zorder=5, edgecolors='black')
ax2.scatter([sigma_post], [v_prot_at_post], color='#2E7D32', s=110, zorder=5, edgecolors='black')
# Annotation arrows showing Protection gain and Vega gain
ax2.annotate(
f"Unprotected at Pre-Vol ({sigma_pre:.0f}%):\nโ‚ช{v_unprot_at_pre:.2f}/opt",
xy=(sigma_pre, v_unprot_at_pre), xytext=(sigma_pre - 8, v_unprot_at_pre + 4),
arrowprops=dict(arrowstyle="->", color="#D32F2F", lw=1.5),
fontsize=8.5, fontweight='bold', color='#B71C1C',
bbox=dict(boxstyle="round,pad=0.3", fc="#FFEBEE", ec="#D32F2F")
)
ax2.annotate(
f"Protected + Vol Expansion ({sigma_post:.0f}%):\nโ‚ช{v_prot_at_post:.2f}/opt (+29.6% Net Gain)",
xy=(sigma_post, v_prot_at_post), xytext=(sigma_post - 12, v_prot_at_post + 4.5),
arrowprops=dict(arrowstyle="->", color="#2E7D32", lw=1.5),
fontsize=8.5, fontweight='bold', color='#1B5E20',
bbox=dict(boxstyle="round,pad=0.3", fc="#E8F5E9", ec="#2E7D32")
)
# Arrow showing net executive wealth transfer
ax2.annotate(
"", xy=(sigma_post, v_prot_at_post), xytext=(sigma_pre, v_unprot_at_pre),
arrowprops=dict(arrowstyle="fancy,tail_width=0.4,head_width=0.8", color="#FF8F00", alpha=0.7)
)
ax2.text(37, 25.5, "+โ‚ช13.06M Total Wealth Transfer\n(2.0M Options Pool)", fontsize=9, fontweight='bold', color='#E65100',
bbox=dict(boxstyle="round,pad=0.3", fc="#FFF3E0", ec="#FFB74D"))
ax2.set_title("B. Vega Slope & Wealth Transfer (Delek Real Estate)\nOption Value Curve: $C(S-D, K-D, \\sigma)$ vs $\\sigma$", fontsize=11, pad=10)
ax2.set_xlabel("Annualized Asset Volatility $\\sigma$ (%)")
ax2.set_ylabel("Option Price per Share (NIS / Option)")
ax2.set_xlim(20, 70)
ax2.set_ylim(14, 38)
ax2.grid(True, linestyle='--', alpha=0.6)
ax2.legend(loc='lower right', frameon=True, facecolor='white', framealpha=0.9)
plt.tight_layout(rect=[0, 0.03, 1, 0.94])
output_path = os.path.join(OUTPUT_DIR, "option_value_vega_gain.png")
plt.savefig(output_path, dpi=300)
plt.close()
print(f" Successfully saved: {output_path}")
def generate_sensitivity_heatmap():
"""
Figure 3: sensitivity_heatmap.png
Generates a high-resolution dual-heatmap matrix showing Executive Option Net Gain (NIS)
and Percentage Value Gain (%) across Moneyness (K/S) and Volatility Expansion Shocks (ฮ”ฯƒ).
"""
# Base simulation baseline: S0 = 100 NIS, Dividend = 15 NIS (15%), T = 3.0 yrs, r = 4.0%, base_vol = 30%
S_0 = 100.0
dividend = 15.0
T = 3.0
r = 0.04
sigma_0 = 0.30
moneyness_ratios = [0.80, 0.90, 1.00, 1.10, 1.20]
moneyness_labels = ["ITM (0.80)", "ITM (0.90)", "ATM (1.00)", "OTM (1.10)", "OTM (1.20)"]
vol_shocks = [0.02, 0.05, 0.08, 0.10, 0.12, 0.15]
vol_shock_labels = ["+2% (32%)", "+5% (35%)", "+8% (38%)", "+10% (40%)", "+12% (42%)", "+15% (45%)"]
net_gain_matrix = np.zeros((len(moneyness_ratios), len(vol_shocks)))
pct_gain_matrix = np.zeros((len(moneyness_ratios), len(vol_shocks)))
for i, m in enumerate(moneyness_ratios):
K_0 = S_0 * m
for j, v_shock in enumerate(vol_shocks):
sim = simulate_dividend_impact(S_0, K_0, T, r, sigma_0, dividend, sigma_increase=v_shock)
net_gain_matrix[i, j] = sim["Net_Benefit_To_Executive"]
pct_gain_matrix[i, j] = (sim["Value_Protected_Higher_Vol"] / sim["Value_Unprotected"] - 1.0) * 100.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6.5))
fig.suptitle("Executive Wealth Sensitivity Matrix: Strike Moneyness ($K/S$) vs Volatility Jump ($\\Delta\\sigma$)\nImpact of Dividend Protection + Risk Shifting Leverage Expansion", fontsize=13.5, y=0.98)
# --- Heatmap 1: Net Benefit in NIS per Option ---
im1 = ax1.imshow(net_gain_matrix, cmap='YlOrRd', aspect='auto', interpolation='nearest')
ax1.set_title("A. Absolute Option Gain (NIS / Option)\n$\\Delta C = C_{\\text{Protected}}(\\sigma_0 + \\Delta\\sigma) - C_{\\text{Unprotected}}(\\sigma_0)$", fontsize=10.5, pad=10)
ax1.set_xticks(np.arange(len(vol_shock_labels)))
ax1.set_yticks(np.arange(len(moneyness_labels)))
ax1.set_xticklabels(vol_shock_labels, rotation=25, ha='right', fontsize=9)
ax1.set_yticklabels(moneyness_labels, fontsize=9.5)
ax1.set_xlabel("Volatility Shock Expansion $\\Delta\\sigma$ (Post-Div $\\sigma$)", fontweight='bold')
ax1.set_ylabel("Option Moneyness $(K_0 / S_0)$", fontweight='bold')
# Annotate values inside cells
for i in range(len(moneyness_ratios)):
for j in range(len(vol_shocks)):
val = net_gain_matrix[i, j]
text_color = "white" if val > (net_gain_matrix.max() * 0.65) else "black"
ax1.text(j, i, f"+โ‚ช{val:.2f}", ha="center", va="center", color=text_color, fontweight='bold', fontsize=9.5)
cbar1 = fig.colorbar(im1, ax=ax1, fraction=0.046, pad=0.04)
cbar1.set_label("NIS / Option Gain", fontsize=9.5, fontweight='bold')
# --- Heatmap 2: Percentage Benefit over Unprotected (%) ---
im2 = ax2.imshow(pct_gain_matrix, cmap='viridis', aspect='auto', interpolation='nearest')
ax2.set_title("B. Relative Wealth Gain (% Over Unprotected Baseline)\n$[C_{\\text{Protected}}(\\sigma_0 + \\Delta\\sigma) / C_{\\text{Unprotected}}(\\sigma_0) - 1] \\times 100\\%$", fontsize=10.5, pad=10)
ax2.set_xticks(np.arange(len(vol_shock_labels)))
ax2.set_yticks(np.arange(len(moneyness_labels)))
ax2.set_xticklabels(vol_shock_labels, rotation=25, ha='right', fontsize=9)
ax2.set_yticklabels(moneyness_labels, fontsize=9.5)
ax2.set_xlabel("Volatility Shock Expansion $\\Delta\\sigma$ (Post-Div $\\sigma$)", fontweight='bold')
ax2.set_ylabel("Option Moneyness $(K_0 / S_0)$", fontweight='bold')
# Annotate values inside cells
for i in range(len(moneyness_ratios)):
for j in range(len(vol_shocks)):
val = pct_gain_matrix[i, j]
text_color = "black" if val > (pct_gain_matrix.max() * 0.7) else "white"
ax2.text(j, i, f"+{val:.1f}%", ha="center", va="center", color=text_color, fontweight='bold', fontsize=9.5)
cbar2 = fig.colorbar(im2, ax=ax2, fraction=0.046, pad=0.04)
cbar2.set_label("Percentage Gain (%)", fontsize=9.5, fontweight='bold')
plt.tight_layout(rect=[0, 0.03, 1, 0.94])
output_path = os.path.join(OUTPUT_DIR, "sensitivity_heatmap.png")
plt.savefig(output_path, dpi=300)
plt.close()
print(f" Successfully saved: {output_path}")
def main():
print("================================================================")
print("Plot Generator: Generating Academic-Grade Publication Figures")
print("================================================================")
generate_altman_vs_accounting_surplus()
generate_option_value_vega_gain()
generate_sensitivity_heatmap()
print("================================================================")
print("All 3 high-resolution figures successfully generated in /home/dcor/omerazoulay/nini:")
print("1. altman_vs_accounting_surplus.png")
print("2. option_value_vega_gain.png")
print("3. sensitivity_heatmap.png")
print("================================================================")
if __name__ == "__main__":
main()