shacosky2

bs_app.py

Jun 25th, 2026 (edited)
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.06 KB | None | 0 0
  1. # ============================================================
  2. # BLACK-SCHOLES CALCULATOR — STREAMLIT APP
  3. # Curso de Derivados Financieros
  4. #
  5. # Instalar dependencias:
  6. # pip install streamlit yfinance plotly
  7. #
  8. # Ejecutar:
  9. # streamlit run bs_app.py
  10. # ============================================================
  11.  
  12. import streamlit as st
  13. import plotly.graph_objects as go
  14. import numpy as np
  15. from math import log, sqrt, exp, erf
  16.  
  17. try:
  18. import yfinance as yf
  19. YFINANCE_OK = True
  20. except ImportError:
  21. YFINANCE_OK = False
  22.  
  23.  
  24. # ============================================================
  25. # FUNCIONES BLACK-SCHOLES
  26. # ============================================================
  27.  
  28. def N(x):
  29. """Distribución normal acumulada estándar."""
  30. return 0.5 * (1 + erf(x / sqrt(2)))
  31.  
  32. def npdf(x):
  33. """Densidad normal estándar."""
  34. return exp(-0.5 * x**2) / sqrt(2 * np.pi)
  35.  
  36. def black_scholes(S, K, T, sigma, r):
  37. """
  38. Precio Black-Scholes para call europea + Greeks.
  39. Retorna dict con todos los valores calculados.
  40. """
  41. d1 = (log(S / K) + (r + sigma**2 / 2) * T) / (sigma * sqrt(T))
  42. d2 = d1 - sigma * sqrt(T)
  43. call = S * N(d1) - K * exp(-r * T) * N(d2)
  44. delta = N(d1)
  45. gamma = npdf(d1) / (S * sigma * sqrt(T))
  46. theta = (-(S * npdf(d1) * sigma) / (2 * sqrt(T))
  47. - r * K * exp(-r * T) * N(d2)) / 365
  48. vega = S * npdf(d1) * sqrt(T) / 100
  49. return dict(
  50. call=round(call, 4),
  51. delta=round(delta, 4),
  52. gamma=round(gamma, 4),
  53. theta=round(theta, 4),
  54. vega=round(vega, 4),
  55. d1=round(d1, 4),
  56. d2=round(d2, 4),
  57. N_d1=round(N(d1), 4),
  58. N_d2=round(N(d2), 4),
  59. intrinsic=round(max(0, S - K), 4),
  60. time_value=round(max(0, call - max(0, S - K)), 4),
  61. breakeven=round(K + call, 4),
  62. )
  63.  
  64. @st.cache_data(ttl=300)
  65. def get_stock_data(ticker_symbol):
  66. """Descarga precio y volatilidad histórica desde Yahoo Finance."""
  67. if not YFINANCE_OK:
  68. return None
  69. try:
  70. tk = yf.Ticker(ticker_symbol)
  71. hist = tk.history(period="60d")
  72. if hist.empty:
  73. return None
  74. price = hist["Close"].iloc[-1]
  75. returns = hist["Close"].pct_change().dropna()
  76. vol = returns.tail(30).std() * sqrt(252)
  77. info = tk.info
  78. vol = float(vol) if np.isfinite(vol) else None
  79. return {
  80. "ticker": ticker_symbol.upper(),
  81. "name": info.get("longName", ticker_symbol),
  82. "price": round(float(price), 2),
  83. "vol": round(vol, 4) if vol is not None else None,
  84. }
  85. except Exception:
  86. return None
  87.  
  88.  
  89. # ============================================================
  90. # CONFIGURACIÓN DE LA PÁGINA
  91. # ============================================================
  92.  
  93. st.set_page_config(
  94. page_title="Black-Scholes Calculator",
  95. page_icon="📈",
  96. layout="wide"
  97. )
  98.  
  99. st.markdown(
  100. """
  101. <style>
  102. .block-container {
  103. padding-top: 1.45rem;
  104. padding-bottom: 0.25rem;
  105. max-width: 100%;
  106. }
  107. h1 {
  108. font-size: 1.75rem !important;
  109. line-height: 1.2 !important;
  110. margin: 0 0 0.2rem 0 !important;
  111. padding-top: 0.1rem;
  112. }
  113. h2, h3 {
  114. margin: 0.15rem 0 0.25rem 0 !important;
  115. }
  116. div[data-testid="stCaptionContainer"] {
  117. font-size: 0.78rem;
  118. margin-bottom: 0.15rem;
  119. }
  120. div[data-testid="stMetric"] {
  121. border: 1px solid rgba(255, 255, 255, 0.08);
  122. border-radius: 8px;
  123. padding: 0.42rem 0.55rem;
  124. background: linear-gradient(135deg, #12372f 0%, #1d5b4f 100%);
  125. box-shadow: inset 0 1px 0 rgba(255,255,255,0.06);
  126. }
  127. div[data-testid="stHorizontalBlock"] > div:nth-child(2) div[data-testid="stMetric"] {
  128. background: linear-gradient(135deg, #173b33 0%, #24705f 100%);
  129. }
  130. div[data-testid="stHorizontalBlock"] > div:nth-child(3) div[data-testid="stMetric"],
  131. div[data-testid="stHorizontalBlock"] > div:nth-child(4) div[data-testid="stMetric"] {
  132. background: linear-gradient(135deg, #1b3048 0%, #2e5b86 100%);
  133. }
  134. div[data-testid="stHorizontalBlock"] > div:nth-child(5) div[data-testid="stMetric"],
  135. div[data-testid="stHorizontalBlock"] > div:nth-child(6) div[data-testid="stMetric"] {
  136. background: linear-gradient(135deg, #35265d 0%, #5d4aa1 100%);
  137. }
  138. div[data-testid="stHorizontalBlock"] > div:nth-child(7) div[data-testid="stMetric"],
  139. div[data-testid="stHorizontalBlock"] > div:nth-child(8) div[data-testid="stMetric"] {
  140. background: linear-gradient(135deg, #4a3418 0%, #8a6425 100%);
  141. }
  142. div[data-testid="stMetricLabel"] p {
  143. font-size: 0.72rem !important;
  144. white-space: nowrap;
  145. color: rgba(255,255,255,0.82) !important;
  146. }
  147. div[data-testid="stMetricValue"] {
  148. font-size: 1.08rem !important;
  149. line-height: 1.1 !important;
  150. color: #ffffff !important;
  151. font-weight: 650 !important;
  152. }
  153. div[data-testid="stHorizontalBlock"] {
  154. gap: 0.5rem;
  155. }
  156. div[data-testid="stTabs"] button {
  157. padding: 0.35rem 0.85rem;
  158. }
  159. div[data-testid="stPlotlyChart"] {
  160. margin-top: -0.25rem;
  161. }
  162. section[data-testid="stSidebar"] .block-container {
  163. padding: 0.5rem 0.9rem 0.35rem 0.9rem;
  164. }
  165. section[data-testid="stSidebar"] {
  166. min-width: 350px !important;
  167. width: 350px !important;
  168. }
  169. section[data-testid="stSidebar"] > div {
  170. min-width: 350px !important;
  171. width: 350px !important;
  172. }
  173. section[data-testid="stSidebar"] h2,
  174. section[data-testid="stSidebar"] h3 {
  175. color: #f7f8fb !important;
  176. font-size: 0.9rem !important;
  177. font-weight: 750 !important;
  178. line-height: 1.05 !important;
  179. margin: 0.55rem 0 0.45rem 0 !important;
  180. }
  181. section[data-testid="stSidebar"] label,
  182. section[data-testid="stSidebar"] p {
  183. font-size: 0.72rem !important;
  184. }
  185. section[data-testid="stSidebar"] label p {
  186. color: #dfe6ef !important;
  187. font-weight: 650 !important;
  188. margin-bottom: 0.28rem !important;
  189. }
  190. section[data-testid="stSidebar"] div[data-baseweb="select"] > div,
  191. section[data-testid="stSidebar"] div[data-testid="stNumberInput"] input {
  192. border: 1px solid rgba(255,255,255,0.10) !important;
  193. border-radius: 8px !important;
  194. background-color: #090d16 !important;
  195. box-shadow: inset 0 1px 0 rgba(255,255,255,0.04);
  196. }
  197. section[data-testid="stSidebar"] div[data-testid="stNumberInput"] {
  198. width: 100% !important;
  199. }
  200. section[data-testid="stSidebar"] div[data-testid="stNumberInput"] input {
  201. font-size: 0.9rem !important;
  202. padding: 0.32rem 0.5rem !important;
  203. width: 100% !important;
  204. min-width: 0 !important;
  205. }
  206. section[data-testid="stSidebar"] div[data-testid="stNumberInput"] button {
  207. display: none !important;
  208. }
  209. section[data-testid="stSidebar"] div[data-testid="stSlider"] {
  210. padding-right: 0.15rem;
  211. }
  212. section[data-testid="stSidebar"] div[data-testid="stTooltipHoverTarget"] {
  213. display: none !important;
  214. }
  215. }
  216. section[data-testid="stSidebar"] hr {
  217. margin: 0.15rem 0;
  218. }
  219. section[data-testid="stSidebar"] div[data-testid="stVerticalBlock"] {
  220. gap: 0.42rem;
  221. }
  222. section[data-testid="stSidebar"] div[data-testid="stSelectbox"],
  223. section[data-testid="stSidebar"] div[data-testid="stNumberInput"],
  224. section[data-testid="stSidebar"] div[data-testid="stSlider"] {
  225. margin-bottom: 0.08rem;
  226. }
  227. section[data-testid="stSidebar"] div[data-testid="stAlert"] {
  228. padding: 0.22rem 0.45rem;
  229. margin: 0.1rem 0;
  230. }
  231. .sidebar-chip {
  232. border: 1px solid rgba(35, 194, 149, 0.26);
  233. border-radius: 8px;
  234. padding: 0.45rem 0.55rem;
  235. background: linear-gradient(135deg, rgba(18,55,47,0.72), rgba(22,38,55,0.72));
  236. margin: 0.28rem 0 0.35rem 0;
  237. }
  238. .sidebar-chip .name {
  239. color: #72f0bf;
  240. font-weight: 750;
  241. font-size: 0.76rem;
  242. line-height: 1.2;
  243. }
  244. .sidebar-chip .meta {
  245. color: #b8c1cc;
  246. font-size: 0.7rem;
  247. margin-top: 0.25rem;
  248. }
  249. .sidebar-note {
  250. color: #aeb7c2;
  251. font-size: 0.7rem;
  252. line-height: 1.25;
  253. margin: 0.05rem 0 0.22rem 0;
  254. }
  255. .scenario-note {
  256. border-left: 3px solid #ff4b5c;
  257. border-radius: 0 6px 6px 0;
  258. background: rgba(255, 75, 92, 0.07);
  259. color: #d6dce5;
  260. font-size: 0.72rem;
  261. line-height: 1.25;
  262. padding: 0.32rem 0.45rem;
  263. margin: 0.2rem 0 0.45rem 0;
  264. }
  265. .sidebar-section-rule {
  266. height: 1px;
  267. background: linear-gradient(90deg, rgba(255,255,255,0.12), rgba(255,255,255,0));
  268. margin: 0.55rem 0 0.5rem 0;
  269. }
  270. </style>
  271. """,
  272. unsafe_allow_html=True,
  273. )
  274.  
  275. st.title("Black-Scholes Calculator")
  276. st.caption("Opciones call europeas — datos reales de mercado")
  277.  
  278.  
  279. # ============================================================
  280. # SIDEBAR: TICKER + PARÁMETROS
  281. # ============================================================
  282.  
  283. with st.sidebar:
  284. st.header("Parámetros")
  285.  
  286. # --- Ticker ---
  287. st.subheader("Acción")
  288. quick = st.selectbox(
  289. "Ticker",
  290. ["NVDA", "AAPL", "TSLA", "MSFT", "AMZN", "GOOGL", "SPY", "Otro..."]
  291. )
  292. if quick == "Otro...":
  293. ticker_input = st.text_input("Escribe el ticker", value="META").upper()
  294. else:
  295. ticker_input = quick
  296.  
  297. usar_real = st.toggle("Usar datos reales (yfinance)", value=YFINANCE_OK)
  298.  
  299. # --- Obtener datos ---
  300. S_default, sigma_default = 150.0, 0.30
  301. stock_info = None
  302.  
  303. if usar_real and YFINANCE_OK:
  304. with st.spinner(f"Cargando {ticker_input}..."):
  305. stock_info = get_stock_data(ticker_input)
  306. if stock_info:
  307. S_default = stock_info["price"]
  308. if stock_info["vol"] is not None:
  309. sigma_default = stock_info["vol"]
  310. vol_text = f"{sigma_default*100:.1f}%"
  311. else:
  312. vol_text = "manual 30.0%"
  313. st.markdown(
  314. f"""
  315. <div class="sidebar-chip">
  316. <div class="name">{stock_info['name']}</div>
  317. <div class="meta">Precio ${S_default:.2f} · Vol. {vol_text}</div>
  318. </div>
  319. """,
  320. unsafe_allow_html=True,
  321. )
  322. else:
  323. st.warning(f"{ticker_input} no aparece en Yahoo Finance. Usa valores manuales.")
  324.  
  325. escenario = st.selectbox(
  326. "Escenario de clase",
  327. [
  328. "Base: call OTM 3 meses",
  329. "ATM: strike = precio",
  330. "Volatilidad alta",
  331. "Largo plazo: 1 año",
  332. ]
  333. )
  334.  
  335. scenario_defaults = {
  336. "Base: call OTM 3 meses": {
  337. "K": round(S_default * 1.05),
  338. "T": 0.25,
  339. "sigma": sigma_default,
  340. "note": "Caso inicial: opción fuera del dinero con vencimiento corto.",
  341. },
  342. "ATM: strike = precio": {
  343. "K": round(S_default),
  344. "T": 0.25,
  345. "sigma": sigma_default,
  346. "note": "Muestra qué pasa cuando el strike está cerca de S₀.",
  347. },
  348. "Volatilidad alta": {
  349. "K": round(S_default * 1.05),
  350. "T": 0.25,
  351. "sigma": min(1.0, max(0.05, sigma_default * 1.6)),
  352. "note": "Sube σ para ver cómo aumenta la prima de la opción.",
  353. },
  354. "Largo plazo: 1 año": {
  355. "K": round(S_default * 1.05),
  356. "T": 1.0,
  357. "sigma": sigma_default,
  358. "note": "Más tiempo al vencimiento eleva el valor tiempo.",
  359. },
  360. }
  361. preset = scenario_defaults[escenario]
  362. st.markdown(f'<div class="scenario-note">{preset["note"]}</div>',
  363. unsafe_allow_html=True)
  364. st.markdown('<div class="sidebar-section-rule"></div>', unsafe_allow_html=True)
  365.  
  366. # --- Parámetros del contrato ---
  367. st.subheader("Contrato")
  368.  
  369. K = st.slider(
  370. "Strike K ($)",
  371. min_value=float(round(S_default * 0.5)),
  372. max_value=float(round(S_default * 1.6)),
  373. value=float(preset["K"]),
  374. step=1.0
  375. )
  376.  
  377. T = st.slider(
  378. "Vencimiento T (años)",
  379. min_value=0.05,
  380. max_value=2.0,
  381. value=float(preset["T"]),
  382. step=0.05,
  383. format="%.2f"
  384. )
  385. st.markdown('<div class="sidebar-section-rule"></div>', unsafe_allow_html=True)
  386.  
  387. # --- Parámetros de mercado ---
  388. st.subheader("Mercado")
  389.  
  390. S = st.number_input("Precio actual S₀ ($)", value=S_default, step=1.0)
  391. sigma = st.number_input("Volatilidad anual σ", min_value=0.05, max_value=1.0,
  392. value=float(preset["sigma"]), step=0.01, format="%.2f")
  393. r = st.number_input("Tasa libre de riesgo r", min_value=0.0, max_value=0.15,
  394. value=0.043, step=0.001, format="%.3f")
  395.  
  396.  
  397. # ============================================================
  398. # CÁLCULO
  399. # ============================================================
  400.  
  401. res = black_scholes(S, K, T, sigma, r)
  402.  
  403. # Moneyness
  404. if S > K * 1.02:
  405. moneyness, mon_color = "IN THE MONEY (ITM)", "normal"
  406. elif S < K * 0.98:
  407. moneyness, mon_color = "OUT OF THE MONEY (OTM)", "inverse"
  408. else:
  409. moneyness, mon_color = "AT THE MONEY (ATM)", "off"
  410.  
  411.  
  412. # ============================================================
  413. # MÉTRICAS COMPACTAS
  414. # ============================================================
  415.  
  416. kpi = st.columns(8)
  417. kpi[0].metric("Prima call", f"${res['call']:.2f}")
  418. kpi[1].metric("Break-even", f"${res['breakeven']:.2f}")
  419. kpi[2].metric("Intrínseco", f"${res['intrinsic']:.2f}")
  420. kpi[3].metric("Valor tiempo", f"${res['time_value']:.2f}")
  421. kpi[4].metric("Δ Delta", f"{res['delta']:.4f}",
  422. help="Si S sube $1, la call sube ~$" + str(round(res['delta'], 2)))
  423. kpi[5].metric("Γ Gamma", f"{res['gamma']:.4f}",
  424. help="Velocidad de cambio del delta por $1 en S")
  425. kpi[6].metric("Θ Theta", f"{res['theta']:.4f}",
  426. help=f"Pierde ${abs(res['theta']):.4f} de valor por día")
  427. kpi[7].metric("ν Vega", f"{res['vega']:.4f}",
  428. help=f"Si σ sube 1%, la call sube ~${res['vega']:.2f}")
  429.  
  430. st.caption(f"{moneyness} | Prob. de expirar ITM ≈ {res['N_d2']*100:.1f}% | S=${S:.2f}, K=${K:.2f}, T={T:.2f}, σ={sigma:.2f}, r={r:.3f}")
  431.  
  432.  
  433. # ============================================================
  434. # GRÁFICOS
  435. # ============================================================
  436.  
  437. tab1, tab2, tab3, tab4 = st.tabs(["Payoff al vencimiento", "Curva de precio BS", "Sensibilidad", "Fórmula"])
  438.  
  439. s_range = np.linspace(max(1, K * 0.45), K * 1.65, 200)
  440.  
  441. with tab1:
  442. # Payoff diagram
  443. payoff = np.maximum(0, s_range - K) - res['call']
  444. loss_line = np.full_like(s_range, -res['call'])
  445.  
  446. fig1 = go.Figure()
  447. fig1.add_trace(go.Scatter(
  448. x=s_range, y=payoff, name="Ganancia neta",
  449. line=dict(color="#1D9E75", width=2.5),
  450. fill="tozeroy",
  451. fillcolor="rgba(29,158,117,0.10)"
  452. ))
  453. fig1.add_trace(go.Scatter(
  454. x=s_range, y=loss_line, name=f"Pérdida máxima (−${res['call']:.2f})",
  455. line=dict(color="#D85A30", width=1.5, dash="dash")
  456. ))
  457. fig1.add_vline(x=S, line_color="rgba(226,232,240,0.55)", line_width=1,
  458. line_dash="dash",
  459. annotation_text=f"S actual ${S:.0f}", annotation_position="top left")
  460. fig1.add_vline(x=res['breakeven'], line_color="#F5A524", line_width=1.5,
  461. line_dash="dot",
  462. annotation_text=f"Break-even ${res['breakeven']:.0f}", annotation_position="top right")
  463. fig1.add_hline(y=0, line_color="gray", line_width=0.8)
  464. fig1.update_layout(
  465. xaxis_title="Precio al vencimiento (S_T)",
  466. yaxis_title="Ganancia / Pérdida ($)",
  467. legend=dict(orientation="h", y=-0.18),
  468. height=285, margin=dict(t=10, r=10, b=45, l=10)
  469. )
  470. st.plotly_chart(fig1, width="stretch")
  471. st.caption(f"Break-even ${res['breakeven']:.2f} | Pérdida máxima ${res['call']:.2f}")
  472.  
  473. with tab2:
  474. # Curva BS vs valor intrínseco
  475. bs_prices = [black_scholes(sv, K, T, sigma, r)["call"] for sv in s_range]
  476. intr_prices = np.maximum(0, s_range - K)
  477.  
  478. fig2 = go.Figure()
  479. fig2.add_trace(go.Scatter(
  480. x=s_range, y=bs_prices, name="Precio Black-Scholes",
  481. line=dict(color="#534AB7", width=2.5)
  482. ))
  483. fig2.add_trace(go.Scatter(
  484. x=s_range, y=intr_prices, name="Valor intrínseco",
  485. line=dict(color="#B4B2A9", width=1.5, dash="dash")
  486. ))
  487. fig2.add_vline(x=S, line_color="rgba(226,232,240,0.55)", line_width=1,
  488. line_dash="dash",
  489. annotation_text=f"S actual ${S:.0f}", annotation_position="top left")
  490. fig2.add_vline(x=K, line_color="#888780", line_dash="dot",
  491. annotation_text=f"Strike ${K:.0f}", annotation_position="top left")
  492. fig2.update_layout(
  493. xaxis_title="Precio actual de la acción (S₀)",
  494. yaxis_title="Precio de la call ($)",
  495. legend=dict(orientation="h", y=-0.18),
  496. height=285, margin=dict(t=10, r=10, b=45, l=10)
  497. )
  498. st.plotly_chart(fig2, width="stretch")
  499. st.caption(f"Valor tiempo actual: ${res['time_value']:.2f}")
  500.  
  501. with tab3:
  502. # Tabla de sensibilidad por strike
  503. st.caption("Cómo cambia la prima según el strike elegido")
  504. multipliers = [0.80, 0.85, 0.90, 0.95, 1.00, 1.05, 1.10, 1.15, 1.20]
  505. rows = []
  506. for m in multipliers:
  507. k_test = round(S * m, 2)
  508. r_test = black_scholes(S, k_test, T, sigma, r)
  509. if S > k_test * 1.02:
  510. mon = "ITM"
  511. elif S < k_test * 0.98:
  512. mon = "OTM"
  513. else:
  514. mon = "ATM"
  515. rows.append({
  516. "Strike (K)": f"${k_test:.2f}",
  517. "Prima": f"${r_test['call']:.2f}",
  518. "Moneyness": mon,
  519. "Prob ITM": f"{r_test['N_d2']*100:.1f}%",
  520. "Break-even": f"${r_test['breakeven']:.2f}",
  521. "Valor tiempo": f"${r_test['time_value']:.2f}",
  522. })
  523. import pandas as pd
  524. df = pd.DataFrame(rows)
  525. st.dataframe(df, width="stretch", hide_index=True, height=285)
  526.  
  527.  
  528. # ============================================================
  529. # FÓRMULA PASO A PASO
  530. # ============================================================
  531.  
  532. with tab4:
  533. f1, f2 = st.columns([1, 1])
  534. f1.markdown("**Fórmula**")
  535. f1.code(
  536. "d1 = (ln(S/K) + (r + sigma^2/2) * T) / (sigma * sqrt(T))\n"
  537. "d2 = d1 - sigma * sqrt(T)\n"
  538. "C = S*N(d1) - K*exp(-r*T)*N(d2)",
  539. language="text",
  540. )
  541. f2.markdown("**Valores actuales**")
  542. f2.code(
  543. f"S={S:.2f} K={K:.2f} T={T:.2f} sigma={sigma:.2f} r={r:.3f}\n"
  544. f"d1={res['d1']:.4f} d2={res['d2']:.4f}\n"
  545. f"N(d1)={res['N_d1']:.4f} N(d2)={res['N_d2']:.4f}\n"
  546. f"C=${res['call']:.2f}",
  547. language="text",
  548. )
  549.  
Advertisement
Add Comment
Please, Sign In to add comment