Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import yfinance as yf
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from scipy.stats import norm
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import datetime
|
| 8 |
+
import requests
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
# Configurar matplotlib para Streamlit
|
| 12 |
+
import matplotlib
|
| 13 |
+
matplotlib.use('Agg')
|
| 14 |
+
|
| 15 |
+
# -------------------------------
|
| 16 |
+
# Paso 1: Obtener tickers desde Gemini
|
| 17 |
+
# -------------------------------
|
| 18 |
+
|
| 19 |
+
def obtener_tickers_desde_nombres(empresas):
|
| 20 |
+
prompt = (
|
| 21 |
+
"Devuélveme únicamente una lista separada por comas con los tickers de las siguientes empresas: "
|
| 22 |
+
f"{empresas}. No expliques nada más, solo devuelve los tickers separados por comas."
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
headers = {
|
| 26 |
+
"Authorization": f"Bearer {os.getenv('GEMINI_API_KEY')}",
|
| 27 |
+
"Content-Type": "application/json"
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
data = {
|
| 31 |
+
"contents": [{"role": "user", "parts": [{"text": prompt}]}]
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
response = requests.post(
|
| 35 |
+
"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent",
|
| 36 |
+
headers=headers,
|
| 37 |
+
json=data
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
result = response.json()
|
| 42 |
+
raw_text = result["candidates"][0]["content"]["parts"][0]["text"]
|
| 43 |
+
tickers = [t.strip().upper() for t in raw_text.split(",") if t.strip()]
|
| 44 |
+
return tickers
|
| 45 |
+
except Exception as e:
|
| 46 |
+
st.error("Error al obtener tickers desde Gemini")
|
| 47 |
+
return []
|
| 48 |
+
|
| 49 |
+
# -------------------------------
|
| 50 |
+
# Paso 2: Interfaz Streamlit
|
| 51 |
+
# -------------------------------
|
| 52 |
+
|
| 53 |
+
st.title("Calculadora de VaR y CVaR con Gemini y Yahoo Finance")
|
| 54 |
+
|
| 55 |
+
empresa_input = st.text_input("Escribe los nombres de las empresas separadas por coma (ej. Apple, Google, Meta):")
|
| 56 |
+
|
| 57 |
+
confidence_level = st.selectbox("Nivel de confianza:", [0.95, 0.99])
|
| 58 |
+
|
| 59 |
+
if st.button("Calcular VaR y CVaR") and empresa_input:
|
| 60 |
+
tickers = obtener_tickers_desde_nombres(empresa_input)
|
| 61 |
+
if len(tickers) < 2:
|
| 62 |
+
st.warning("Se requieren al menos dos tickers válidos.")
|
| 63 |
+
else:
|
| 64 |
+
st.success(f"Tickers detectados: {', '.join(tickers)}")
|
| 65 |
+
|
| 66 |
+
weights = np.array([1/len(tickers)] * len(tickers))
|
| 67 |
+
|
| 68 |
+
year = datetime.datetime.today().year
|
| 69 |
+
start_date = f"{year}-01-02"
|
| 70 |
+
end_date = datetime.datetime.today().strftime("%Y-%m-%d")
|
| 71 |
+
|
| 72 |
+
data = yf.download(tickers, start=start_date, end=end_date)["Close"]
|
| 73 |
+
data = data.dropna()
|
| 74 |
+
returns = data.pct_change().dropna()
|
| 75 |
+
portfolio_returns = returns.dot(weights)
|
| 76 |
+
|
| 77 |
+
tail_prob = 1 - confidence_level
|
| 78 |
+
historical_VaR = np.percentile(portfolio_returns, tail_prob * 100)
|
| 79 |
+
mean_ret = portfolio_returns.mean()
|
| 80 |
+
std_ret = portfolio_returns.std()
|
| 81 |
+
z_score = norm.ppf(tail_prob)
|
| 82 |
+
parametric_VaR = mean_ret + z_score * std_ret
|
| 83 |
+
simulated_returns = np.random.normal(mean_ret, std_ret, 10000)
|
| 84 |
+
mc_VaR = np.percentile(simulated_returns, tail_prob * 100)
|
| 85 |
+
historical_CVaR = portfolio_returns[portfolio_returns <= historical_VaR].mean()
|
| 86 |
+
|
| 87 |
+
st.subheader("Resultados:")
|
| 88 |
+
st.markdown(f"**Historical VaR:** {historical_VaR:.4%}")
|
| 89 |
+
st.markdown(f"**Parametric VaR:** {parametric_VaR:.4%}")
|
| 90 |
+
st.markdown(f"**Monte Carlo VaR:** {mc_VaR:.4%}")
|
| 91 |
+
st.markdown(f"**Historical CVaR (Expected Shortfall):** {historical_CVaR:.4%}")
|
| 92 |
+
|
| 93 |
+
# Gráfico 1: Histograma
|
| 94 |
+
fig1, ax1 = plt.subplots(figsize=(10, 6))
|
| 95 |
+
ax1.hist(portfolio_returns, bins=50, density=True, alpha=0.5)
|
| 96 |
+
ax1.axvline(historical_VaR, color="red", linestyle="--", label="Historical VaR")
|
| 97 |
+
ax1.axvline(parametric_VaR, color="blue", linestyle="--", label="Parametric VaR")
|
| 98 |
+
ax1.axvline(mc_VaR, color="green", linestyle="--", label="Monte Carlo VaR")
|
| 99 |
+
ax1.set_title("Distribución de Retornos del Portafolio")
|
| 100 |
+
ax1.legend()
|
| 101 |
+
st.pyplot(fig1)
|
| 102 |
+
|
| 103 |
+
# Gráfico 2: Serie de tiempo
|
| 104 |
+
fig2, ax2 = plt.subplots(figsize=(10, 6))
|
| 105 |
+
ax2.plot(portfolio_returns.index, portfolio_returns, color="purple", label="Portfolio Returns")
|
| 106 |
+
ax2.axhline(historical_VaR, color="red", linestyle="--", label="Historical VaR")
|
| 107 |
+
ax2.axhline(parametric_VaR, color="blue", linestyle="--", label="Parametric VaR")
|
| 108 |
+
ax2.axhline(mc_VaR, color="green", linestyle="--", label="Monte Carlo VaR")
|
| 109 |
+
ax2.set_title("Serie de tiempo de los retornos del portafolio")
|
| 110 |
+
ax2.legend()
|
| 111 |
+
st.pyplot(fig2)
|