ML Engine Updates: - Updated BTCUSD with Polygon API data (2024-2025): 215,699 new records - Re-trained all ML models: Attention (R²: 0.223), Base, Metamodel (87.3% confidence) - Backtest results: +176.71R profit with aggressive_filter strategy Documentation Consolidation: - Created docs/99-analisis/_MAP.md index with 13 new analysis documents - Consolidated inventories: removed duplicates from orchestration/inventarios/ - Updated ML_INVENTORY.yml with BTCUSD metrics and training results - Added execution reports: FASE11-BTCUSD, correction issues, alignment validation Architecture & Integration: - Updated all module documentation with NEXUS v3.4 frontmatter - Fixed _MAP.md indexes across all folders - Updated orchestration plans and traces Files: 229 changed, 5064 insertions(+), 1872 deletions(-) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
601 lines
13 KiB
Markdown
601 lines
13 KiB
Markdown
---
|
|
id: "SETUP-PYTHON"
|
|
title: "Configuración del Entorno Python - Trading Platform"
|
|
type: "Documentation"
|
|
project: "trading-platform"
|
|
version: "1.0.0"
|
|
updated_date: "2026-01-04"
|
|
---
|
|
|
|
# Configuración del Entorno Python - Trading Platform
|
|
|
|
Este documento describe cómo configurar y gestionar los entornos Python para todos los servicios de ML/AI en el proyecto Trading Platform.
|
|
|
|
## Índice
|
|
|
|
1. [Requisitos Previos](#requisitos-previos)
|
|
2. [Arquitectura de Servicios Python](#arquitectura-de-servicios-python)
|
|
3. [Instalación Rápida](#instalación-rápida)
|
|
4. [Instalación Manual por Servicio](#instalación-manual-por-servicio)
|
|
5. [Estructura de Directorios](#estructura-de-directorios)
|
|
6. [Principios SOLID Aplicados](#principios-solid-aplicados)
|
|
7. [Gestión de Dependencias](#gestión-de-dependencias)
|
|
8. [Troubleshooting](#troubleshooting)
|
|
|
|
## Requisitos Previos
|
|
|
|
### Software Requerido
|
|
|
|
- **Python**: 3.11 o superior
|
|
- **Miniconda**: Instalado en `~/miniconda3/`
|
|
- **Git**: Para clonar el repositorio
|
|
- **PostgreSQL**: 14 o superior (para servicios con DB)
|
|
- **Redis**: 7 o superior (para caching)
|
|
|
|
### Verificar Instalación de Miniconda
|
|
|
|
```bash
|
|
~/miniconda3/bin/conda --version
|
|
# Debe mostrar: conda 25.9.1 o superior
|
|
```
|
|
|
|
Si Miniconda no está instalado:
|
|
|
|
```bash
|
|
# Descargar Miniconda
|
|
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
|
|
|
|
# Instalar
|
|
bash Miniconda3-latest-Linux-x86_64.sh -b -p ~/miniconda3
|
|
|
|
# Inicializar (opcional)
|
|
~/miniconda3/bin/conda init bash
|
|
```
|
|
|
|
## Arquitectura de Servicios Python
|
|
|
|
El proyecto Trading Platform incluye tres servicios principales en Python:
|
|
|
|
### 1. Data Service (`apps/data-service/`)
|
|
|
|
**Propósito**: Sincronización de datos de mercado desde múltiples fuentes
|
|
|
|
**Stack tecnológico**:
|
|
- FastAPI (opcional, para API endpoints)
|
|
- asyncpg (PostgreSQL asíncrono)
|
|
- aiohttp (HTTP client asíncrono)
|
|
- APScheduler (jobs programados)
|
|
- websockets (datos en tiempo real)
|
|
|
|
**Puerto**: 8001
|
|
|
|
### 2. ML Engine (`apps/ml-engine/`)
|
|
|
|
**Propósito**: Modelos de predicción y análisis de trading
|
|
|
|
**Stack tecnológico**:
|
|
- PyTorch (deep learning)
|
|
- scikit-learn (ML tradicional)
|
|
- XGBoost (gradient boosting)
|
|
- FastAPI (API REST)
|
|
- ta (análisis técnico)
|
|
|
|
**Puerto**: 8002
|
|
|
|
### 3. LLM Agent (`apps/llm-agent/`)
|
|
|
|
**Propósito**: Agente de trading inteligente con Claude AI
|
|
|
|
**Stack tecnológico**:
|
|
- Anthropic SDK (Claude API)
|
|
- LangChain (framework LLM)
|
|
- ChromaDB (vector database para RAG)
|
|
- FastAPI (API REST)
|
|
- asyncpg (PostgreSQL asíncrono)
|
|
|
|
**Puerto**: 8003
|
|
|
|
## Instalación Rápida
|
|
|
|
### Opción 1: Configurar Todos los Servicios
|
|
|
|
```bash
|
|
cd /home/isem/workspace/projects/trading-platform
|
|
|
|
# Ejecutar script de setup
|
|
./scripts/setup-python-envs.sh all
|
|
```
|
|
|
|
### Opción 2: Configurar un Servicio Específico
|
|
|
|
```bash
|
|
# Solo data-service
|
|
./scripts/setup-python-envs.sh data-service
|
|
|
|
# Solo ml-engine
|
|
./scripts/setup-python-envs.sh ml-engine
|
|
|
|
# Solo llm-agent
|
|
./scripts/setup-python-envs.sh llm-agent
|
|
```
|
|
|
|
### Verificar Instalación
|
|
|
|
```bash
|
|
# Listar entornos creados
|
|
~/miniconda3/bin/conda env list | grep trading
|
|
|
|
# Debería mostrar:
|
|
# trading-data-service
|
|
# trading-ml-engine
|
|
# trading-llm-agent
|
|
```
|
|
|
|
## Instalación Manual por Servicio
|
|
|
|
### Data Service
|
|
|
|
```bash
|
|
cd /home/isem/workspace/projects/trading-platform/apps/data-service
|
|
|
|
# Crear entorno con conda
|
|
~/miniconda3/bin/conda env create -f environment.yml
|
|
|
|
# Activar entorno
|
|
conda activate trading-data-service
|
|
|
|
# Verificar instalación
|
|
python -c "import aiohttp, asyncpg; print('OK')"
|
|
|
|
# Configurar variables de entorno
|
|
cp .env.example .env
|
|
# Editar .env con tus configuraciones
|
|
|
|
# Ejecutar (modo desarrollo)
|
|
python -m src.main
|
|
```
|
|
|
|
### ML Engine
|
|
|
|
```bash
|
|
cd /home/isem/workspace/projects/trading-platform/apps/ml-engine
|
|
|
|
# Crear entorno con conda
|
|
~/miniconda3/bin/conda env create -f environment.yml
|
|
|
|
# Activar entorno
|
|
conda activate trading-ml-engine
|
|
|
|
# Verificar instalación de PyTorch
|
|
python -c "import torch; print(f'PyTorch: {torch.__version__}')"
|
|
|
|
# Verificar CUDA (si disponible)
|
|
python -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}')"
|
|
|
|
# Configurar variables de entorno
|
|
cp .env.example .env
|
|
# Editar .env con tus configuraciones
|
|
|
|
# Ejecutar API
|
|
uvicorn src.main:app --reload --host 0.0.0.0 --port 8002
|
|
```
|
|
|
|
### LLM Agent
|
|
|
|
```bash
|
|
cd /home/isem/workspace/projects/trading-platform/apps/llm-agent
|
|
|
|
# Crear entorno con conda
|
|
~/miniconda3/bin/conda env create -f environment.yml
|
|
|
|
# Activar entorno
|
|
conda activate trading-llm-agent
|
|
|
|
# Verificar instalación
|
|
python -c "import anthropic, langchain; print('OK')"
|
|
|
|
# Configurar variables de entorno
|
|
cp .env.example .env
|
|
# IMPORTANTE: Configurar ANTHROPIC_API_KEY en .env
|
|
|
|
# Ejecutar API
|
|
uvicorn src.main:app --reload --host 0.0.0.0 --port 8003
|
|
```
|
|
|
|
## Estructura de Directorios
|
|
|
|
Cada servicio Python sigue esta estructura basada en principios SOLID:
|
|
|
|
```
|
|
apps/{service}/
|
|
├── src/
|
|
│ ├── __init__.py # Package initialization
|
|
│ ├── main.py # Entry point (FastAPI app)
|
|
│ ├── config.py # Configuration (Pydantic Settings)
|
|
│ │
|
|
│ ├── models/ # Data models (Pydantic)
|
|
│ │ ├── __init__.py
|
|
│ │ ├── requests.py # Request models
|
|
│ │ ├── responses.py # Response models
|
|
│ │ └── domain.py # Domain models
|
|
│ │
|
|
│ ├── services/ # Business logic (SOLID)
|
|
│ │ ├── __init__.py
|
|
│ │ ├── interfaces.py # Abstract interfaces
|
|
│ │ └── implementations.py # Concrete implementations
|
|
│ │
|
|
│ ├── repositories/ # Data access layer
|
|
│ │ ├── __init__.py
|
|
│ │ ├── base.py # Base repository
|
|
│ │ └── {entity}_repo.py # Entity repositories
|
|
│ │
|
|
│ └── api/ # API routes
|
|
│ ├── __init__.py
|
|
│ ├── routes/ # Route handlers
|
|
│ └── dependencies.py # FastAPI dependencies
|
|
│
|
|
├── tests/ # Unit and integration tests
|
|
│ ├── __init__.py
|
|
│ ├── unit/
|
|
│ ├── integration/
|
|
│ └── conftest.py
|
|
│
|
|
├── config/ # Configuration files
|
|
│ └── settings.yml
|
|
│
|
|
├── environment.yml # Conda environment
|
|
├── requirements.txt # Pip requirements (backup)
|
|
├── pyproject.toml # Project metadata (optional)
|
|
└── .env.example # Environment variables template
|
|
```
|
|
|
|
## Principios SOLID Aplicados
|
|
|
|
### 1. Single Responsibility Principle (SRP)
|
|
|
|
Cada clase/módulo tiene una única responsabilidad:
|
|
|
|
```python
|
|
# config.py - Solo configuración
|
|
class Settings(BaseSettings):
|
|
database_url: str
|
|
api_key: str
|
|
|
|
# services/price_service.py - Solo lógica de precios
|
|
class PriceService:
|
|
def get_current_price(self, symbol: str) -> float:
|
|
pass
|
|
|
|
# repositories/price_repository.py - Solo acceso a datos
|
|
class PriceRepository:
|
|
def fetch_from_db(self, symbol: str) -> Price:
|
|
pass
|
|
```
|
|
|
|
### 2. Open/Closed Principle (OCP)
|
|
|
|
Extensible sin modificar código existente:
|
|
|
|
```python
|
|
# services/interfaces.py
|
|
from abc import ABC, abstractmethod
|
|
|
|
class DataSourceInterface(ABC):
|
|
@abstractmethod
|
|
async def fetch_data(self, symbol: str):
|
|
pass
|
|
|
|
# services/implementations.py
|
|
class AlphaVantageDataSource(DataSourceInterface):
|
|
async def fetch_data(self, symbol: str):
|
|
# Implementation
|
|
|
|
class YahooFinanceDataSource(DataSourceInterface):
|
|
async def fetch_data(self, symbol: str):
|
|
# Implementation
|
|
```
|
|
|
|
### 3. Liskov Substitution Principle (LSP)
|
|
|
|
Las implementaciones son sustituibles:
|
|
|
|
```python
|
|
# Cualquier DataSourceInterface puede ser usada
|
|
async def get_market_data(
|
|
source: DataSourceInterface,
|
|
symbol: str
|
|
):
|
|
return await source.fetch_data(symbol)
|
|
|
|
# Funciona con cualquier implementación
|
|
data1 = await get_market_data(AlphaVantageDataSource(), "AAPL")
|
|
data2 = await get_market_data(YahooFinanceDataSource(), "AAPL")
|
|
```
|
|
|
|
### 4. Interface Segregation Principle (ISP)
|
|
|
|
Interfaces específicas y pequeñas:
|
|
|
|
```python
|
|
# En lugar de una interfaz grande:
|
|
# class TradingService(ABC):
|
|
# @abstractmethod
|
|
# def get_price(self): pass
|
|
# @abstractmethod
|
|
# def execute_trade(self): pass
|
|
# @abstractmethod
|
|
# def send_notification(self): pass
|
|
|
|
# Mejor: interfaces segregadas
|
|
class PriceProvider(ABC):
|
|
@abstractmethod
|
|
def get_price(self): pass
|
|
|
|
class TradeExecutor(ABC):
|
|
@abstractmethod
|
|
def execute_trade(self): pass
|
|
|
|
class Notifier(ABC):
|
|
@abstractmethod
|
|
def send_notification(self): pass
|
|
```
|
|
|
|
### 5. Dependency Inversion Principle (DIP)
|
|
|
|
Depender de abstracciones, no de implementaciones concretas:
|
|
|
|
```python
|
|
# main.py
|
|
from services.interfaces import DataSourceInterface
|
|
from services.implementations import AlphaVantageDataSource
|
|
|
|
# Dependency Injection
|
|
def create_app(data_source: DataSourceInterface = None):
|
|
if data_source is None:
|
|
data_source = AlphaVantageDataSource()
|
|
|
|
app = FastAPI()
|
|
app.state.data_source = data_source
|
|
return app
|
|
```
|
|
|
|
## Gestión de Dependencias
|
|
|
|
### Actualizar Dependencias
|
|
|
|
```bash
|
|
# Activar entorno
|
|
conda activate trading-ml-engine
|
|
|
|
# Actualizar paquetes conda
|
|
conda update --all
|
|
|
|
# Actualizar paquetes pip
|
|
pip list --outdated
|
|
pip install --upgrade <package>
|
|
```
|
|
|
|
### Agregar Nueva Dependencia
|
|
|
|
1. **Editar environment.yml**:
|
|
|
|
```yaml
|
|
dependencies:
|
|
- nueva-libreria>=1.0.0
|
|
# o en pip:
|
|
- pip:
|
|
- nueva-libreria>=1.0.0
|
|
```
|
|
|
|
2. **Actualizar entorno**:
|
|
|
|
```bash
|
|
conda activate trading-ml-engine
|
|
conda env update -f environment.yml --prune
|
|
```
|
|
|
|
3. **Actualizar requirements.txt**:
|
|
|
|
```bash
|
|
pip freeze > requirements.txt
|
|
```
|
|
|
|
### Exportar Dependencias
|
|
|
|
```bash
|
|
# Exportar environment.yml actual
|
|
conda env export > environment.yml
|
|
|
|
# Exportar solo paquetes principales (recomendado)
|
|
conda env export --from-history > environment.yml
|
|
```
|
|
|
|
## Testing
|
|
|
|
### Ejecutar Tests
|
|
|
|
```bash
|
|
# Todos los tests
|
|
pytest
|
|
|
|
# Con coverage
|
|
pytest --cov=src --cov-report=html
|
|
|
|
# Tests específicos
|
|
pytest tests/unit/
|
|
pytest tests/integration/
|
|
|
|
# Test específico
|
|
pytest tests/unit/test_price_service.py
|
|
```
|
|
|
|
### Estructura de Tests
|
|
|
|
```python
|
|
# tests/unit/test_price_service.py
|
|
import pytest
|
|
from src.services.price_service import PriceService
|
|
|
|
@pytest.fixture
|
|
def price_service():
|
|
return PriceService()
|
|
|
|
def test_get_current_price(price_service):
|
|
price = price_service.get_current_price("AAPL")
|
|
assert price > 0
|
|
```
|
|
|
|
## Troubleshooting
|
|
|
|
### Problema: Conda no encontrado
|
|
|
|
```bash
|
|
# Verificar instalación
|
|
ls -la ~/miniconda3/bin/conda
|
|
|
|
# Si no existe, reinstalar Miniconda
|
|
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
|
|
bash Miniconda3-latest-Linux-x86_64.sh -b -p ~/miniconda3
|
|
```
|
|
|
|
### Problema: Conflictos de dependencias
|
|
|
|
```bash
|
|
# Eliminar entorno y recrear
|
|
conda env remove -n trading-ml-engine
|
|
conda env create -f environment.yml
|
|
```
|
|
|
|
### Problema: PyTorch no detecta CUDA
|
|
|
|
```bash
|
|
# Verificar CUDA
|
|
nvidia-smi
|
|
|
|
# Reinstalar PyTorch con CUDA
|
|
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
|
|
```
|
|
|
|
### Problema: Import errors
|
|
|
|
```bash
|
|
# Verificar que estás en el entorno correcto
|
|
conda env list
|
|
|
|
# Activar entorno correcto
|
|
conda activate trading-ml-engine
|
|
|
|
# Verificar instalación del paquete
|
|
pip list | grep <package>
|
|
```
|
|
|
|
### Problema: Puerto en uso
|
|
|
|
```bash
|
|
# Verificar qué está usando el puerto
|
|
lsof -i :8002
|
|
|
|
# Matar proceso
|
|
kill -9 <PID>
|
|
|
|
# O usar otro puerto
|
|
uvicorn src.main:app --port 8004
|
|
```
|
|
|
|
## Comandos Útiles
|
|
|
|
### Gestión de Entornos
|
|
|
|
```bash
|
|
# Listar entornos
|
|
conda env list
|
|
|
|
# Activar entorno
|
|
conda activate trading-ml-engine
|
|
|
|
# Desactivar entorno
|
|
conda deactivate
|
|
|
|
# Eliminar entorno
|
|
conda env remove -n trading-ml-engine
|
|
|
|
# Clonar entorno
|
|
conda create --name trading-ml-engine-dev --clone trading-ml-engine
|
|
```
|
|
|
|
### Información del Entorno
|
|
|
|
```bash
|
|
# Listar paquetes instalados
|
|
conda list
|
|
|
|
# Información del entorno
|
|
conda info
|
|
|
|
# Revisar historial de instalación
|
|
conda list --revisions
|
|
```
|
|
|
|
### Limpieza
|
|
|
|
```bash
|
|
# Limpiar caché de conda
|
|
conda clean --all
|
|
|
|
# Limpiar paquetes no usados
|
|
conda clean --packages
|
|
|
|
# Limpiar caché de pip
|
|
pip cache purge
|
|
```
|
|
|
|
## Desarrollo
|
|
|
|
### Code Quality
|
|
|
|
```bash
|
|
# Format code
|
|
black src/
|
|
isort src/
|
|
|
|
# Lint
|
|
flake8 src/
|
|
|
|
# Type checking
|
|
mypy src/
|
|
```
|
|
|
|
### Pre-commit Hooks (Opcional)
|
|
|
|
```bash
|
|
# Instalar pre-commit
|
|
pip install pre-commit
|
|
|
|
# Instalar hooks
|
|
pre-commit install
|
|
|
|
# Ejecutar manualmente
|
|
pre-commit run --all-files
|
|
```
|
|
|
|
## Referencias
|
|
|
|
- [Conda User Guide](https://docs.conda.io/projects/conda/en/latest/user-guide/)
|
|
- [FastAPI Documentation](https://fastapi.tiangolo.com/)
|
|
- [PyTorch Documentation](https://pytorch.org/docs/)
|
|
- [Pydantic Documentation](https://docs.pydantic.dev/)
|
|
- [SOLID Principles in Python](https://realpython.com/solid-principles-python/)
|
|
|
|
## Soporte
|
|
|
|
Para preguntas o problemas:
|
|
|
|
1. Revisar la documentación del proyecto en `/docs`
|
|
2. Crear un issue en el repositorio
|
|
3. Contactar al equipo de desarrollo
|
|
|
|
---
|
|
|
|
Última actualización: 2025-12-05
|
|
Versión: 1.0.0
|