# Módulo Portfolio

**Epic:** OQI-008 - Portfolio Manager
**Progreso:** 20%
**Responsable:** Portfolio + Backend Teams

## Descripción

El módulo portfolio proporciona gestión completa de portfolios de criptomonedas con asset allocation, rebalancing automático, goal tracking, y visualización de performance. Los usuarios pueden crear múltiples portfolios con diferentes risk profiles (Conservative, Moderate, Aggressive), establecer target allocations, y recibir recomendaciones de rebalanceo basadas en desviaciones del target.

El sistema incluye real-time updates via WebSocket, custom charts implementados con Canvas API (sin librerías externas), y goal tracking con progress monitoring y projected completion dates.

## Componentes

### Páginas

- `PortfolioDashboard.tsx` - Dashboard principal con tabs (Resumen/Metas): portfolio selector, stats cards, allocation visualization, position table, rebalancing recommendations, performance chart, best/worst performers
- `CreatePortfolio.tsx` - Formulario de creación de portfolio: name input, risk profile selection (Conservative/Moderate/Aggressive), optional initial value simulation
- `EditAllocations.tsx` - Gestión de target allocations: current vs target %, real-time validation (must sum to 100%), add/remove assets, auto-balance function, visual allocation bars
- `CreateGoal.tsx` - Crear financial goals: preset templates (Emergency Fund, Vacation, Car, House, Retirement, Education), target amount/date, monthly contribution calculator

### Componentes Reutilizables

- `AllocationChart.tsx` - SVG-based donut chart con color-coded segments, center text con total portfolio value, interactive legend con percentage breakdown, hover tooltips
- `AllocationTable.tsx` - Detailed position breakdown table con 8 columns (Asset, Quantity, Value, Current %, Target %, Deviation, P&L, P&L %), asset icons, color-coded indicators
- `GoalCard.tsx` - Financial goal status card: status indicator (on_track/at_risk/behind), progress bar, target vs current amount, time remaining, projected completion, monthly contribution
- `PerformanceChart.tsx` - Canvas-based line chart con gradient fill, period selector (7D/1M/3M/1A/All), hover tooltip, grid lines, responsive sizing, dynamic color
- `RebalanceCard.tsx` - Rebalancing recommendations display: action priority sorting (high/medium/low), color-coded, buy/sell recommendations con USD amounts, deviation visualization, execution button

## Estructura de Carpetas

```
modules/portfolio/
├── components/
│   ├── AllocationChart.tsx
│   ├── AllocationTable.tsx
│   ├── GoalCard.tsx
│   ├── PerformanceChart.tsx
│   └── RebalanceCard.tsx
├── pages/
│   ├── PortfolioDashboard.tsx
│   ├── CreatePortfolio.tsx
│   ├── EditAllocations.tsx
│   └── CreateGoal.tsx
└── README.md
```

**Servicios y estado compartidos:**
- **Service:** `services/portfolio.service.ts` (Axios)
- **Store:** `stores/portfolioStore.ts` (Zustand con WebSocket support)
- **WebSocket:** `services/websocket.service.ts` (portfolioWS)

## APIs Consumidas

### Portfolio Management (Base URL: `/api/v1`)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/portfolio` | GET | Obtener todos los portfolios del usuario |
| `/portfolio/{id}` | GET | Detalle de portfolio individual |
| `/portfolio` | POST | Crear nuevo portfolio (params: name, riskProfile) |
| `/portfolio/{id}/allocations` | PUT | Actualizar asset allocations target |

### Rebalancing (2 endpoints)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/portfolio/{id}/rebalance` | GET | Obtener rebalancing recommendations (threshold 5%) |
| `/portfolio/{id}/rebalance` | POST | Ejecutar rebalancing orders |

### Statistics & Performance (3 endpoints)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/portfolio/{id}/stats` | GET | Estadísticas de portfolio (total value, day/week/month changes, best/worst performers) |
| `/portfolio/{id}/performance?period={period}` | GET | Historical performance (periods: week, month, 3months, year, all) |
| `/portfolio/{id}/performance/stats` | GET | Detailed performance statistics |

