Skip to content

Conversation

@salvac12
Copy link

Summary

This PR completes Phase A: Stabilize of the FinRobot migration plan, establishing a clean and well-structured codebase ready for the agentic investment system (Phase B).

Changes by Phase

Phase 0: Governance Setup

  • Added CLAUDE.md (coding standards)
  • Added PLAN.md (migration roadmap)
  • Configured pyproject.toml with ruff + mypy
  • Added .pre-commit-config.yaml
  • Added PR template

Phase 1: Security Fixes

  • Removed all bare except: statements
  • Added input validation with Pydantic (Python) and Zod (TypeScript)

Phase 2: Delete Redundant Code

  • Archived tutorials_beginner/, tutorials_advanced/, experiments/ to archive/

Phase 3: English Migration

  • Migrated all Spanish identifiers to English in core modules
  • Added backward-compatible aliases

Phase 4: Testing Infrastructure

  • Setup pytest + Vitest
  • Added 115+ Python tests, 56+ TypeScript tests

Phase 5: Error Handling Standardization

  • Created mi_patrimonio/core/exceptions.py (Python)
  • Created vercel-patrimonio/lib/errors.ts (TypeScript)
  • Added structured logging

Phase 6: Architecture Cleanup

  • Created abstract DataProvider base class
  • Implemented dependency injection container
  • Added lazy initialization pattern

Phase 7: Streamlit Migration

  • Ported risk calculations to TypeScript (riskAnalysis.ts)
  • Created RiskAnalysis.tsx dashboard component
  • Created DistributionPieChart.tsx component
  • Added Risk Analysis tab to main app

Test Plan

  • Run Python tests: pytest mi_patrimonio/tests/
  • Run TypeScript tests: cd vercel-patrimonio && npm test
  • Verify Next.js build: cd vercel-patrimonio && npm run build
  • Check TypeScript types: cd vercel-patrimonio && tsc --noEmit

Files Changed

New files (key):

  • CLAUDE.md, PLAN.md - Documentation
  • mi_patrimonio/core/exceptions.py - Custom exceptions
  • mi_patrimonio/core/container.py - DI container
  • vercel-patrimonio/lib/riskAnalysis.ts - Risk calculations
  • vercel-patrimonio/components/RiskAnalysis.tsx - Risk dashboard

🤖 Generated with Claude Code

salvac12 and others added 11 commits January 15, 2026 12:06
- Add CLAUDE.md with comprehensive coding standards
- Add PLAN.md with 12-phase migration roadmap (Phases A & B)
- Add pyproject.toml with ruff, mypy, pytest configuration
- Add .pre-commit-config.yaml for git hooks (linting, type checking, secrets)
- Add PR template at .github/PULL_REQUEST_TEMPLATE.md
- Update tsconfig.json with maximum TypeScript strictness

Phase 0 of FinRobot enterprise-grade refactoring complete.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Phase 1 security fixes:
- Replace 6 bare except clauses with specific exception types
  - setup.py: FileNotFoundError
  - sec_utils.py: OSError, IOError, KeyError
  - price_server.py: Exception with logging
  - ai_advisor.py: json.JSONDecodeError, KeyError, TypeError
  - xbrl_parser.py: ValueError
- Add input validation to Python API endpoints (price_server.py)
  - Ticker format validation with regex pattern
  - Max tickers per request limit (50)
- Add Zod validation library to TypeScript frontend
  - Create lib/validation.ts with schemas
  - Update prices, chat, snapshot API routes
- Fix TypeScript strict mode errors (error: any -> error instanceof Error)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Phase 2 cleanup:
- Delete vercel-finrobot/ directory (4,873 lines removed)
  - Redundant duplicate of mi_patrimonio/ code
  - Was used for early Vercel deployment testing
- Archive legacy directories to archive/
  - tutorials_beginner/ -> archive/tutorials_beginner/
  - tutorials_advanced/ -> archive/tutorials_advanced/
  - experiments/ -> archive/experiments/
- Remove commented code from data sources
  - fmp_utils.py: remove commented import
  - sec_utils.py: remove commented cache logic

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Phase 3 English migration - config_portfolios.py:
- Rename all Spanish field names to English:
  - nombre → name
  - nombre_corto → short_name
  - propietario → owner
  - CARTERA → HOLDINGS
  - tipo → asset_type
  - cuenta → account
  - titulos → shares
  - precio_compra → purchase_price
  - valor_actual → current_value
  - moneda → currency
  - coste → cost
  - precio_mercado → market_price
  - fecha_compra → purchase_date
  - DISTRIBUCION_OBJETIVO → TARGET_ALLOCATION
  - renta_variable → equities
  - renta_fija → fixed_income
  - PERFIL_INVERSOR → INVESTOR_PROFILE
  - horizonte_anos → investment_horizon_years
  - tolerancia_riesgo → risk_tolerance
