Spaces:
Build error
Build error
A newer version of the Streamlit SDK is available:
1.54.0
🚀 Guía de MLOps - Investment Assistant
📋 Tabla de Contenidos
- Introducción
- Arquitectura MLOps
- Configuración
- Pipeline de Datos (DVC)
- Tracking de Modelos (MLflow)
- Monitoreo y Drift Detection
- Agentes con RAG
- Despliegue en Kubernetes
- Evaluación de Modelos
📖 Introducción
Este proyecto implementa un sistema completo de MLOps para el Investment Assistant, incluyendo:
- ✅ DVC: Versionado de datos y modelos
- ✅ MLflow: Tracking de experimentos y modelos
- ✅ RAG System: Agentes con Retrieval Augmented Generation
- ✅ Drift Detection: Detección de cambios en distribución de datos
- ✅ Kubernetes: Despliegue escalable y resiliente
- ✅ Monitoring: Métricas y alertas en tiempo real
🏗️ Arquitectura MLOps
┌─────────────────────────────────────────────────────────────┐
│ Investment Assistant │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ FastAPI │ │ Streamlit │ │ Agents │ │
│ │ Backend │◄───┤ Frontend │ │ with RAG │ │
│ └──────┬───────┘ └──────────────┘ └──────┬───────┘ │
│ │ │ │
│ ┌──────▼──────────────────────────────────────────▼──────┐ │
│ │ Monitoring & Drift Detection │ │
│ └──────┬─────────────────────────────────────────────────┘ │
│ │ │
│ ┌──────▼──────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ MLflow │ │ DVC │ │ Kubernetes │ │
│ │ Tracking │ │ Versioning │ │ Cluster │ │
│ └─────────────┘ └──────────────┘ └──────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
⚙️ Configuración
Prerrequisitos
# Instalar dependencias
pip install -r requirements.txt
# Instalar DVC
pip install dvc dvc-s3
# Instalar MLflow
pip install mlflow
Variables de Entorno
Crear archivo .env con:
# OpenAI
OPENAI_API_KEY=your-openai-key
OPENAI_MODEL=gpt-4
# Azure
AZURE_TEXT_ANALYTICS_ENDPOINT=https://...
AZURE_TEXT_ANALYTICS_KEY=your-key
# APIs
ALPHA_VANTAGE_API_KEY=your-key
# MLOps
MLFLOW_TRACKING_URI=http://localhost:5000
📊 Pipeline de Datos (DVC)
Inicializar DVC
# Inicializar repositorio DVC
dvc init
# Configurar remoto (opcional)
dvc remote add -d local ./dvc-cache
# O usar S3
dvc remote add -d s3 s3://your-bucket/dvc-cache
Ejecutar Pipeline
# Ejecutar pipeline completo
dvc repro
# Ejecutar etapa específica
dvc repro prepare_data
# Ver pipeline
dvc dag
# Ver métricas
dvc metrics show
Estructura de Datos
data/
├── raw/ # Datos crudos
├── processed/ # Datos procesados (DVC tracked)
│ ├── market_data.parquet
│ └── indicators.parquet
models/ # Modelos (DVC tracked)
│ ├── top_strategy_model.pkl
│ └── bottom_strategy_model.pkl
metrics/ # Métricas (DVC tracked)
│ ├── model_metrics.json
│ └── evaluation_metrics.json
🎯 Tracking de Modelos (MLflow)
Iniciar Servidor MLflow
# Servidor MLflow
mlflow server --host 0.0.0.0 --port 5000
# O usar Docker
docker run -p 5000:5000 ghcr.io/mlflow/mlflow:v2.11.1
Entrenar Modelos
# Entrenar modelos (registra automáticamente en MLflow)
python scripts/train_model.py
Ver Experimentos
Abrir en navegador: http://localhost:5000
Registrar Modelo
import mlflow
# En train_model.py ya está incluido
mlflow.sklearn.log_model(model, "strategy_model")
Cargar Modelo para Producción
import mlflow.pyfunc
# Cargar modelo por versión
model = mlflow.pyfunc.load_model(
model_uri=f"runs:/{run_id}/strategy_model"
)
🔍 Monitoreo y Drift Detection
Inicializar Monitoreo
from src.monitoring.monitoring_service import MonitoringService
# Crear servicio de monitoreo
monitoring = MonitoringService(drift_threshold=0.15)
# Establecer baseline de referencia
reference_data = pd.read_parquet("data/processed/indicators.parquet")
monitoring.initialize_reference_baseline(reference_data)
Detectar Drift
# Obtener datos actuales
current_data = fetch_current_market_data()
# Detectar drift
drift_result = monitoring.drift_detector.detect_drift(current_data)
if drift_result["drift_detected"]:
print("⚠️ Drift detectado! Re-entrenar modelo recomendado.")
Obtener Health Report
# Reporte de salud del sistema
health = monitoring.get_health_report()
print(f"Status: {health['status']}")
print(f"Predictions 24h: {health['metrics']['predictions_last_24h']}")
print(f"Drift alerts: {health['metrics']['drift_alerts_last_7d']}")
🤖 Agentes con RAG
Inicializar Agente
from openai import OpenAI
from src.agents.investment_agent import InvestmentAgent
from src.agents.rag_system import RAGSystem
# Inicializar cliente OpenAI
openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# Crear sistema RAG
rag = RAGSystem(openai_client)
# Crear agente
agent = InvestmentAgent(openai_client, rag)
Usar Agente
# Chat con agente (usa RAG automáticamente)
response = agent.chat(
"¿Debería invertir en Bitcoin ahora?",
context={"market_data": current_market_data}
)
print(response)
# Análisis de estrategia con agente
analysis = agent.analyze_strategy(
symbol="SPY",
strategy_type="TOP",
market_data=market_data,
news_sentiment=sentiment
)
Agregar Conocimiento al RAG
# Agregar documentos al knowledge base
documents = [
{
"content": "Nueva estrategia de inversión...",
"metadata": {"source": "research", "type": "strategy"}
}
]
rag.add_documents(documents)
☸️ Despliegue en Kubernetes
Prerrequisitos
- Kubernetes cluster (local con Minikube o cloud)
kubectlconfigurado- Docker images construidas
Construir Imágenes
# Construir imagen Docker
docker build -t investment-assistant:latest .
# O usar docker-compose
docker-compose build
Aplicar Configuraciones
# Crear secrets (ajustar valores primero)
kubectl apply -f kubernetes/secrets.yaml
# Crear PVCs
kubectl apply -f kubernetes/pvc.yaml
# Crear servicios
kubectl apply -f kubernetes/service.yaml
# Crear deployments
kubectl apply -f kubernetes/deployment.yaml
# Crear HPA
kubectl apply -f kubernetes/hpa.yaml
Verificar Despliegue
# Ver pods
kubectl get pods
# Ver servicios
kubectl get services
# Ver logs
kubectl logs -f deployment/investment-assistant-api
# Ver HPA
kubectl get hpa
Escalar Manualmente
# Escalar deployment
kubectl scale deployment investment-assistant-api --replicas=5
📈 Evaluación de Modelos
Evaluación Básica
# Evaluar modelos entrenados
python scripts/evaluate_model.py
Evaluación Comprehensiva
# Evaluación con drift detection y métricas completas
python scripts/evaluate_model_enhanced.py
Ejecutar Tests
# Todos los tests
pytest
# Tests unitarios
pytest tests/test_agents.py tests/test_monitoring.py
# Tests de integración
pytest tests/test_integration.py
# Con coverage
pytest --cov=src --cov-report=html
📊 Métricas y Reportes
Ver Métricas DVC
# Mostrar métricas
dvc metrics show
# Comparar métricas entre versiones
dvc metrics diff HEAD~1
Ver Métricas MLflow
Abrir UI de MLflow: http://localhost:5000
Métricas de Monitoreo
# Obtener métricas recientes
recent_metrics = monitoring.metrics_collector.get_recent_metrics(hours=24)
# Estadísticas de rendimiento
stats = monitoring.metrics_collector.calculate_performance_stats(strategy_type="TOP")
🔧 Mejores Prácticas
Versionado de Datos
- Siempre versionar datos con DVC antes de entrenar
- Tag releases importantes:
dvc tag v1.0 - Comparar versiones:
dvc diff v1.0 v1.1
Tracking de Experimentos
- Registrar todos los parámetros en MLflow
- Log métricas durante entrenamiento
- Tag runs importantes (production, baseline, etc.)
Monitoreo Continuo
- Establecer baseline con datos históricos
- Monitorear drift diariamente
- Alertar cuando drift > threshold
Despliegue
- Usar versiones específicas de imágenes
- Health checks en todos los servicios
- Resource limits apropiados
- HPA para escalado automático
🆘 Troubleshooting
DVC Issues
# Verificar cache
dvc cache dir
# Limpiar cache
dvc cache cleanup
# Forzar reproducción
dvc repro --force
MLflow Issues
# Verificar servidor
curl http://localhost:5000/health
# Resetear base de datos (¡cuidado!)
mlflow db upgrade
Kubernetes Issues
# Ver eventos
kubectl get events --sort-by=.metadata.creationTimestamp
# Describir pod
kubectl describe pod <pod-name>
# Ver logs
kubectl logs <pod-name> --previous
📚 Recursos Adicionales
Versión: 1.0
Última actualización: {{ fecha }}