refactor: Complete Phase A - Stabilize codebase#76
Open
salvac12 wants to merge 11 commits intoAI4Finance-Foundation:masterfrom
Open
refactor: Complete Phase A - Stabilize codebase#76salvac12 wants to merge 11 commits intoAI4Finance-Foundation:masterfrom
salvac12 wants to merge 11 commits intoAI4Finance-Foundation:masterfrom
Conversation
- 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
CLAUDE.md(coding standards)PLAN.md(migration roadmap)pyproject.tomlwith ruff + mypy.pre-commit-config.yamlPhase 1: Security Fixes
except:statementsPhase 2: Delete Redundant Code
tutorials_beginner/,tutorials_advanced/,experiments/toarchive/Phase 3: English Migration
Phase 4: Testing Infrastructure
Phase 5: Error Handling Standardization
mi_patrimonio/core/exceptions.py(Python)vercel-patrimonio/lib/errors.ts(TypeScript)Phase 6: Architecture Cleanup
DataProviderbase classPhase 7: Streamlit Migration
riskAnalysis.ts)RiskAnalysis.tsxdashboard componentDistributionPieChart.tsxcomponentTest Plan
pytest mi_patrimonio/tests/cd vercel-patrimonio && npm testcd vercel-patrimonio && npm run buildcd vercel-patrimonio && tsc --noEmitFiles Changed
New files (key):
CLAUDE.md,PLAN.md- Documentationmi_patrimonio/core/exceptions.py- Custom exceptionsmi_patrimonio/core/container.py- DI containervercel-patrimonio/lib/riskAnalysis.ts- Risk calculationsvercel-patrimonio/components/RiskAnalysis.tsx- Risk dashboard🤖 Generated with Claude Code