- Add LEGACY_FIELD_MAPPING for backward compatibility
- Add type hints to helper functions

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Migrated the following files from Spanish to English identifiers:

- config.py:
  - PERFILES_RIESGO → RISK_PROFILES
  - CATEGORIAS_ACTIVOS → ASSET_CATEGORIES
  - ETFS_RECOMENDADOS → RECOMMENDED_ETFS
  - All field names (nombre→name, descripcion→description, etc.)

- portfolio.py:
  - PerfilInversor → InvestorProfile
  - Posicion → Position
  - calcular_distribucion → calculate_distribution
  - All method names (agregar_posicion→add_position, etc.)

- data_provider.py:
  - obtener_cotizacion → get_quote
  - obtener_cotizaciones_batch → get_quotes_batch
  - obtener_historico → get_historical
  - obtener_tipo_cambio → get_exchange_rate
  - All dataclass fields (precio→price, moneda→currency, etc.)

All modules include legacy aliases for backward compatibility.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Python (mi_patrimonio):
- Add tests/ directory with conftest.py fixtures
- Add test_portfolio.py with 34 tests for InvestorProfile, Position, Portfolio
- Add test_data_provider.py with 22 tests for Quote, HistoricalData, DataProvider
- Coverage: portfolio.py 75%, data_provider.py 95%

TypeScript (vercel-patrimonio):
- Add vitest.config.ts with jsdom environment and 70% coverage thresholds
- Add __tests__/setup.ts with Next.js router mocks
- Add __tests__/validation.test.ts with 41 tests for Zod schemas
- Add test scripts to package.json

Total: 97 tests passing

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add /api/historical-metrics route for YTD and daily return calculations
  - Fetches prices from Yahoo Finance with proper date logic
  - Handles positions bought before vs during 2026 correctly
  - Calculates daily change vs yesterday's closing values

- Update useLivePrices.ts with environment detection
  - Use Next.js API directly on Vercel (no local server)
  - Fall back to OpenBB server in local development

- Update usePerformanceMetrics.ts to use historical-metrics API
  - Primary: fetch from /api/historical-metrics
  - Fallback: use snapshot-based calculations

- Update portfolioPositions.ts with January 2026 data
  - Add new broker types (GDAF, Varios)
  - Add new categories (Commodities, Nuclear)
  - Update position values and shares

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Python (mi_patrimonio/core/):
- Add exceptions.py with typed exception hierarchy:
  - FinRobotError (base), DataFetchError, ValidationError
  - ConfigurationError, PortfolioError, PriceServiceError
- Add logging.py with structured logging utilities
- Add 21 unit tests for exception classes

TypeScript (vercel-patrimonio/lib/):
- Add errors.ts with matching error types and utilities:
  - FinRobotError, DataFetchError, ValidationError, ApiError
  - isFinRobotError, getErrorMessage, getErrorCode helpers
- Add 33 unit tests for error module

Logging migration:
- config.py: Replace print() with logger.warning()
- finrobot_agents.py: Replace print() with logger.info/warning()
- sec_tools/xbrl_parser.py: Add logging, specific exception catches
- sec_tools/data_cache.py: Add logging, specific exception catches

Total tests: 77 Python + 74 TypeScript = 151 tests passing

Co-Authored-By: Claude Opus 4.5 <[email protected]>
…hase 6)

- Add abstract base classes for data providers (DataProviderBase, MarketDataProvider, etc.)
- Add configuration module with ProviderConfig and DataSourceConfig
- Add FinnHubProvider and FMPProvider with dependency injection
- Add ServiceContainer for mi_patrimonio with lazy initialization
- Make legacy utility imports lazy to avoid requiring all dependencies
- Add 23 tests for new provider infrastructure

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add risk analysis utilities (volatility, Sharpe, beta, VaR, max drawdown)
- Add useRiskMetrics hook for React components
- Add DistributionPieChart component with Recharts
- Add RiskAnalysis dashboard with score gauge and 8 metric cards
- Add Risk Analysis tab to main navigation
- Add pie chart to Dashboard distribution section
- Add 56 unit tests for risk calculations
- Delete legacy Streamlit files (app.py, app_familia.py)
- Update PLAN.md marking Phase A complete

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@BruceYanghy BruceYanghy self-assigned this Jan 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants