VicMata commited on
Commit
12b0b0e
·
verified ·
1 Parent(s): f0ca490

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -41
app.py CHANGED
@@ -76,50 +76,53 @@ confidence_percent = st.slider(
76
  )
77
  confidence_level = confidence_percent / 100
78
 
 
79
  if st.button("Identificar Tickers") and empresa_input:
80
- tickers = obtener_tickers_desde_nombres(empresa_input)
81
-
82
- if len(tickers) < 2:
83
- st.warning("Se requieren al menos dos tickers válidos.")
84
- st.stop()
85
  else:
86
- st.success(f"Tickers detectados: {', '.join(tickers)}")
87
-
88
- st.subheader("Asignar pesos a cada activo (la suma debe ser 100%)")
89
-
90
- # Inicializar los pesos en session_state si no existen
91
- for ticker in tickers:
92
- key = f"weight_{ticker}"
93
- if key not in st.session_state:
94
- st.session_state[key] = round(100 / len(tickers), 2)
95
-
96
- # Crear inputs para cada peso
97
- cols = st.columns(len(tickers))
98
- total_weight = 0
99
- weight_inputs = []
100
-
101
- for i, ticker in enumerate(tickers):
102
- with cols[i]:
103
- weight = st.number_input(
104
- f"{ticker} (%)",
105
- min_value=0.0,
106
- max_value=100.0,
107
- value=st.session_state[f"weight_{ticker}"],
108
- key=f"weight_{ticker}",
109
- step=0.1,
110
- format="%.2f"
111
- )
112
- weight_inputs.append(weight)
113
- total_weight += weight
114
-
115
- # Validar suma de 100%
116
- if abs(total_weight - 100.0) > 0.01:
117
- st.warning(f"⚠️ La suma de los pesos es {total_weight:.2f}%. Debe ser exactamente 100%.")
118
- st.stop()
119
-
120
- weights = np.array(weight_inputs) / 100
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  if st.button("Calcular VaR y CVaR"):
 
123
  start_date = fecha_inicio.strftime("%Y-%m-%d")
124
  end_date = datetime.datetime.today().strftime("%Y-%m-%d")
125
 
@@ -144,7 +147,7 @@ if st.button("Identificar Tickers") and empresa_input:
144
  st.markdown(f"**Monte Carlo VaR:** {mc_VaR:.4%}")
145
  st.markdown(f"**Historical CVaR (Expected Shortfall):** {historical_CVaR:.4%}")
146
 
147
- # Gráfico: Histograma con líneas VaR
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")
 
76
  )
77
  confidence_level = confidence_percent / 100
78
 
79
+ # ✅ Botón para detectar tickers
80
  if st.button("Identificar Tickers") and empresa_input:
81
+ tickers_detectados = obtener_tickers_desde_nombres(empresa_input)
82
+ if len(tickers_detectados) >= 2:
83
+ st.session_state["tickers"] = tickers_detectados
 
 
84
  else:
85
+ st.warning("Se requieren al menos dos tickers válidos.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
+ # ✅ Mostrar si ya se identificaron los tickers
88
+ if "tickers" in st.session_state:
89
+ tickers = st.session_state["tickers"]
90
+ st.success(f"Tickers detectados: {', '.join(tickers)}")
91
+ st.subheader("Asignar pesos a cada activo (la suma debe ser 100%)")
92
+
93
+ # Inicializar pesos si no existen
94
+ for ticker in tickers:
95
+ key = f"weight_{ticker}"
96
+ if key not in st.session_state:
97
+ st.session_state[key] = round(100 / len(tickers), 2)
98
+
99
+ # Inputs para los pesos
100
+ cols = st.columns(len(tickers))
101
+ total_weight = 0
102
+ weight_inputs = []
103
+
104
+ for i, ticker in enumerate(tickers):
105
+ with cols[i]:
106
+ weight = st.number_input(
107
+ f"{ticker} (%)",
108
+ min_value=0.0,
109
+ max_value=100.0,
110
+ value=st.session_state[f"weight_{ticker}"],
111
+ key=f"weight_{ticker}",
112
+ step=0.1,
113
+ format="%.2f"
114
+ )
115
+ st.session_state[f"weight_{ticker}"] = weight
116
+ weight_inputs.append(weight)
117
+ total_weight += weight
118
+
119
+ # Validación de suma
120
+ if abs(total_weight - 100.0) > 0.01:
121
+ st.warning(f"⚠️ La suma de los pesos es {total_weight:.2f}%. Debe ser exactamente 100%.")
122
+ else:
123
+ # Calcular VaR y CVaR
124
  if st.button("Calcular VaR y CVaR"):
125
+ weights = np.array(weight_inputs) / 100
126
  start_date = fecha_inicio.strftime("%Y-%m-%d")
127
  end_date = datetime.datetime.today().strftime("%Y-%m-%d")
128
 
 
147
  st.markdown(f"**Monte Carlo VaR:** {mc_VaR:.4%}")
148
  st.markdown(f"**Historical CVaR (Expected Shortfall):** {historical_CVaR:.4%}")
149
 
150
+ # Gráfico de VaR
151
  fig1, ax1 = plt.subplots(figsize=(10, 6))
152
  ax1.hist(portfolio_returns, bins=50, density=True, alpha=0.5)
153
  ax1.axvline(historical_VaR, color="red", linestyle="--", label="Historical VaR")