### Goals (4 endpoints)

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/portfolio/goals` | GET | Todos los goals del usuario |
| `/portfolio/goals` | POST | Crear nuevo goal (params: name, targetAmount, targetDate, monthlyContribution) |
| `/portfolio/goals/{id}/progress` | PUT | Actualizar goal progress |
| `/portfolio/goals/{id}` | DELETE | Eliminar goal |

## WebSocket Integration

### Portfolio WebSocket (URL: `ws://localhost:3000/ws/portfolio`)

**Events:**
- **Subscribe:** `portfolio:subscribe { portfolioId }`
- **Update:** `portfolio:update` receives `PortfolioUpdate` con totalValue, unrealizedPnl, allocations
- **Unsubscribe:** `portfolio:unsubscribe { portfolioId }`
- **Refresh:** `portfolio:refresh { portfolioId }`

**PortfolioUpdate Interface:**
```typescript
{
  portfolioId: string;
  totalValue: number;
  unrealizedPnl: number;
  unrealizedPnlPercent: number;
  allocations: Array<{
    asset: string;
    value: number;
    currentPercent: number;
    pnl: number;
    pnlPercent: number;
  }>;
  timestamp: string;
}
```

## Uso Rápido

```tsx
import {
  PortfolioDashboard,
  CreatePortfolio,
  EditAllocations,
  CreateGoal
} from '@/modules/portfolio';
import {
  usePortfolioStore,
  usePortfolios,
  useSelectedPortfolio,
  usePortfolioStats
} from '@/stores/portfolioStore';

// Uso en router
<Route path="/portfolio" element={<PortfolioDashboard />} />
<Route path="/portfolio/create" element={<CreatePortfolio />} />
<Route path="/portfolio/:id/allocations" element={<EditAllocations />} />
<Route path="/goals/create" element={<CreateGoal />} />

// Uso de store
function MyComponent() {
  const {
    portfolios,
    selectedPortfolio,
    stats,
    recommendations,
    fetchPortfolios,
    selectPortfolio,
    executeRebalance,
    updateAllocations,
    connectWebSocket
  } = usePortfolioStore();

  useEffect(() => {
    fetchPortfolios();
    connectWebSocket(); // Real-time updates
  }, []);

  const handleRebalance = async () => {
    await executeRebalance();
  };

  const handleUpdateAllocations = async (allocations) => {
    await updateAllocations(allocations);
  };

  return (
    <div>
      <h2>Portfolios: {portfolios.length}</h2>
      {selectedPortfolio && (
        <>
          <p>Total Value: ${stats?.totalValue}</p>
          <p>Day Change: {stats?.dayChangePercent}%</p>
          <p>Unrealized P&L: ${stats?.allTimeChange}</p>
          <button onClick={handleRebalance}>Execute Rebalance</button>
        </>
      )}
    </div>
  );
}

// Uso de selectors
function StatsComponent() {
  const portfolios = usePortfolios();
  const selectedPortfolio = useSelectedPortfolio();
  const stats = usePortfolioStats();

  return (
    <div>
      <p>Selected: {selectedPortfolio?.name}</p>
      <p>Total: ${stats?.totalValue}</p>
    </div>
  );
}
```

## Características Principales

### Portfolio Management
- Create múltiples portfolios
- 3 risk profiles: Conservative (low risk), Moderate (balanced), Aggressive (high risk)
- Asset allocation management con target % configuration
- 10 crypto assets soportados (BTC, ETH, USDT, SOL, LINK, AVAX, ADA, DOT, MATIC, UNI)

### Real-time Updates
- WebSocket integration para live price updates
- Auto-refresh de portfolio value y P&L
- Connection status indicator
- Graceful reconnection con exponential backoff

### Asset Allocation
- Visual donut chart (SVG) con asset breakdown
- Detailed table con current vs target allocation
- Deviation tracking (% off target)
- Color-coded indicators para over/under-allocated assets

