Forecasting / app.py
AngelGabrielTroncoso's picture
Update app.py
e3576fb verified
Raw
History Blame Contribute Delete
8.82 kB
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("<p style='color:red;'>Por favor, sube un archivo CSV o Excel.</p>")
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("<p style='color:red;'>Formato de archivo no soportado. Sube un CSV o Excel.</p>")
except Exception as e:
return gr.Markdown(f"<p style='color:red;'>Error al leer el archivo: {e}</p>")
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("<p style='color:red;'>No se pudieron cargar los datos.</p>")
# 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("<p style='color:red;'>Por favor, ingresa un s铆mbolo de ticker.</p>")
if forecast_days <= 0:
return gr.Markdown("<p style='color:red;'>Los d铆as de pron贸stico deben ser un n煤mero positivo.</p>")
# 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"\
"<p style='color:#888;'><b>Nota:</b> Esta es una simulaci贸n. Una implementaci贸n real requerir铆a la obtenci贸n de datos financieros y un modelo de pron贸stico robusto.</p>")
# 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<p style='color:#888;'><b>Nota:</b> Este es un an谩lisis de sentimiento simulado. Una implementaci贸n real usar铆a un modelo NLP.</p>", 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<p style='color:#888;'><b>Nota:</b> Esta es una respuesta simulada de un LLM.</p>"
return response
# --- Gradio Interface ---
with gr.Blocks(title="Plataforma de Inteligencia de Inversiones (Simulada)") as demo:
gr.HTML("<h1 style='text-align: center; color: #333;'>馃搱 Plataforma de Inteligencia de Inversiones (Simulada) 馃挵</h1>")
gr.Markdown(
"<p style='text-align: center; font-size: 1.1em; color: #555;'>"+
"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. "+
"<b>Las funcionalidades de pron贸stico, sentimiento y LLM son simuladas en este ejemplo</b> para demostrar la estructura."+
"</p>"
)
# 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