creame una pagina donde aparezcan diferentes gaps que ha hecho a lo largo de un periodo de tiempo en concreto que yo te voy a dar de diferentes ticker de acciones y muestrame su valor en dolares tanto en el high delñ premarket, en el open, el hihg del open, el low del open y el cierre de sesion
To upload files, please first save the app
import streamlit as st
import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime, timedelta
st.title("📊 Stock Gaps Analyzer")
# Sidebar para la selección de parámetros
st.sidebar.header("Parámetros de búsqueda")
# Input para los tickers
tickers_input = st.sidebar.text_area(
"Introduce los tickers (separados por coma):",
value="AAPL,MSFT,GOOGL",
help="Ejemplo: AAPL,MSFT,GOOGL"
)
# Selección de fechas
col1, col2 = st.sidebar.columns(2)
with col1:
start_date = st.date_input(
"Fecha inicial",
datetime.now() - timedelta(days=30)
)
with col2:
end_date = st.date_input(
"Fecha final",
datetime.now()
)
# Umbral para considerar un gap
gap_threshold = st.sidebar.slider(
"Umbral de gap (%)",
min_value=1.0,
max_value=10.0,
value=2.0,
step=0.1,
help="Porcentaje mÃnimo para considerar un gap"
)
if st.sidebar.button("Analizar Gaps"):
# Procesar lista de tickers
tickers = [ticker.strip() for ticker in tickers_input.split(",")]
# Contenedor para almacenar todos los gaps encontrados
all_gaps = []
for ticker in tickers:
with st.spinner(f'Analizando {ticker}...'):
try:
# Obtener datos
stock = yf.Ticker(ticker)
hist = stock.history(start=start_date, end=end_date, interval="1d")
# Obtener datos de premarket si están disponibles
premarket_high = hist.get('High', None)
# Calcular gaps
for i in range(1, len(hist)):
prev_close = hist['Close'][i-1]
open_price = hist['Open'][i]
high_price = hist['High'][i]
low_price = hist['Low'][i]
close_price = hist['Close'][i]
# Calcular el porcentaje de gap
gap_percentage = ((open_price - prev_close) / prev_close) * 100
# Si el gap supera el umbral (positivo o negativo)
if abs(gap_percentage) >= gap_threshold:
gap_info = {
'Fecha': hist.index[i].date(),
'Ticker': ticker,
'Gap %': round(gap_percentage, 2),
'Precio Previo Cierre': round(prev_close, 2),
'Precio Apertura': round(open_price, 2),
'Máximo DÃa': round(high_price, 2),
'MÃnimo DÃa': round(low_price, 2),
'Precio Cierre': round(close_price, 2),
}
all_gaps.append(gap_info)
except Exception as e:
st.error(f"Error al procesar {ticker}: {str(e)}")
if all_gaps:
# Convertir a DataFrame
gaps_df = pd.DataFrame(all_gaps)
# Ordenar por fecha y tamaño de gap
gaps_df = gaps_df.sort_values(['Fecha', 'Gap %'], ascending=[False, False])
# Mostrar tabla de gaps
st.subheader("Gaps Encontrados")
st.dataframe(gaps_df, use_container_width=True)
# Crear gráfico de dispersión de gaps
fig = go.Figure()
for ticker in gaps_df['Ticker'].unique():
ticker_data = gaps_df[gaps_df['Ticker'] == ticker]
fig.add_trace(go.Scatter(
x=ticker_data['Fecha'],
y=ticker_data['Gap %'],
mode='markers',
name=ticker,
text=[
f"Ticker: {ticker}<br>"
f"Fecha: {fecha}<br>"
f"Gap: {gap}%<br>"
f"Apertura: ${open_price}<br>"
f"Cierre: ${close}"
for fecha, gap, open_price, close in zip(
ticker_data['Fecha'],
ticker_data['Gap %'],
ticker_data['Precio Apertura'],
ticker_data['Precio Cierre']
)
],
hovertemplate="%{text}<extra></extra>"
))
fig.update_layout(
title="Distribución de Gaps por Fecha",
xaxis_title="Fecha",
yaxis_title="Gap (%)",
hovermode='closest'
)
st.plotly_chart(fig, use_container_width=True)
# EstadÃsticas de gaps
st.subheader("EstadÃsticas de Gaps")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Total Gaps", len(gaps_df))
with col2:
st.metric("Gap Promedio", f"{gaps_df['Gap %'].mean():.2f}%")
with col3:
st.metric("Gap Máximo", f"{gaps_df['Gap %'].max():.2f}%")
else:
st.info("No se encontraron gaps que cumplan con el criterio establecido.")
else:
st.info("👈 Configura los parámetros en el panel lateral y haz clic en 'Analizar Gaps' para comenzar.")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?