### Rebalancing
- AI-powered recommendations basadas en 5% deviation threshold
- Priority levels: high (>10% deviation), medium (5-10%), low (<5%)
- Buy/sell actions con USD amounts
- One-click execution con order generation
- Balance check (rebalance disabled si within threshold)

### Performance Tracking
- Historical performance chart con múltiples períodos (7D, 1M, 3M, 1A, All)
- Canvas-based custom rendering (no external libraries)
- Hover tooltips con date, value, daily change
- Best/worst performer identification

### Goal Setting
- Create financial goals con preset templates
- Target amount y target date
- Monthly contribution calculator con auto-suggestion
- Progress tracking con status (on_track, at_risk, behind)
- Projected completion date
- Delete y update goals

### Custom Charts (No External Libraries)
- **AllocationChart:** Pure SVG con polar to Cartesian conversion
  ```typescript
  const x = centerX + radius * Math.cos(angleRad);
  const y = centerY + radius * Math.sin(angleRad);
  ```
- **PerformanceChart:** Canvas 2D API con high DPI support
  ```typescript
  const dpr = window.devicePixelRatio || 1;
  canvas.width = rect.width * dpr;
  ctx.scale(dpr, dpr);
  ```

## Available Assets

10 supported cryptocurrency assets:

| Symbol | Name | Color | Logo Source |
|--------|------|-------|-------------|
| BTC | Bitcoin | #F7931A | cryptologos.cc |
| ETH | Ethereum | #627EEA | cryptologos.cc |
| USDT | Tether | #26A17B | cryptologos.cc |
| SOL | Solana | #9945FF | cryptologos.cc |
| LINK | Chainlink | #2A5ADA | cryptologos.cc |
| AVAX | Avalanche | #E84142 | cryptologos.cc |
| ADA | Cardano | #0033AD | cryptologos.cc |
| DOT | Polkadot | #E6007A | cryptologos.cc |
| MATIC | Polygon | #8247E5 | cryptologos.cc |
| UNI | Uniswap | Default | cryptologos.cc |

## Tests

```bash
# Tests unitarios del módulo
npm run test modules/portfolio

# Tests de integración con WebSocket
npm run test:integration portfolio/websocket

# Tests E2E de flujos de portfolio
npm run test:e2e portfolio
```

## Roadmap

### Pendientes - Alta Prioridad (P1)
- [ ] **Tax-loss Harvesting** (50h) - Automated tax-loss harvesting strategies
- [ ] **Portfolio Analytics** (35h) - Sharpe ratio, volatility, correlation matrix
- [ ] **Auto-rebalance Scheduler** (25h) - Scheduled automatic rebalancing (daily/weekly/monthly)

### Mediano Plazo (P2)
- [ ] **Dollar-cost Averaging** (25h) - Automated DCA con scheduling
- [ ] **Portfolio Comparison** (20h) - Compare múltiples portfolios side-by-side
- [ ] **Custom Benchmarks** (15h) - Compare against custom benchmarks (not just asset allocation)
- [ ] **Risk Metrics Dashboard** (30h) - VaR, Conditional VaR, max drawdown

### Largo Plazo (P3)
- [ ] **Portfolio Sharing** (15h) - Share portfolios con otros usuarios (read-only)
- [ ] **Clone Portfolio** (10h) - Clone existing portfolio como template
- [ ] **Backtesting** (60h) - Backtest allocation strategies con historical data
- [ ] **AI Portfolio Advisor** (80h) - LLM-powered portfolio recommendations

## Dependencias

- `zustand` - State management
- `axios` - HTTP client
- `socket.io-client` - WebSocket client
- `@heroicons/react` - Icons (v24 solid)
- Canvas 2D API (native browser)
- SVG (native browser)

## Documentación Relacionada

- **ET Specs:**
  - ET-PFM-009: Custom Charts (SVG+Canvas)
- **User Stories:** US-PFM-001 a US-PFM-012
- **Backend API Docs:** `/docs/api/portfolio.md`
- **WebSocket Protocol:** `/docs/websocket/portfolio-updates.md`

---

**Última actualización:** 2026-01-25
**Autor:** Claude Opus 4.5
