---
id: "ET-PFM-010"
title: "Arquitectura General del Sistema Portfolio Manager"
type: "Technical Specification"
status: "Done"
priority: "Alta"
epic: "OQI-008"
project: "trading-platform"
version: "1.0.0"
created_date: "2026-01-28"
updated_date: "2026-01-28"
---

# ET-PFM-010: Arquitectura General del Sistema Portfolio Manager

**Epica:** OQI-008 - Portfolio Manager
**Version:** 1.0
**Fecha:** 2026-01-28
**Estado:** Planificado

---

## 1. Vision General

El Portfolio Manager es un sistema integral de gestion de carteras de inversion a largo plazo que permite a los usuarios administrar multiples estrategias de inversion, realizar rebalanceo automatico, y proyectar metas financieras.

### 1.1 Objetivos del Sistema

| Objetivo | Descripcion | Metrica de Exito |
|----------|-------------|------------------|
| Multi-estrategia | Gestionar diferentes perfiles de riesgo | 5+ perfiles predefinidos |
| Optimizacion | Portfolio basado en Modern Portfolio Theory | Sharpe > benchmark |
| Rebalanceo | Automatizacion inteligente | Drift < 5% mantenido |
| Proyecciones | Simulaciones Monte Carlo | 10,000 escenarios |
| Reportes | Documentacion profesional | PDF, CSV, Excel |

---

## 2. Arquitectura de Alto Nivel

```
+--------------------------------------------------------------------------------+
|                           PORTFOLIO MANAGER SYSTEM                              |
+--------------------------------------------------------------------------------+
|                                                                                 |
|  +---------------------------------------------------------------------------+ |
|  |                           PRESENTATION LAYER                               | |
|  |  +------------------+  +------------------+  +------------------------+    | |
|  |  | Portfolio        |  | Rebalance        |  | Goals &                |    | |
|  |  | Dashboard        |  | Interface        |  | Projections            |    | |
|  |  +------------------+  +------------------+  +------------------------+    | |
|  |                                                                           | |
|  |  +------------------+  +------------------+  +------------------------+    | |
|  |  | Risk Metrics     |  | Reports          |  | Stress Test            |    | |
|  |  | Panel            |  | Generator        |  | Simulator              |    | |
|  |  +------------------+  +------------------+  +------------------------+    | |
|  +---------------------------------------------------------------------------+ |
|                                    |                                           |
|                                    | REST API + WebSocket                      |
|                                    v                                           |
|  +---------------------------------------------------------------------------+ |
|  |                           BUSINESS LAYER                                   | |
|  |                                                                           | |
|  |  +-------------------+     +-------------------+     +------------------+ | |
|  |  | Portfolio Service |     | Metrics Service   |     | Goals Service    | | |
|  |  |                   |     |                   |     |                  | | |
|  |  | - Summary         |     | - TWR/MWR         |     | - Create         | | |
|  |  | - Positions       |     | - Sharpe/Sortino  |     | - Project        | | |
|  |  | - History         |     | - VaR/CVaR        |     | - Track          | | |
|  |  | - Snapshots       |     | - Drawdown        |     | - Simulate       | | |
|  |  +-------------------+     +-------------------+     +------------------+ | |
|  |                                                                           | |
|  |  +-------------------+     +-------------------+     +------------------+ | |
|  |  | Rebalance Engine  |     | Stress Test       |     | Report Service   | | |
|  |  |                   |     | Engine            |     |                  | | |
|  |  | - Drift Detection |     | - Scenarios       |     | - PDF Generator  | | |
|  |  | - Plan Generator  |     | - Impact Calc     |     | - Tax Reports    | | |
|  |  | - Executor        |     | - Monte Carlo     |     | - Export         | | |
|  |  +-------------------+     +-------------------+     +------------------+ | |
|  +---------------------------------------------------------------------------+ |
|                                    |                                           |
|                                    | TypeORM / Prisma                          |
|                                    v                                           |
|  +---------------------------------------------------------------------------+ |
|  |                           DATA LAYER                                       | |
|  |                                                                           | |
|  |  +-------------------+     +-------------------+     +------------------+ | |
|  |  | PostgreSQL        |     | Redis             |     | External APIs    | | |
|  |  |                   |     |                   |     |                  | | |
|  |  | - portfolios      |     | - Session cache   |     | - Market Data    | | |
|  |  | - positions       |     | - Metrics cache   |     | - Prices         | | |
|  |  | - transactions    |     | - Rate limiting   |     | - Benchmarks     | | |
|  |  | - goals           |     | - Real-time data  |     | - Economic       | | |
|  |  | - risk_metrics    |     +-------------------+     +------------------+ | |
|  |  +-------------------+                                                     | |
|  +---------------------------------------------------------------------------+ |
|                                                                                 |
+--------------------------------------------------------------------------------+
```

---

## 3. Componentes Principales

### 3.1 Frontend (React + TypeScript)

