import gradio as gr import pandas as pd import numpy as np import matplotlib.pyplot as plt import io import base64 # --- Helper Functions --- def plot_to_base64(fig): """Converts a matplotlib figure to a base64 encoded PNG image.""" buf = io.BytesIO() fig.savefig(buf, format='png') plt.close(fig) return base64.b64encode(buf.getvalue()).decode('utf-8') # 1. Data Ingestion def ingest_financial_data(file): """ Simulated ingestion of financial data. In a real application, this would parse various financial data formats, handle APIs (e.g., Yahoo Finance, Alpha Vantage), cleaning, etc. """ if file is None: return gr.Markdown("

Por favor, sube un archivo CSV o Excel.

") df = None try: if file.name.lower().endswith('.csv'): df = pd.read_csv(file.name) elif file.name.lower().endswith(('.xls', '.xlsx')): df = pd.read_excel(file.name) else: return gr.Markdown("

Formato de archivo no soportado. Sube un CSV o Excel.

") except Exception as e: return gr.Markdown(f"

Error al leer el archivo: {e}

") if df is not None: # Convert DataFrame info to string to display in markdown info_buffer = io.StringIO() df.info(buf=info_buffer) return gr.Markdown(f"""### Datos Cargados ({file.orig_name if hasattr(file, 'orig_name') else 'archivo'}) **Primeras 5 filas:** {df.head().to_markdown(index=False)} **Información básica:** ``` {info_buffer.getvalue()} ```""") else: return gr.Markdown("

No se pudieron cargar los datos.

