SmartFolio is a portfolio management application for crypto, stocks and banking. It combines portfolio reporting, risk analysis, allocation tools and machine learning across dedicated modules.
Crypto holdings are organized into 11 asset groups, with support for CoinTracking API and CSV data sources.
Three modules share risk analysis, allocation and machine learning services.
- Decision Engine: Automated governance with "Freeze Semantics" to prevent panic selling.
- Phase Engine: Proactive detection of market regimes (Bitcoin Season vs Altseason) with auto-tilts.
- Allocation Engine V2: Top-down hierarchical rebalancing (Macro → Sectors → Coins).
- Smart Execution: Dynamic thresholds and "Incumbency Protection" to minimize churn.
- Smart Taxonomy: Automatically groups hundreds of tokens into 11 Canonical Groups (BTC, ETH, SOL, AI, DeFi...) to drastically reduce cognitive load for large wallets.
- CoinTracking Native: Deep integration with CoinTracking (API & CSV) to handle complex transaction histories and real-time balances accurately.
- Market Opportunities: AI Scanner that detects portfolio gaps and suggests Stocks/ETFs.
- Intelligent Stop Loss: 6 adaptive methods (Trailing, Volatility-based) to protect gains.
- Risk Analytics: Specific beta and correlation analysis against S&P 500.
- P&L Today: Real-time performance tracking with "Anchor Points" (Midnight/Session).
- Unified View: Cross-asset aggregation (Crypto + Stocks + Bank) in your reference currency.
- Structure Analysis: Monitoring of liquidity ratios (Stable/Cash vs Risky Assets).
- AI Chat Assistant: Global AI assistant with context awareness (Groq free / Claude premium)
- Context-aware: Automatically sees current page data (portfolio, risk, opportunities)
- Knowledge base: Dynamically synced with documentation (Decision Index, Risk Score, etc.)
- Floating button (Ctrl+K) available on all pages
- Auto-refresh: Knowledge base reloads from .md files (5-min cache TTL)
- Advanced ML: LSTM & Transformers for volatility and trend prediction.
- Risk Score V2: Unified "Robustness Score" (0-100) across all asset classes.
- Stress Testing & Monte Carlo (Dec 2025): Real portfolio simulations
- Monte Carlo: 10,000 simulations with historical distributions (VaR/CVaR, loss probabilities)
- Stress Tests: 6 crisis scenarios (2008, COVID-19, China ban, Tether collapse, Fed hike, Exchange hack)
- Interactive charts with on-demand calculation (10-30 sec, sessionStorage cache)
- ML Sentiment: Proprietary sentiment score (0-100) - NOT Fear & Greed Index (alternative.me). Formula:
50 + (sentiment_ml × 50)where sentiment ∈ [-1, 1]. - Multi-Tenant: Complete isolation of data and configurations per user.
- Python 3.10+
- pip, virtualenv
- (Optional) Redis for advanced caching and real-time streaming
Windows (PowerShell):
py -m venv .venv
.\\.venv\\Scripts\\Activate
pip install -r requirements.txt
copy .env.example .env
# Edit .env with your API keys (CoinGecko, CoinTracking, FRED)Linux/macOS:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
# Edit .env with your API keysPlaywright (optional, for crypto-toolbox scraping):
pip install playwright
playwright install chromiumWindows:
.\\.venv\\Scripts\\Activate
.\\start_dev.ps1
# With scheduler (P&L snapshots, OHLCV updates): .\\start_dev.ps1 -EnableSchedulerLinux/macOS:
source .venv/bin/activate
./start_dev.sh
# With scheduler: ./start_dev.sh --enable-schedulerThis is the recommended method for running the application in a stable, production-like environment.
-
Prerequisites:
- Docker and Docker Compose installed.
- An
.envfile created from.env.examplewith the necessary API keys.
-
Automated Deployment (Recommended): The
deploy.shscript automates pulling the latest code, rebuilding the Docker image, and launching the services../deploy.sh
To restart without rebuilding the image:
./deploy.sh --skip-build
-
Manual Launch: You can also use
docker-composecommands directly:# Build and start services in the background docker-compose up -d --build # Stop services docker-compose down # View logs docker-compose logs -f
- Settings: http://localhost:8080/static/settings.html (initial configuration)
- Dashboard: http://localhost:8080/static/dashboard.html
- API Docs: http://localhost:8080/docs
| Page | Description | URL |
|---|---|---|
| Dashboard | Global portfolio view + P&L Today | /static/dashboard.html |
| Analytics | Real-time ML + Decision Index | /static/analytics-unified.html |
| Risk | Risk management + Governance + Alerts | /static/risk-dashboard.html |
| Market Regimes | Stock/BTC/ETH regime detection (HMM) | /static/market-regimes.html |
| Advanced Risk | Monte Carlo, GRI, Stress Testing | /static/advanced-risk.html |
| Cycle Analysis | Bitcoin cycle analysis + historical charts | /static/cycle-analysis.html |
| Rebalance | Dynamic rebalancing plans | /static/rebalance.html |
| Execution | Real-time execution with validation | /static/execution.html |
| Simulations | Complete pipeline simulator | /static/simulations.html |
| DI Backtest | Decision Index historical backtesting | /static/di-backtest.html |
| Wealth Dashboard | Unified wealth (liquidities, assets, liabilities) | /static/wealth-dashboard.html |
| Monitoring | System KPIs + Alerts History | /static/monitoring.html |
| Admin Dashboard | User management, logs, cache, ML models (RBAC) | /static/admin-dashboard.html |
| Stock Dashboard | Stocks, ETFs, funds overview (Saxo Bank) | /static/saxo-dashboard.html |
| Stock Analytics | Stock risk analysis + advanced analytics | /static/bourse-analytics.html |
| Stock Recommendations | Portfolio recommendations + market opportunities | /static/bourse-recommendations.html |
api/
├── main.py # Main app + routers
├── deps.py # Dependency injection (multi-tenant)
├── execution/ # Decision Engine + Governance
├── *_endpoints.py # 30+ modular routers
services/
├── balance_service.py # Multi-source data resolution
├── execution/governance.py # Decision Engine + Freeze semantics
├── ml/orchestrator.py # ML orchestration
├── risk_scoring.py # Central Risk Score (dual system)
├── portfolio.py # P&L tracking
static/
├── *.html # Main pages
├── core/
│ ├── allocation-engine.js # Topdown hierarchical allocation
│ └── unified-insights-v2.js # Phase Engine
├── components/
│ ├── nav.js # Unified navigation
│ ├── decision-index-panel.js # Decision Index UI
│ └── flyout-panel.js # Reusable Risk Sidebar
├── global-config.js # Centralized frontend config
data/
└── users/{user_id}/
├── config.json # User configuration (API keys)
├── cointracking/data/ # Crypto CSV (auto versioning)
├── saxobank/data/ # Stock market CSV
└── wealth/wealth.json # Unified wealth data (assets, liabilities)
- [OK] Secrets management:
.envtemplate, pre-commit hooks (detect-secrets + gitleaks) - Secure frontend: 464 console.log → debugLogger, ESLint (no-console, no-eval)
- [OK] HTTP headers: CSP, X-Content-Type-Options, X-Frame-Options, rate limiting
- [OK] Automated tests: header & security validation
Complete details: SECURITY.md, AUTHENTICATION.md, and EXTERNAL_ACCESS_CADDY.md
- CLAUDE.md - Guide for AI agents (critical rules, patterns, quick checks)
- ARCHITECTURE.md - Detailed architecture
- Docker Deployment Guide - Production deployment guide
- API Reference - Endpoints and schemas
- User Guide - Complete user guide
- AI Chat Assistant: AI_CHAT_GLOBAL.md - Global AI assistant (Groq/Claude), context-aware, dynamic knowledge base
- Allocation: ALLOCATION_ENGINE_V2.md - Topdown hierarchical, floors, incumbency
- Decision Index: DECISION_INDEX_V2.md - Dual scoring (DI vs Regime)
- Risk Management: RISK_SEMANTICS.md, RISK_SCORING_MODULE.md
- Governance: governance.md - Automated governance system
- Phase Engine: PHASE_ENGINE.md - Market phase detection
- Simulator: SIMULATION_ENGINE.md - Complete pipeline
- Sources System: SOURCES_V2.md - Modular multi-source (category-based)
- Market Opportunities: MARKET_OPPORTUNITIES_SYSTEM.md - Scoring 3-pillars, gap detection
- Intelligent Stop Loss: STOP_LOSS_SYSTEM.md - 6 adaptive methods (Trailing Stop NEW Oct 2025)
- P&L Today: P&L Today - Real-time tracking
- Redis: REDIS_SETUP.md - Cache & streaming
- Wealth Module: WEALTH_MODULE.md - Unified wealth management (CRUD, migration)
- Logging: LOGGING.md - Rotating logs (5MB x3, AI-optimized)
- Developer Guide - Setup, tests, workflow
- Testing Guide - Unit/Integration/E2E tests
- Runbooks - Operational procedures
- Troubleshooting - Common issues resolution
- Contributing - Contribution guidelines
- I18N Migration - FR → EN translation report (Feb 2026)
Documentation Index - Complete list of available docs
6 configured users: demo, jack, donato, elda, roberto, clea
- Complete isolation: separate data, config, API keys
- Dynamic selector: navigation bar (independent from Admin menu)
- Dynamic sources: auto display of CSV + API according to config
- Local CSV: upload via Settings → Sources (automatic versioning)
- CoinTracking API: if keys configured (real-time)
- Saxo API: import stock market positions
- Banks: manual bank accounts
# .env
COINGECKO_API_KEY=your_key_here # Crypto prices (3 min cache)
COINTRACKING_API_KEY=your_key_here # Real-time balances
FRED_API_KEY=your_key_here # Macro data
REDIS_URL=redis://localhost:6379/0 # Advanced cache (optional)# Health & Config
GET /healthz # Application status
GET /api/config # Frontend configuration
# Portfolio
GET /balances/current?source=cointracking # Current balances
GET /portfolio/metrics?user_id=demo # Metrics + P&L Today
POST /portfolio/snapshot # Create P&L snapshot
# ML & Analytics
GET /api/ml/sentiment/symbol/BTC # ML Sentiment
GET /api/ml/cycle_score # Cycle Score
GET /api/ml/onchain_score # On-Chain Score
# Risk
GET /api/risk/dashboard # Complete risk dashboard
GET /api/risk/bourse/dashboard # Stock market risk (Saxo)
# Governance & Execution
GET /execution/governance/state # Governance state
POST /execution/governance/approve # Approve plan
GET /execution/monitoring/live # Real-time monitoring
# Wealth
GET /api/wealth/items # List wealth items
POST /api/wealth/items # Create wealth item
GET /api/wealth/summary # Net Worth summary
# Sources
GET /api/sources/list # Available sources
POST /api/sources/upload # Upload file
GET /api/sources/test # Test source
# AI Chat Assistant
POST /api/ai/chat # Chat with AI (context-aware)
GET /api/ai/providers # List configured providers
GET /api/ai/quick-questions/{page} # Get quick questions for page
POST /api/ai/refresh-knowledge # Force reload docs from .md files
GET /api/ai/knowledge-stats # Cache statisticsComplete API: http://localhost:8080/docs (Swagger UI)
# Activate environment
.venv\\Scripts\\Activate # Windows
source .venv/bin/activate # Linux/macOS
# Unit tests
pytest tests/unit -v
# Integration tests
pytest tests/integration -v
# E2E tests (requires running server)
pytest tests/e2e -v
# Coverage
pytest --cov=services --cov=api --cov-report=html# Backend: ALWAYS use dependency injection
from api.deps import get_required_user
@router.get("/endpoint")
async def endpoint(user: str = Depends(get_required_user)):
pass// Frontend: ALWAYS use window.loadBalanceData()
const balanceResult = await window.loadBalanceData(true);- Convention: Higher = more robust
- ** FORBIDDEN**: Never invert with
100 - scoreRisk
- Decision Index: Technical allocation quality (65/45 fixed)
- Regime Score: Market state (0-100 variable)
- Phase: Based ONLY on Cycle Score (<70=bearish, 70-90=moderate, ≥90=bullish)
Details: CLAUDE.md
Contributions welcome! See CONTRIBUTING.md for guidelines.
Recommended workflow:
- Fork the project
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'feat: add amazing feature') - Push branch (
git push origin feature/amazing-feature) - Open Pull Request
See CHANGELOG.md for complete version history.
This project is a starter/template for personal or educational use.
- Documentation: docs/index.md
- Issues: For bugs and feature requests
- Troubleshooting: docs/troubleshooting.md
Status: [OK] Production Stable (Feb 2026) Version: 4.0 Stack: Python 3.10+ • FastAPI • Vanilla JS (ES6) • Redis (optional)


