#!/usr/bin/env python3
"""
Dimensionamento di una posizione corta di gamma: i due criteri e il loro
punto di incrocio. Produce i numeri del capitolo sul protocollo operativo.

    python3 figure/dimensionamento.py
"""
import math, os
HERE = os.path.dirname(os.path.abspath(__file__))
SQ = math.sqrt(2.0 * math.pi)
S, SIG, M, HRS_YR = 6500.0, 0.12, 100, 252 * 6.5
K_SIGMA = 3.0        # ampiezza in deviazioni standard residue
X_SHOCK = 0.01       # shock fisso: 1% del sottostante, indipendente da T
BUDGET = 50_000.0    # budget di perdita in dollari


def gamma_atm(T):
    return (1.0 / SQ) / (S * SIG * math.sqrt(T))


print(f"S={S:,.0f}  sigma={SIG:.0%}  budget=${BUDGET:,.0f}  "
      f"k={K_SIGMA:.0f} sd  shock={X_SHOCK:.0%}\n")
print(f"{'ore':>6} {'sigma*sqrt(T)':>13} {'k-sd (%)':>9} {'perdita/contr (k-sd)':>21}"
      f" {'perdita/contr (shock)':>22} {'vincolante':>11} {'n max':>8}")
righe = []
for h in (6.5, 4.0, 2.0, 1.26, 1.0, 0.5, 0.25):
    T = h / HRS_YR
    g = gamma_atm(T)
    gdollar = g * M * S * S                 # gamma in dollari per movimento unitario
    x_sd = K_SIGMA * SIG * math.sqrt(T)
    L_sd = 0.5 * gdollar * x_sd ** 2
    L_sh = 0.5 * gdollar * X_SHOCK ** 2
    L = max(L_sd, L_sh)
    quale = "k-sd" if L_sd >= L_sh else "SHOCK"
    # Contratti compatibili con il budget nello scenario: il rapporto viene
    # troncato perché l'intero successivo supererebbe il limite specificato.
    n = math.floor(BUDGET / L)
    righe.append((h, SIG * math.sqrt(T), x_sd, L_sd, L_sh, quale, n))
    print(f"{h:>6.2f} {SIG*math.sqrt(T):>13.5f} {x_sd*100:>8.2f}% "
          f"{L_sd:>21,.0f} {L_sh:>22,.0f} {quale:>11} {n:>8d}"
          f"   perdita {n*L:>7,.0f}")

T_star = (X_SHOCK / (K_SIGMA * SIG)) ** 2
print(f"\nincrocio dei due criteri: T* = (x0/(k sigma))^2 = {T_star:.3e} anni"
      f" = {T_star*HRS_YR:.2f} ore di borsa")

with open(os.path.join(HERE, "dimensionamento.txt"), "w") as f:
    for h, v, x, a, b, q, n in righe:
        f.write(f"{h:.2f} & {v:.5f} & {x*100:.2f}\\% & {a:,.0f} & {b:,.0f} & "
                f"{q} & {n:.0f} \\\\\n")
print("scritto figure/dimensionamento.txt")