") # 2. Time Series Forecasting def perform_forecasting(ticker_symbol: str, forecast_days: int): """ Placeholder for time series forecasting. A real implementation would use models like Prophet, ARIMA, LSTM, etc., and fetch historical data (e.g., via yfinance). """ if not ticker_symbol: return gr.Markdown("

Por favor, ingresa un símbolo de ticker.

") if forecast_days <= 0: return gr.Markdown("

Los días de pronóstico deben ser un número positivo.

") # Simulate some data dates = pd.date_range(end=pd.Timestamp.today(), periods=100, freq='D') values = np.random.randn(100).cumsum() + 100 # Add future dates for forecast future_dates = pd.date_range(start=dates[-1] + pd.Timedelta(days=1), periods=forecast_days, freq='D') forecast_values = np.random.randn(forecast_days).cumsum() * 0.5 + values[-1] # Simple random walk forecast fig, ax = plt.subplots(figsize=(10, 6)) ax.plot(dates, values, label='Histórico') ax.plot(future_dates, forecast_values, label='Pronóstico (Simulado)', linestyle='--') ax.set_title(f'Pronóstico de {ticker_symbol} para {forecast_days} días (Simulado)') ax.set_xlabel('Fecha') ax.set_ylabel('Valor') ax.legend() plt.tight_layout() img_base64 = plot_to_base64(fig) return gr.Markdown(f"### Pronóstico para {ticker_symbol}\n\n"\ f"Se ha generado un pronóstico simulado para los próximos {forecast_days} días.\n\n"\ f"![Pronóstico](data:image/png;base64,{img_base64})\n\n"\ "

Nota: Esta es una simulación. Una implementación real requeriría la obtención de datos financieros y un modelo de pronóstico robusto.

") # 3. Sentiment Analysis def analyze_sentiment(text: str): """ Placeholder for sentiment analysis. A real implementation would use a pre-trained NLP model (e.g., from Hugging Face Transformers). """ if not text: return gr.Textbox(value="Por favor, ingresa texto para analizar el sentimiento.", interactive=False) # Simple keyword-based sentiment for demonstration text_lower = text.lower() sentiment = "Neutral" if "good" in text_lower or "buy" in text_lower or "strong" in text_lower or "profit" in text_lower or "crecimiento" in text_lower or "alza" in text_lower: sentiment = "Positivo" elif "bad" in text_lower or "sell" in text_lower or "weak" in text_lower or "loss" in text_lower or "caída" in text_lower or "baja" in text_lower: sentiment = "Negativo" return gr.Textbox(value=f"**Análisis de Sentimiento:** {sentiment}\n\n**Texto Analizado:**\n{text}\n\n

Nota: Este es un análisis de sentimiento simulado. Una implementación real usaría un modelo NLP.

", interactive=False) # 4. LLM Financial Copilot def llm_copilot_chat(message, history): """ Placeholder for an LLM-powered financial copilot. A real implementation would integrate with an actual LLM (e.g., OpenAI GPT, Google Gemini, local Hugging Face model). """ # Simulate LLM response message_lower = message.lower() if "precio de la acción" in message_lower or "cotización" in message_lower: response = "Como copiloto simulado, no puedo dar consejos financieros en tiempo real ni cotizaciones precisas. Pero puedo buscar información general sobre el mercado. ¿Qué acción te interesa?" elif "invertir" in message_lower or "inversión" in message_lower: response = "La inversión implica riesgos. Siempre es recomendable consultar a un asesor financiero certificado. ¿Hay algún sector que te interese explorar (de forma simulada)?" elif "hola" in message_lower or "hi" in message_lower: response = "¡Hola! Soy tu copiloto financiero simulado. ¿En qué puedo ayudarte hoy (recuerda que soy una simulación)?" else: response = f"Como copiloto financiero simulado, no puedo procesar consultas complejas de IA o dar consejos financieros reales. Mi respuesta a '{message}' sería muy general. Para un LLM real, se requeriría una API o un modelo dedicado.\n\n

Nota: Esta es una respuesta simulada de un LLM.

" return response # --- Gradio Interface --- with gr.Blocks(title="Plataforma de Inteligencia de Inversiones (Simulada)") as demo: gr.HTML("

📈 Plataforma de Inteligencia de Inversiones (Simulada) 💰

") gr.Markdown( "

"+ "Este es un prototipo para una plataforma de inteligencia de inversiones, combinando "+ "ingestión de datos, pronóstico temporal, análisis de sentimiento y un copiloto financiero con LLM. "+ "Las funcionalidades de pronóstico, sentimiento y LLM son simuladas en este ejemplo para demostrar la estructura."+ "

" ) # Define individual interfaces for each tab ingestion_interface = gr.Interface( fn=ingest_financial_data, inputs=gr.File(label="Sube tu archivo CSV o Excel de datos financieros", file_types=[".csv", ".xls", ".xlsx"]), outputs=gr.Markdown(label="Vista Previa de Datos"), title="Ingestión de Datos Financieros", # This title will appear on the tab live=False # Only run on button click ) forecasting_interface = gr.Interface( fn=perform_forecasting, inputs=[ gr.Textbox(label="Símbolo de Ticker (e.g., AAPL, MSFT)", placeholder="Ingresa un símbolo de ticker"), gr.Number(label="Días a Pronosticar", value=30, minimum=1, maximum=365) ], outputs=gr.Markdown(label="Resultado del Pronóstico"), title="Pronóstico Temporal (Simulado)", # This title will appear on the tab live=False # Only run on button click ) sentiment_interface = gr.Interface( fn=analyze_sentiment, inputs=gr.Textbox(label="Texto para Análisis de Sentimiento", placeholder="Pega una noticia financiera o un comentario aquí..."), outputs=gr.Textbox(label="Resultado del Sentimiento", interactive=False), title="Análisis de Sentimiento (Simulado)", # This title will appear on the tab live=False # Only run on button click ) # ChatInterface is already a type of Interface llm_copilot_interface = gr.ChatInterface( llm_copilot_chat, chatbot=gr.Chatbot(height=300, allow_tags=False), title="Copiloto Financiero con LLM (Simulado)", # This title will appear on the tab # fill_height=True # fill_height is not a recognized parameter for ChatInterface in all versions ) gr.TabbedInterface( [ ingestion_interface, forecasting_interface, sentiment_interface, llm_copilot_interface ] ) # To run in Colab, uncomment the following line if __name__ == "__main__": demo.launch(share=True) # share=True is often needed for Colab