Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ============================================================
- # BLACK-SCHOLES CALCULATOR — STREAMLIT APP
- # Curso de Derivados Financieros
- #
- # Instalar dependencias:
- # pip install streamlit yfinance plotly
- #
- # Ejecutar:
- # streamlit run bs_app.py
- # ============================================================
- import streamlit as st
- import plotly.graph_objects as go
- import numpy as np
- from math import log, sqrt, exp, erf
- try:
- import yfinance as yf
- YFINANCE_OK = True
- except ImportError:
- YFINANCE_OK = False
- # ============================================================
- # FUNCIONES BLACK-SCHOLES
- # ============================================================
- def N(x):
- """Distribución normal acumulada estándar."""
- return 0.5 * (1 + erf(x / sqrt(2)))
- def npdf(x):
- """Densidad normal estándar."""
- return exp(-0.5 * x**2) / sqrt(2 * np.pi)
- def black_scholes(S, K, T, sigma, r):
- """
- Precio Black-Scholes para call europea + Greeks.
- Retorna dict con todos los valores calculados.
- """
- d1 = (log(S / K) + (r + sigma**2 / 2) * T) / (sigma * sqrt(T))
- d2 = d1 - sigma * sqrt(T)
- call = S * N(d1) - K * exp(-r * T) * N(d2)
- delta = N(d1)
- gamma = npdf(d1) / (S * sigma * sqrt(T))
- theta = (-(S * npdf(d1) * sigma) / (2 * sqrt(T))
- - r * K * exp(-r * T) * N(d2)) / 365
- vega = S * npdf(d1) * sqrt(T) / 100
- return dict(
- call=round(call, 4),
- delta=round(delta, 4),
- gamma=round(gamma, 4),
- theta=round(theta, 4),
- vega=round(vega, 4),
- d1=round(d1, 4),
- d2=round(d2, 4),
- N_d1=round(N(d1), 4),
- N_d2=round(N(d2), 4),
- intrinsic=round(max(0, S - K), 4),
- time_value=round(max(0, call - max(0, S - K)), 4),
- breakeven=round(K + call, 4),
- )
- @st.cache_data(ttl=300)
- def get_stock_data(ticker_symbol):
- """Descarga precio y volatilidad histórica desde Yahoo Finance."""
- if not YFINANCE_OK:
- return None
- try:
- tk = yf.Ticker(ticker_symbol)
- hist = tk.history(period="60d")
- if hist.empty:
- return None
- price = hist["Close"].iloc[-1]
- returns = hist["Close"].pct_change().dropna()
- vol = returns.tail(30).std() * sqrt(252)
- info = tk.info
- vol = float(vol) if np.isfinite(vol) else None
- return {
- "ticker": ticker_symbol.upper(),
- "name": info.get("longName", ticker_symbol),
- "price": round(float(price), 2),
- "vol": round(vol, 4) if vol is not None else None,
- }
- except Exception:
- return None
- # ============================================================
- # CONFIGURACIÓN DE LA PÁGINA
- # ============================================================
- st.set_page_config(
- page_title="Black-Scholes Calculator",
- page_icon="📈",
- layout="wide"
- )
- st.markdown(
- """
- <style>
- .block-container {
- padding-top: 1.45rem;
- padding-bottom: 0.25rem;
- max-width: 100%;
- }
- h1 {
- font-size: 1.75rem !important;
- line-height: 1.2 !important;
- margin: 0 0 0.2rem 0 !important;
- padding-top: 0.1rem;
- }
- h2, h3 {
- margin: 0.15rem 0 0.25rem 0 !important;
- }
- div[data-testid="stCaptionContainer"] {
- font-size: 0.78rem;
- margin-bottom: 0.15rem;
- }
- div[data-testid="stMetric"] {
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 8px;
- padding: 0.42rem 0.55rem;
- background: linear-gradient(135deg, #12372f 0%, #1d5b4f 100%);
- box-shadow: inset 0 1px 0 rgba(255,255,255,0.06);
- }
- div[data-testid="stHorizontalBlock"] > div:nth-child(2) div[data-testid="stMetric"] {
- background: linear-gradient(135deg, #173b33 0%, #24705f 100%);
- }
- div[data-testid="stHorizontalBlock"] > div:nth-child(3) div[data-testid="stMetric"],
- div[data-testid="stHorizontalBlock"] > div:nth-child(4) div[data-testid="stMetric"] {
- background: linear-gradient(135deg, #1b3048 0%, #2e5b86 100%);
- }
- div[data-testid="stHorizontalBlock"] > div:nth-child(5) div[data-testid="stMetric"],
- div[data-testid="stHorizontalBlock"] > div:nth-child(6) div[data-testid="stMetric"] {
- background: linear-gradient(135deg, #35265d 0%, #5d4aa1 100%);
- }
- div[data-testid="stHorizontalBlock"] > div:nth-child(7) div[data-testid="stMetric"],
- div[data-testid="stHorizontalBlock"] > div:nth-child(8) div[data-testid="stMetric"] {
- background: linear-gradient(135deg, #4a3418 0%, #8a6425 100%);
- }
- div[data-testid="stMetricLabel"] p {
- font-size: 0.72rem !important;
- white-space: nowrap;
- color: rgba(255,255,255,0.82) !important;
- }
- div[data-testid="stMetricValue"] {
- font-size: 1.08rem !important;
- line-height: 1.1 !important;
- color: #ffffff !important;
- font-weight: 650 !important;
- }
- div[data-testid="stHorizontalBlock"] {
- gap: 0.5rem;
- }
- div[data-testid="stTabs"] button {
- padding: 0.35rem 0.85rem;
- }
- div[data-testid="stPlotlyChart"] {
- margin-top: -0.25rem;
- }
- section[data-testid="stSidebar"] .block-container {
- padding: 0.5rem 0.9rem 0.35rem 0.9rem;
- }
- section[data-testid="stSidebar"] {
- min-width: 350px !important;
- width: 350px !important;
- }
- section[data-testid="stSidebar"] > div {
- min-width: 350px !important;
- width: 350px !important;
- }
- section[data-testid="stSidebar"] h2,
- section[data-testid="stSidebar"] h3 {
- color: #f7f8fb !important;
- font-size: 0.9rem !important;
- font-weight: 750 !important;
- line-height: 1.05 !important;
- margin: 0.55rem 0 0.45rem 0 !important;
- }
- section[data-testid="stSidebar"] label,
- section[data-testid="stSidebar"] p {
- font-size: 0.72rem !important;
- }
- section[data-testid="stSidebar"] label p {
- color: #dfe6ef !important;
- font-weight: 650 !important;
- margin-bottom: 0.28rem !important;
- }
- section[data-testid="stSidebar"] div[data-baseweb="select"] > div,
- section[data-testid="stSidebar"] div[data-testid="stNumberInput"] input {
- border: 1px solid rgba(255,255,255,0.10) !important;
- border-radius: 8px !important;
- background-color: #090d16 !important;
- box-shadow: inset 0 1px 0 rgba(255,255,255,0.04);
- }
- section[data-testid="stSidebar"] div[data-testid="stNumberInput"] {
- width: 100% !important;
- }
- section[data-testid="stSidebar"] div[data-testid="stNumberInput"] input {
- font-size: 0.9rem !important;
- padding: 0.32rem 0.5rem !important;
- width: 100% !important;
- min-width: 0 !important;
- }
- section[data-testid="stSidebar"] div[data-testid="stNumberInput"] button {
- display: none !important;
- }
- section[data-testid="stSidebar"] div[data-testid="stSlider"] {
- padding-right: 0.15rem;
- }
- section[data-testid="stSidebar"] div[data-testid="stTooltipHoverTarget"] {
- display: none !important;
- }
- }
- section[data-testid="stSidebar"] hr {
- margin: 0.15rem 0;
- }
- section[data-testid="stSidebar"] div[data-testid="stVerticalBlock"] {
- gap: 0.42rem;
- }
- section[data-testid="stSidebar"] div[data-testid="stSelectbox"],
- section[data-testid="stSidebar"] div[data-testid="stNumberInput"],
- section[data-testid="stSidebar"] div[data-testid="stSlider"] {
- margin-bottom: 0.08rem;
- }
- section[data-testid="stSidebar"] div[data-testid="stAlert"] {
- padding: 0.22rem 0.45rem;
- margin: 0.1rem 0;
- }
- .sidebar-chip {
- border: 1px solid rgba(35, 194, 149, 0.26);
- border-radius: 8px;
- padding: 0.45rem 0.55rem;
- background: linear-gradient(135deg, rgba(18,55,47,0.72), rgba(22,38,55,0.72));
- margin: 0.28rem 0 0.35rem 0;
- }
- .sidebar-chip .name {
- color: #72f0bf;
- font-weight: 750;
- font-size: 0.76rem;
- line-height: 1.2;
- }
- .sidebar-chip .meta {
- color: #b8c1cc;
- font-size: 0.7rem;
- margin-top: 0.25rem;
- }
- .sidebar-note {
- color: #aeb7c2;
- font-size: 0.7rem;
- line-height: 1.25;
- margin: 0.05rem 0 0.22rem 0;
- }
- .scenario-note {
- border-left: 3px solid #ff4b5c;
- border-radius: 0 6px 6px 0;
- background: rgba(255, 75, 92, 0.07);
- color: #d6dce5;
- font-size: 0.72rem;
- line-height: 1.25;
- padding: 0.32rem 0.45rem;
- margin: 0.2rem 0 0.45rem 0;
- }
- .sidebar-section-rule {
- height: 1px;
- background: linear-gradient(90deg, rgba(255,255,255,0.12), rgba(255,255,255,0));
- margin: 0.55rem 0 0.5rem 0;
- }
- </style>
- """,
- unsafe_allow_html=True,
- )
- st.title("Black-Scholes Calculator")
- st.caption("Opciones call europeas — datos reales de mercado")
- # ============================================================
- # SIDEBAR: TICKER + PARÁMETROS
- # ============================================================
- with st.sidebar:
- st.header("Parámetros")
- # --- Ticker ---
- st.subheader("Acción")
- quick = st.selectbox(
- "Ticker",
- ["NVDA", "AAPL", "TSLA", "MSFT", "AMZN", "GOOGL", "SPY", "Otro..."]
- )
- if quick == "Otro...":
- ticker_input = st.text_input("Escribe el ticker", value="META").upper()
- else:
- ticker_input = quick
- usar_real = st.toggle("Usar datos reales (yfinance)", value=YFINANCE_OK)
- # --- Obtener datos ---
- S_default, sigma_default = 150.0, 0.30
- stock_info = None
- if usar_real and YFINANCE_OK:
- with st.spinner(f"Cargando {ticker_input}..."):
- stock_info = get_stock_data(ticker_input)
- if stock_info:
- S_default = stock_info["price"]
- if stock_info["vol"] is not None:
- sigma_default = stock_info["vol"]
- vol_text = f"{sigma_default*100:.1f}%"
- else:
- vol_text = "manual 30.0%"
- st.markdown(
- f"""
- <div class="sidebar-chip">
- <div class="name">{stock_info['name']}</div>
- <div class="meta">Precio ${S_default:.2f} · Vol. {vol_text}</div>
- </div>
- """,
- unsafe_allow_html=True,
- )
- else:
- st.warning(f"{ticker_input} no aparece en Yahoo Finance. Usa valores manuales.")
- escenario = st.selectbox(
- "Escenario de clase",
- [
- "Base: call OTM 3 meses",
- "ATM: strike = precio",
- "Volatilidad alta",
- "Largo plazo: 1 año",
- ]
- )
- scenario_defaults = {
- "Base: call OTM 3 meses": {
- "K": round(S_default * 1.05),
- "T": 0.25,
- "sigma": sigma_default,
- "note": "Caso inicial: opción fuera del dinero con vencimiento corto.",
- },
- "ATM: strike = precio": {
- "K": round(S_default),
- "T": 0.25,
- "sigma": sigma_default,
- "note": "Muestra qué pasa cuando el strike está cerca de S₀.",
- },
- "Volatilidad alta": {
- "K": round(S_default * 1.05),
- "T": 0.25,
- "sigma": min(1.0, max(0.05, sigma_default * 1.6)),
- "note": "Sube σ para ver cómo aumenta la prima de la opción.",
- },
- "Largo plazo: 1 año": {
- "K": round(S_default * 1.05),
- "T": 1.0,
- "sigma": sigma_default,
- "note": "Más tiempo al vencimiento eleva el valor tiempo.",
- },
- }
- preset = scenario_defaults[escenario]
- st.markdown(f'<div class="scenario-note">{preset["note"]}</div>',
- unsafe_allow_html=True)
- st.markdown('<div class="sidebar-section-rule"></div>', unsafe_allow_html=True)
- # --- Parámetros del contrato ---
- st.subheader("Contrato")
- K = st.slider(
- "Strike K ($)",
- min_value=float(round(S_default * 0.5)),
- max_value=float(round(S_default * 1.6)),
- value=float(preset["K"]),
- step=1.0
- )
- T = st.slider(
- "Vencimiento T (años)",
- min_value=0.05,
- max_value=2.0,
- value=float(preset["T"]),
- step=0.05,
- format="%.2f"
- )
- st.markdown('<div class="sidebar-section-rule"></div>', unsafe_allow_html=True)
- # --- Parámetros de mercado ---
- st.subheader("Mercado")
- S = st.number_input("Precio actual S₀ ($)", value=S_default, step=1.0)
- sigma = st.number_input("Volatilidad anual σ", min_value=0.05, max_value=1.0,
- value=float(preset["sigma"]), step=0.01, format="%.2f")
- r = st.number_input("Tasa libre de riesgo r", min_value=0.0, max_value=0.15,
- value=0.043, step=0.001, format="%.3f")
- # ============================================================
- # CÁLCULO
- # ============================================================
- res = black_scholes(S, K, T, sigma, r)
- # Moneyness
- if S > K * 1.02:
- moneyness, mon_color = "IN THE MONEY (ITM)", "normal"
- elif S < K * 0.98:
- moneyness, mon_color = "OUT OF THE MONEY (OTM)", "inverse"
- else:
- moneyness, mon_color = "AT THE MONEY (ATM)", "off"
- # ============================================================
- # MÉTRICAS COMPACTAS
- # ============================================================
- kpi = st.columns(8)
- kpi[0].metric("Prima call", f"${res['call']:.2f}")
- kpi[1].metric("Break-even", f"${res['breakeven']:.2f}")
- kpi[2].metric("Intrínseco", f"${res['intrinsic']:.2f}")
- kpi[3].metric("Valor tiempo", f"${res['time_value']:.2f}")
- kpi[4].metric("Δ Delta", f"{res['delta']:.4f}",
- help="Si S sube $1, la call sube ~$" + str(round(res['delta'], 2)))
- kpi[5].metric("Γ Gamma", f"{res['gamma']:.4f}",
- help="Velocidad de cambio del delta por $1 en S")
- kpi[6].metric("Θ Theta", f"{res['theta']:.4f}",
- help=f"Pierde ${abs(res['theta']):.4f} de valor por día")
- kpi[7].metric("ν Vega", f"{res['vega']:.4f}",
- help=f"Si σ sube 1%, la call sube ~${res['vega']:.2f}")
- 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}")
- # ============================================================
- # GRÁFICOS
- # ============================================================
- tab1, tab2, tab3, tab4 = st.tabs(["Payoff al vencimiento", "Curva de precio BS", "Sensibilidad", "Fórmula"])
- s_range = np.linspace(max(1, K * 0.45), K * 1.65, 200)
- with tab1:
- # Payoff diagram
- payoff = np.maximum(0, s_range - K) - res['call']
- loss_line = np.full_like(s_range, -res['call'])
- fig1 = go.Figure()
- fig1.add_trace(go.Scatter(
- x=s_range, y=payoff, name="Ganancia neta",
- line=dict(color="#1D9E75", width=2.5),
- fill="tozeroy",
- fillcolor="rgba(29,158,117,0.10)"
- ))
- fig1.add_trace(go.Scatter(
- x=s_range, y=loss_line, name=f"Pérdida máxima (−${res['call']:.2f})",
- line=dict(color="#D85A30", width=1.5, dash="dash")
- ))
- fig1.add_vline(x=S, line_color="rgba(226,232,240,0.55)", line_width=1,
- line_dash="dash",
- annotation_text=f"S actual ${S:.0f}", annotation_position="top left")
- fig1.add_vline(x=res['breakeven'], line_color="#F5A524", line_width=1.5,
- line_dash="dot",
- annotation_text=f"Break-even ${res['breakeven']:.0f}", annotation_position="top right")
- fig1.add_hline(y=0, line_color="gray", line_width=0.8)
- fig1.update_layout(
- xaxis_title="Precio al vencimiento (S_T)",
- yaxis_title="Ganancia / Pérdida ($)",
- legend=dict(orientation="h", y=-0.18),
- height=285, margin=dict(t=10, r=10, b=45, l=10)
- )
- st.plotly_chart(fig1, width="stretch")
- st.caption(f"Break-even ${res['breakeven']:.2f} | Pérdida máxima ${res['call']:.2f}")
- with tab2:
- # Curva BS vs valor intrínseco
- bs_prices = [black_scholes(sv, K, T, sigma, r)["call"] for sv in s_range]
- intr_prices = np.maximum(0, s_range - K)
- fig2 = go.Figure()
- fig2.add_trace(go.Scatter(
- x=s_range, y=bs_prices, name="Precio Black-Scholes",
- line=dict(color="#534AB7", width=2.5)
- ))
- fig2.add_trace(go.Scatter(
- x=s_range, y=intr_prices, name="Valor intrínseco",
- line=dict(color="#B4B2A9", width=1.5, dash="dash")
- ))
- fig2.add_vline(x=S, line_color="rgba(226,232,240,0.55)", line_width=1,
- line_dash="dash",
- annotation_text=f"S actual ${S:.0f}", annotation_position="top left")
- fig2.add_vline(x=K, line_color="#888780", line_dash="dot",
- annotation_text=f"Strike ${K:.0f}", annotation_position="top left")
- fig2.update_layout(
- xaxis_title="Precio actual de la acción (S₀)",
- yaxis_title="Precio de la call ($)",
- legend=dict(orientation="h", y=-0.18),
- height=285, margin=dict(t=10, r=10, b=45, l=10)
- )
- st.plotly_chart(fig2, width="stretch")
- st.caption(f"Valor tiempo actual: ${res['time_value']:.2f}")
- with tab3:
- # Tabla de sensibilidad por strike
- st.caption("Cómo cambia la prima según el strike elegido")
- multipliers = [0.80, 0.85, 0.90, 0.95, 1.00, 1.05, 1.10, 1.15, 1.20]
- rows = []
- for m in multipliers:
- k_test = round(S * m, 2)
- r_test = black_scholes(S, k_test, T, sigma, r)
- if S > k_test * 1.02:
- mon = "ITM"
- elif S < k_test * 0.98:
- mon = "OTM"
- else:
- mon = "ATM"
- rows.append({
- "Strike (K)": f"${k_test:.2f}",
- "Prima": f"${r_test['call']:.2f}",
- "Moneyness": mon,
- "Prob ITM": f"{r_test['N_d2']*100:.1f}%",
- "Break-even": f"${r_test['breakeven']:.2f}",
- "Valor tiempo": f"${r_test['time_value']:.2f}",
- })
- import pandas as pd
- df = pd.DataFrame(rows)
- st.dataframe(df, width="stretch", hide_index=True, height=285)
- # ============================================================
- # FÓRMULA PASO A PASO
- # ============================================================
- with tab4:
- f1, f2 = st.columns([1, 1])
- f1.markdown("**Fórmula**")
- f1.code(
- "d1 = (ln(S/K) + (r + sigma^2/2) * T) / (sigma * sqrt(T))\n"
- "d2 = d1 - sigma * sqrt(T)\n"
- "C = S*N(d1) - K*exp(-r*T)*N(d2)",
- language="text",
- )
- f2.markdown("**Valores actuales**")
- f2.code(
- f"S={S:.2f} K={K:.2f} T={T:.2f} sigma={sigma:.2f} r={r:.3f}\n"
- f"d1={res['d1']:.4f} d2={res['d2']:.4f}\n"
- f"N(d1)={res['N_d1']:.4f} N(d2)={res['N_d2']:.4f}\n"
- f"C=${res['call']:.2f}",
- language="text",
- )
Advertisement
Add Comment
Please, Sign In to add comment