| Componente | Descripcion | Archivo |
|------------|-------------|---------|
| PortfolioDashboard | Vista principal del portfolio | `Portfolio.tsx` |
| PositionsTable | Tabla de posiciones | `PositionsTable.tsx` |
| AllocationChart | Grafico donut de asignacion | `AllocationChart.tsx` |
| PerformanceChart | Grafico de rendimiento | `PerformanceChart.tsx` |
| RiskMetricsPanel | Panel de metricas de riesgo | `RiskMetricsPanel.tsx` |
| RebalanceModal | Modal de rebalanceo | `RebalanceModal.tsx` |
| StressTestSimulator | Simulador de stress test | `StressTestSimulator.tsx` |
| GoalTracker | Seguimiento de metas | `GoalTracker.tsx` |
| ReportGenerator | Generador de reportes | `ReportGenerator.tsx` |

### 3.2 Backend (Express.js + TypeScript)

| Servicio | Responsabilidad | Endpoints |
|----------|-----------------|-----------|
| PortfolioService | CRUD de portfolios | `/api/portfolio/*` |
| PositionService | Gestion de posiciones | `/api/portfolio/positions/*` |
| MetricsService | Calculo de metricas | `/api/portfolio/metrics/*` |
| RebalanceService | Motor de rebalanceo | `/api/portfolio/rebalance/*` |
| GoalService | Gestion de metas | `/api/goals/*` |
| StressTestService | Stress testing | `/api/portfolio/stress-test/*` |
| ReportService | Generacion de reportes | `/api/portfolio/reports/*` |
| TaxReportService | Reportes fiscales | `/api/portfolio/tax/*` |

### 3.3 Database (PostgreSQL)

| Tabla | Descripcion | Relaciones |
|-------|-------------|------------|
| `portfolios` | Portfolios de usuarios | 1:N positions |
| `positions` | Posiciones activas | N:1 portfolio |
| `transactions` | Historial de transacciones | N:1 portfolio |
| `portfolio_snapshots` | Snapshots diarios | N:1 portfolio |
| `investment_goals` | Metas de inversion | N:1 user |
| `goal_contributions` | Contribuciones a metas | N:1 goal |
| `target_allocations` | Asignaciones objetivo | N:1 portfolio |
| `rebalance_history` | Historial de rebalanceo | N:1 portfolio |
| `risk_metrics` | Metricas de riesgo calculadas | N:1 portfolio |
| `stress_test_results` | Resultados de stress tests | N:1 portfolio |
| `reports` | Reportes generados | N:1 portfolio |

---

## 4. Flujos de Datos

### 4.1 Flujo de Carga del Dashboard

```
Usuario accede /portfolio
        |
        v
[Frontend] GET /api/portfolio/{id}
        |
        v
[PortfolioService] getPortfolioSummary()
        |
        +---> [PositionService] getPositions()
        |
        +---> [MetricsService] calculateMetrics()
        |
        +---> [Cache] Redis (TTL: 15s para precios)
        |
        v
[Response] PortfolioSummary + Positions + Metrics
        |
        v
[Frontend] Renderiza Dashboard
        |
        v
[WebSocket] Suscripcion a updates de precios
```

### 4.2 Flujo de Rebalanceo

```
Usuario solicita rebalanceo
        |
        v
[Frontend] GET /api/portfolio/rebalance/suggestions
        |
        v
[RebalanceService] calculateDeviation()
        |
        +---> Compara currentAllocation vs targetAllocation
        |
        +---> Calcula drift por cada activo
        |
        v
[RebalanceService] generatePlan()
        |
        +---> Determina ordenes: BUY/SELL
        |
        +---> Ordena: ventas primero (genera liquidez)
        |
        +---> Calcula costos estimados
        |
        v
[Response] RebalancePlan con ordenes sugeridas
        |
        v
[Frontend] Muestra preview al usuario
        |
        v
Usuario confirma
        |
        v
[Frontend] POST /api/portfolio/rebalance/execute
        |
        v
[RebalanceService] executePlan()
        |
        +---> [OrderService] createOrder() x N
        |
        v
[TransactionService] recordTransactions()
        |
        v
[Response] RebalanceResult (success/fail por orden)
```

### 4.3 Flujo de Proyeccion Monte Carlo

```
Usuario solicita proyeccion de meta
        |
        v
[Frontend] POST /api/goals/{id}/projection
        |
        v
[GoalProjectionService] calculateProjection()
        |
        +---> Obtiene parametros:
        |     - current_amount
        |     - monthly_contribution
        |     - expected_return
        |     - target_date
        |
        +---> Ejecuta simulacion Monte Carlo
        |     - 10,000 escenarios
        |     - Distribucion normal de retornos
        |     - Random walk
        |
        v
[Response] GoalProjection
        |
        +---> projectedValue
        +---> probability_of_success
        +---> percentiles (P10, P50, P90)
        +---> requiredContribution (para alcanzar meta)
        |
        v
[Frontend] Renderiza grafico de proyeccion
```

