Update app.py
Browse files
app.py
CHANGED
|
@@ -99,9 +99,8 @@ if "tickers" in st.session_state:
|
|
| 99 |
|
| 100 |
st.markdown(f"**Suma actual:** {total_weight:.2f}%")
|
| 101 |
|
| 102 |
-
# ✅ Botón para ajustar automáticamente
|
| 103 |
if st.button("Ajustar automáticamente"):
|
| 104 |
-
fixed_index = 0
|
| 105 |
fixed_weight = weight_inputs[fixed_index]
|
| 106 |
remaining_weight = 100.0 - fixed_weight
|
| 107 |
rest = tickers[1:]
|
|
@@ -109,7 +108,6 @@ if "tickers" in st.session_state:
|
|
| 109 |
st.session_state[f"weight_{t}"] = round(remaining_weight / (len(tickers) - 1), 2)
|
| 110 |
st.experimental_rerun()
|
| 111 |
|
| 112 |
-
# Validación de suma
|
| 113 |
if abs(total_weight - 100.0) > 0.01:
|
| 114 |
st.warning("⚠️ La suma de los pesos debe ser exactamente 100%.")
|
| 115 |
else:
|
|
@@ -118,32 +116,40 @@ if "tickers" in st.session_state:
|
|
| 118 |
start_date = fecha_inicio.strftime("%Y-%m-%d")
|
| 119 |
end_date = datetime.datetime.today().strftime("%Y-%m-%d")
|
| 120 |
|
|
|
|
| 121 |
data = yf.download(tickers, start=start_date, end=end_date)["Close"]
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
st.markdown(f"**Suma actual:** {total_weight:.2f}%")
|
| 101 |
|
|
|
|
| 102 |
if st.button("Ajustar automáticamente"):
|
| 103 |
+
fixed_index = 0
|
| 104 |
fixed_weight = weight_inputs[fixed_index]
|
| 105 |
remaining_weight = 100.0 - fixed_weight
|
| 106 |
rest = tickers[1:]
|
|
|
|
| 108 |
st.session_state[f"weight_{t}"] = round(remaining_weight / (len(tickers) - 1), 2)
|
| 109 |
st.experimental_rerun()
|
| 110 |
|
|
|
|
| 111 |
if abs(total_weight - 100.0) > 0.01:
|
| 112 |
st.warning("⚠️ La suma de los pesos debe ser exactamente 100%.")
|
| 113 |
else:
|
|
|
|
| 116 |
start_date = fecha_inicio.strftime("%Y-%m-%d")
|
| 117 |
end_date = datetime.datetime.today().strftime("%Y-%m-%d")
|
| 118 |
|
| 119 |
+
# 🛡️ Validar datos antes de continuar
|
| 120 |
data = yf.download(tickers, start=start_date, end=end_date)["Close"]
|
| 121 |
+
|
| 122 |
+
if data.empty or data.isnull().all().all():
|
| 123 |
+
st.error("No se encontraron datos históricos para la fecha seleccionada. Intenta con otra fecha.")
|
| 124 |
+
else:
|
| 125 |
+
data = data.dropna()
|
| 126 |
+
returns = data.pct_change().dropna()
|
| 127 |
+
portfolio_returns = returns.dot(weights)
|
| 128 |
+
|
| 129 |
+
if portfolio_returns.empty:
|
| 130 |
+
st.error("No se pudieron calcular retornos del portafolio. Revisa los datos descargados.")
|
| 131 |
+
else:
|
| 132 |
+
tail_prob = 1 - confidence_level
|
| 133 |
+
historical_VaR = np.percentile(portfolio_returns, tail_prob * 100)
|
| 134 |
+
mean_ret = portfolio_returns.mean()
|
| 135 |
+
std_ret = portfolio_returns.std()
|
| 136 |
+
z_score = norm.ppf(tail_prob)
|
| 137 |
+
parametric_VaR = mean_ret + z_score * std_ret
|
| 138 |
+
simulated_returns = np.random.normal(mean_ret, std_ret, 10000)
|
| 139 |
+
mc_VaR = np.percentile(simulated_returns, tail_prob * 100)
|
| 140 |
+
historical_CVaR = portfolio_returns[portfolio_returns <= historical_VaR].mean()
|
| 141 |
+
|
| 142 |
+
st.subheader("Resultados del Portafolio:")
|
| 143 |
+
st.markdown(f"**Historical VaR:** {historical_VaR:.4%}")
|
| 144 |
+
st.markdown(f"**Parametric VaR:** {parametric_VaR:.4%}")
|
| 145 |
+
st.markdown(f"**Monte Carlo VaR:** {mc_VaR:.4%}")
|
| 146 |
+
st.markdown(f"**Historical CVaR (Expected Shortfall):** {historical_CVaR:.4%}")
|
| 147 |
+
|
| 148 |
+
fig1, ax1 = plt.subplots(figsize=(10, 6))
|
| 149 |
+
ax1.hist(portfolio_returns, bins=50, density=True, alpha=0.5)
|
| 150 |
+
ax1.axvline(historical_VaR, color="red", linestyle="--", label="Historical VaR")
|
| 151 |
+
ax1.axvline(parametric_VaR, color="blue", linestyle="--", label="Parametric VaR")
|
| 152 |
+
ax1.axvline(mc_VaR, color="green", linestyle="--", label="Monte Carlo VaR")
|
| 153 |
+
ax1.set_title("Distribución de Retornos del Portafolio")
|
| 154 |
+
ax1.legend()
|
| 155 |
+
st.pyplot(fig1)
|