---

## 5. Integraciones Externas

### 5.1 Market Data Providers

| Proveedor | Uso | Frecuencia |
|-----------|-----|------------|
| Binance API | Precios crypto | Real-time |
| Alpha Vantage | Datos fundamentales | Diario |
| Yahoo Finance | Benchmarks | Diario |
| TradingView (futuro) | Charts avanzados | Real-time |

### 5.2 Servicios Internos

| Servicio | Puerto | Integracion |
|----------|--------|-------------|
| MCP-Investment | 3093 | Cuentas de inversion |
| MCP-Wallet | 3090 | Balance de wallet |
| MCP-Auth | 3095 | Autenticacion |
| ML-Engine | 3083 | Predicciones (futuro) |

---

## 6. Seguridad

### 6.1 Autenticacion y Autorizacion

- JWT Bearer tokens
- Refresh token rotation
- Rate limiting: 100 req/min por usuario
- Verificacion de ownership en cada request

### 6.2 Validacion de Datos

```typescript
// Ejemplo: validacion de orden de rebalanceo
const RebalanceOrderSchema = z.object({
  portfolioId: z.string().uuid(),
  orders: z.array(z.object({
    symbol: z.string().min(1).max(10),
    action: z.enum(['BUY', 'SELL']),
    amount: z.number().positive().max(1000000),
  })),
  dryRun: z.boolean().default(false),
});
```

### 6.3 Audit Trail

- Todas las transacciones registradas
- Logs de acceso a datos sensibles
- Historial de cambios de configuracion

---

## 7. Escalabilidad

### 7.1 Caching Strategy

| Dato | TTL | Estrategia |
|------|-----|------------|
| Precios | 15s | Write-through |
| Metricas basicas | 1 min | Lazy load |
| Metricas avanzadas | 1 hora | Background job |
| Snapshots | 24 horas | Scheduled job |

### 7.2 Background Jobs

| Job | Frecuencia | Descripcion |
|-----|------------|-------------|
| SnapshotJob | Diario 00:00 UTC | Captura estado del portfolio |
| MetricsJob | Cada 1 hora | Recalcula metricas avanzadas |
| AlertsJob | Cada 5 min | Verifica drift y envia alertas |
| ReportJob | Bajo demanda | Genera reportes PDF |

---

## 8. Metricas de Rendimiento

### 8.1 SLAs

| Operacion | Target | Max |
|-----------|--------|-----|
| Dashboard load | < 1s | 2s |
| Calculo de metricas | < 500ms | 1s |
| Simulacion Monte Carlo | < 3s | 5s |
| Generacion de PDF | < 10s | 30s |

### 8.2 Limites del Sistema

| Recurso | Limite | Razon |
|---------|--------|-------|
| Posiciones por portfolio | 100 | Performance de calculos |
| Escenarios Monte Carlo | 10,000 | Balance precision/tiempo |
| Historial de transacciones | 10,000 | Paginacion requerida |
| Tamanio de reporte PDF | 10 MB | Limite de descarga |

---

## 9. Stack Tecnologico Detallado

### 9.1 Frontend

| Tecnologia | Version | Uso |
|------------|---------|-----|
| React | 18.x | Framework UI |
| TypeScript | 5.x | Tipado estatico |
| Zustand | 4.x | State management |
| TanStack Query | 5.x | Data fetching |
| Recharts | 2.x | Graficos |
| TailwindCSS | 3.x | Estilos |
| Zod | 3.x | Validacion schemas |

### 9.2 Backend

| Tecnologia | Version | Uso |
|------------|---------|-----|
| Node.js | 20.x LTS | Runtime |
| Express.js | 5.x | Framework HTTP |
| TypeScript | 5.x | Tipado estatico |
| TypeORM | 0.3.x | ORM |
| Bull | 4.x | Job queues |
| Node-cron | 3.x | Scheduled jobs |
| PDFKit | 0.14.x | Generacion PDF |

### 9.3 Infraestructura

| Tecnologia | Version | Uso |
|------------|---------|-----|
| PostgreSQL | 16.x | Database principal |
| Redis | 7.x | Cache + queues |
| Docker | 24.x | Contenedores |
| Nginx | 1.25.x | Reverse proxy |

---

## 10. Referencias

- [ET-PFM-001: Arquitectura Dashboard](./ET-PFM-001-arquitectura-dashboard.md)
- [ET-PFM-002: Calculo de Metricas](./ET-PFM-002-calculo-metricas.md)
- [ET-PFM-003: Stress Testing](./ET-PFM-003-stress-testing.md)
- [ET-PFM-004: Motor de Rebalanceo](./ET-PFM-004-motor-rebalanceo.md)
- [ET-PFM-007: Motor de Metas](./ET-PFM-007-motor-metas.md)
- [TRACEABILITY.yml](../implementacion/TRACEABILITY.yml)

---

*Especificacion tecnica - Sistema NEXUS*
