--- title: Portfolio CIO emoji: 💼 colorFrom: blue colorTo: indigo sdk: docker app_port: 7860 app_file: main.py pinned: false ---
# Personalised Portfolio CIO ### AI-Powered Portfolio Intelligence Platform ### Application link: https://huggingface.co/spaces/bhuvi3/CIOAgent **Transform raw market data into actionable investment insights using a multi-agent AI architecture powered by Anthropic Claude.** [![FastAPI](https://img.shields.io/badge/FastAPI-009688?style=for-the-badge&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com/) [![React](https://img.shields.io/badge/React_19-61DAFB?style=for-the-badge&logo=react&logoColor=black)](https://react.dev/) [![Claude](https://img.shields.io/badge/Anthropic_Claude-6B4FBB?style=for-the-badge&logo=anthropic&logoColor=white)](https://anthropic.com/) [![Python](https://img.shields.io/badge/Python_3.12+-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://python.org/) **Click the thumbnail to watch the demo** [![Watch the Demo](https://img.youtube.com/vi/ZmZEs3xsuRM/maxresdefault.jpg?v=2)](https://youtu.be/ZmZEs3xsuRM)
--- ## Table of Contents - [Overview](#overview) - [System Architecture](#system-architecture) - [Multi-Agent AI Engine](#multi-agent-ai-engine) - [Key Features](#key-features) - [Business Value](#business-value) - [User Journey](#user-journey) - [Analytics and Metrics](#analytics-and-metrics) - [API Reference](#api-reference) - [Tech Stack](#tech-stack) - [Project Structure](#project-structure) - [Getting Started](#getting-started) - [Future Possibilities and Roadmap](#future-possibilities--roadmap) - [Disclaimer](#disclaimer) --- ## Overview Portfolio CIO is a **full-stack portfolio analytics platform** that combines quantitative finance with generative AI. Users configure a portfolio of equities, and the system computes institutional-grade metrics, runs Monte Carlo simulations, backtests against historical crises, and deploys **six specialized AI agents** that analyze the data in parallel before a **Chief Investment Officer (CIO) agent** synthesizes everything into personalized, conversational investment guidance. ### What Makes This Different | Traditional Tools | Portfolio CIO | |---|---| | Static dashboards with raw numbers | AI agents that **interpret** every metric in context | | One-size-fits-all risk ratings | Personalized advice based on your **financial profile and goals** | | Manual report generation | Automated **PDF reports** and **text-to-speech** audio | | Siloed analysis views | Unified CIO chat that synthesizes **all analyses** into one conversation | --- ## System Architecture ```mermaid graph TB subgraph Frontend["Frontend (React + Vite)"] UI["User Interface"] Auth["Authentication"] Dash["Dashboard & Charts"] Chat["CIO Chat"] Insights["Portfolio Insights"] end subgraph Backend["Backend (FastAPI)"] API["REST API Layer"] Agents["Multi-Agent Engine"] Metrics["Metrics Engine"] Reports["PDF Report Generator"] end subgraph AI["AI & Integrations"] Claude["Anthropic Claude"] EL["ElevenLabs TTS"] WC["WhiteCircle Safety"] end subgraph Data["Data Sources"] YF["Yahoo Finance"] FS["File Storage (JSON)"] end UI --> API API --> Agents API --> Metrics API --> Reports Agents --> Claude Chat --> WC Chat --> Claude Reports --> EL Metrics --> YF API --> FS ``` The platform follows a clean **three-tier architecture**: 1. **Frontend** — React 19 SPA with a dark-themed dashboard, interactive charts (Recharts), and real-time state management 2. **Backend** — FastAPI with async endpoints, parallel agent execution, and modular metric computation 3. **AI Layer** — Anthropic Claude for multi-agent analysis, ElevenLabs for audio reports, WhiteCircle for content safety --- ## Multi-Agent AI Engine The core differentiator is a **six-agent pipeline** where each agent specializes in a different dimension of portfolio analysis, running in parallel and feeding into a synthesizing CIO agent. ```mermaid flowchart LR A["Portfolio\nInput"] --> B["Metrics\nEngine"] B --> C["Efficient\nFrontier"] B --> D["Monte Carlo\nSimulation"] B --> E["Goal\nProjection"] C --> F["6 AI Agents\n(Parallel)"] D --> F E --> F F --> G["Performance\nAnalyst"] F --> H["Risk\nOfficer"] F --> I["Macro\nStrategist"] F --> J["Stress\nSpecialist"] F --> K["Allocation\nStrategist"] F --> L["Goal\nPlanner"] F --> G["Performance\nAnalyst"] F --> H["Risk\nOfficer"] F --> I["Macro\nStrategist"] F --> K["Allocation\nStrategist"] F --> L["Goal\nPlanner"] G --> M["CIO\nAgent"] H --> M I --> M K --> M L --> M M --> N["Personalized\nInsights"] ``` ### Agent Roles | Agent | Role | What It Analyzes | |---|---|---| | **Performance Analyst** | Quantitative returns specialist | Annual return, volatility, Sharpe, Sortino, Calmar, Treynor, and Information Ratios | | **Risk Officer** | Downside and tail-risk evaluator | Max drawdown, Value at Risk (95%), Conditional VaR, crash exposure | | **Macro Strategist** | Market regime and sensitivity expert | Beta vs. benchmarks (SPY, QQQ), systematic risk exposure | | **Allocation Strategist** | Portfolio construction optimizer | Current allocation vs. efficient frontier, max-Sharpe and min-volatility targets | | **Goal Planner** | Financial planning specialist | Goal probability, median outcomes, required CAGR, surplus/shortfall analysis | | **CIO (Chief Investment Officer)** | Top-level synthesizer and conversational advisor | All of the above + multi-turn chat with full context and safety filtering | All specialist agents run **concurrently** via `asyncio.gather`, reducing total response time dramatically. The CIO agent has access to every sub-agent's analysis and supports **multi-turn conversation** for follow-up questions. --- ## Key Features ### Core Analytics - **Performance Metrics** — Annual return, volatility, and 5 risk-adjusted ratios (Sharpe, Sortino, Calmar, Treynor, Information Ratio) - **Risk Analysis** — Maximum drawdown, daily VaR and CVaR at the 95th percentile - **Benchmark Sensitivity** — Beta calculations against multiple market indices - **Efficient Frontier** — 2,000 random portfolio simulations with max-Sharpe and min-volatility optimal points - **Monte Carlo Stress Test** — 5,000-path forward simulation for 1-year return distributions - **Goal-Based Projection** — GBM Monte Carlo with monthly contributions, success probability, and percentile bands (p10 through p90) ### Portfolio Insights (5 Modules) - **Sector Exposure** — GICS sector breakdown with HHI concentration risk scoring - **Dividend Analysis** — Per-holding yield, payout ratios, projected annual/monthly income - **Rebalancing Engine** — Drift detection with actionable BUY/SELL trade recommendations - **Macro Correlations** — Portfolio correlation vs. 7 macro indicators (VIX, Treasury yields, Gold, USD, Crude Oil) with rolling 60-day windows - **Tax-Loss Harvesting** — Unrealized gain/loss estimates with harvestable loss identification and tax savings projections ### Platform Features - **Secure Authentication** — bcrypt-hashed passwords with rotating Bearer tokens (7-day expiry) - **Persistent State** — Portfolio configs, analyses, chat history, and snapshots survive across sessions - **Portfolio Versioning** — Save, compare, and restore historical portfolio configurations - **Custom Alerts** — Rule-based monitoring (e.g., "alert if Sharpe drops below 1.0") - **PDF Export** — Downloadable reports with metrics, charts, and AI analyses - **Text-to-Speech** — Convert any analysis to audio via ElevenLabs - **Content Safety** — WhiteCircle AI moderation + regex fallback for CIO queries --- ## Business Value In a landscape dominated by generic robo-advisors and complex institutional terminals, *Portfolio CIO* bridges the gap: 1. *Democratization of Institutional Intelligence* * Retail investors gain access to *Hedge-Fund Grade Metrics* (CVaR, Tail Risk, Efficient Frontiers) typically reserved for Bloomberg Terminal users, but explained in plain English by the AI. 2. *Hyper-Personalized Financial Wellness* * By integrating the user's *Assets, Liabilities, and Psychological Risk Tolerance* into the prompt context, the system avoids dangerous "one-size-fits-all" advice. It detects when a user's stated risk tolerance conflicts with their actual portfolio composition (Behavioral Gap Analysis). 3. *Operational Efficiency for Advisors* * For financial planners, this acts as a *"Co-Pilot"*, reducing hours of manual Excel analysis and report writing into seconds of parallelized cloud compute. 4. *Trust-First Architecture* * With *White Circle AI* safety layers and explicit disclaimer injections, the platform prioritizes responsible non-hallucinating guidance, crucial for Fintech compliance. --- ## User Journey ```mermaid flowchart TD A["User Opens App"] --> B{"Authenticated?"} B -- No --> C["Login / Sign Up"] C --> D["Token Issued"] D --> E["Load Saved State"] B -- Yes --> E E --> F["Configure Portfolio"] F --> G["Run Analysis"] G --> H["View Dashboard\nand Frontier"] H --> I["Run AI Agents"] I --> J["View Agent Insights\nand Goal Projection"] J --> K["Chat with CIO"] H --> L["Run Portfolio Insights"] L --> M["View Sectors,\nDividends, Rebalancing,\nMacro, Tax"] K --> N["Export PDF Report"] M --> N J --> O["Save Snapshot"] ``` ### Step-by-Step Walkthrough 1. **Authenticate** — Sign up or log in. Your portfolio and analysis history are restored automatically. 2. **Configure** — Set tickers, weights, benchmarks, date range, risk-free rate, and simulation parameters in the sidebar. Add your financial profile (assets, liabilities, risk tolerance) and investment goal. 3. **Run Analysis** — Computes all quantitative metrics and the efficient frontier. The dashboard populates with performance cards, risk metrics, allocation charts, and the frontier scatter plot. 4. **Run AI Agents** — Six specialist agents analyze your metrics in parallel. Results appear in tabbed panels with rich markdown formatting. Goal projection charts show probability bands. 5. **Chat with the CIO** — Ask follow-up questions in natural language. The CIO has full context of your portfolio, all agent analyses, your financial profile, and goals. Conversation history persists. 6. **Explore Insights** — Run all 7 insight modules simultaneously for deep dives into stress scenarios, sector allocation, dividends, rebalancing needs, macro exposure, tax opportunities, and market sentiment. 7. **Export and Save** — Download a comprehensive PDF report. Save portfolio snapshots for future comparison. Set up alert rules for ongoing monitoring. --- ## Analytics and Metrics ### Quantitative Engine | Category | Metrics | Methodology | |---|---|---| | **Performance** | Annual Return, Volatility, Sharpe, Sortino, Calmar, Treynor, Information Ratio | Daily returns from Yahoo Finance, annualized (x252 / x sqrt 252) | | **Risk** | Max Drawdown, VaR (95%), CVaR (95%) | Peak-to-trough analysis, historical percentile method | | **Benchmark** | Beta vs. each index | Covariance / Variance of daily returns | | **Frontier** | 2,000 optimal portfolios, Max-Sharpe and Min-Vol points | Dirichlet-weighted random sampling, mean-variance optimization | | **Forward Risk** | Expected 1Y return, worst/best 5%/95% | 5,000-path Monte Carlo with GBM | | **Goal Projection** | Success probability, median outcome, required CAGR | GBM Monte Carlo with monthly contributions, binary search for CAGR | ### Insight Modules | Module | Data Source | Key Outputs | |---|---|---| | Sector Exposure | yfinance ticker info (GICS) | Sector weights, HHI concentration risk scoring | | Dividends | yfinance ticker info | Yield, payout ratio, annual/monthly income | | Rebalancing | yfinance live prices | Drift %, recommended trades (BUY/SELL/HOLD) | | Macro Correlations | 7 macro ETF proxies | Static and rolling 60-day correlations | | Tax Harvesting | yfinance historical prices | Unrealized P&L, harvestable losses, tax savings | | News Sentiment | yfinance news + Claude | Per-article sentiment, portfolio-level summary | --- ## API Reference ### Authentication | Method | Endpoint | Description | |---|---|---| | `POST` | `/auth/signup` | Create account (returns Bearer token) | | `POST` | `/auth/login` | Authenticate (returns Bearer token) | | `GET` | `/auth/me` | Get current user info | ### Analysis | Method | Endpoint | Description | |---|---|---| | `POST` | `/analysis/compute` | Compute portfolio metrics (performance, risk, betas, stress test) | | `POST` | `/analysis/frontier` | Compute efficient frontier + all metrics | ### AI Agents | Method | Endpoint | Description | |---|---|---| | `POST` | `/agents/run` | Run all 6 agents in parallel, return metrics + inferences + goal projection | | `POST` | `/agents/run-stream` | SSE streaming version (progressive agent results) | | `POST` | `/agents/cio` | Ask the CIO agent with full portfolio context | ### Portfolio Insights | Method | Endpoint | Description | |---|---|---| | `POST` | `/insights/tax-harvest` | Tax-loss harvesting opportunities | ### Reports and Data | Method | Endpoint | Description | |---|---|---| | `POST` | `/reports/pdf` | Generate downloadable PDF report | | `POST` | `/tts/report` | Convert text to speech (MP3 audio) | | `GET` / `POST` | `/user/data` | Load / save user state | | `POST` | `/portfolio/versions/save` | Save portfolio snapshot | | `GET` | `/portfolio/versions/list` | List saved snapshots | | `DELETE` | `/portfolio/versions/{index}` | Delete a snapshot | | `GET` / `POST` | `/alerts/rules` | Get / save alert rules | | `POST` | `/alerts/check` | Evaluate alert rules against live metrics | | `GET` | `/health` | Health check | --- ## Tech Stack | Layer | Technology | Purpose | |---|---|---| | **Frontend** | React 19, Vite 6, Recharts | SPA with interactive charts and dark-themed UI | | **Backend** | FastAPI, Uvicorn, Pydantic | Async REST API with schema validation | | **AI / LLM** | Anthropic Claude (Opus 4.6) | Multi-agent analysis and conversational CIO | | **Data** | Yahoo Finance, NumPy, Pandas | Market data retrieval and quantitative computation | | **Audio** | ElevenLabs | Text-to-speech report generation | | **Safety** | WhiteCircle AI | Content moderation for user queries | | **Reports** | fpdf2 | PDF document generation | | **Auth** | bcrypt | Password hashing and token management | --- ## Project Structure ``` portfolio-cio/ |-- main.py # FastAPI application entrypoint |-- config/ | +-- settings.py # Environment configuration (Pydantic Settings) | |-- agents/ # Multi-Agent AI Engine | |-- base.py # BaseAgent abstract class | |-- performance_analyst.py # Returns and ratio analysis | |-- risk_officer.py # Drawdown and tail-risk analysis | |-- macro_strategist.py # Benchmark sensitivity analysis | |-- allocation_strategist.py # Frontier-based allocation advice | |-- goal_planner.py # Financial goal analysis | +-- cio.py # CIO synthesizer + multi-turn chat | |-- metrics/ # Quantitative Computation Engine | |-- portfolio.py # Core metrics (return, vol, ratios) | |-- frontier.py # Efficient frontier generation | |-- goal_projection.py # GBM Monte Carlo goal projection | |-- macro_correlation.py # Macro indicator correlations | |-- tax_harvest.py # Tax-loss harvesting | +-- formatters.py # Utilities (sanitize NaN, formatting) | |-- api/ # REST API Layer | |-- schemas.py # Pydantic request/response models | |-- routes_analysis.py # /analysis endpoints | |-- routes_agents.py # /agents endpoints (+ SSE streaming) | |-- routes_auth.py # /auth endpoints | |-- routes_insights.py # /insights endpoints (7 modules) | |-- routes_reports.py # /reports/pdf generation | |-- routes_tts.py # /tts text-to-speech | |-- routes_user_data.py # /user/data persistence | |-- routes_portfolio_versions.py # /portfolio/versions snapshots | +-- routes_alerts.py # /alerts rule management | |-- integrations/ # Third-Party Clients | |-- anthropic_client.py # Anthropic Claude SDK wrapper | |-- elevenlabs_tts.py # ElevenLabs TTS client | +-- whitecircle_safety.py # Content safety moderation | |-- data/ # File-Based Persistence | |-- users.json # User credentials | |-- user_data.json # Saved portfolio states | +-- portfolio_versions.json # Portfolio snapshots | +-- frontend/ # React SPA |-- package.json |-- vite.config.js # Dev server + API proxy config +-- src/ |-- main.jsx # React entrypoint |-- App.jsx # Root component + state management |-- api.js # Backend API client |-- components/ | |-- AuthScreen.jsx # Login / signup | |-- Sidebar.jsx # Portfolio and profile configuration | |-- Dashboard.jsx # Metrics cards and charts | |-- BetaAnalysis.jsx # Benchmark sensitivity display | |-- Frontier.jsx # Efficient frontier scatter plot | |-- GoalProjection.jsx # Goal probability and area chart | |-- AgentTabs.jsx # Tabbed AI agent insights | |-- CIOChat.jsx # Conversational CIO interface | |-- UserProfile.jsx # Investor profile summary | |-- StressScenarios.jsx # Historical crisis results | |-- SectorExposure.jsx # Sector breakdown and HHI | |-- DividendAnalysis.jsx # Dividend income analysis | |-- Rebalancing.jsx # Drift and trade recommendations | |-- MacroCorrelations.jsx# Macro indicator correlations | |-- TaxHarvest.jsx # Tax-loss harvesting view | |-- NewsSentiment.jsx # News sentiment results | |-- PortfolioVersions.jsx# Snapshot management | +-- AlertsPanel.jsx # Alert rule builder and checker +-- styles/ +-- App.css # Dark theme stylesheet ``` --- ## Getting Started ### Prerequisites - **Python 3.12+** - **Node.js 18+** - **Anthropic API key** (required for AI agents) - **ElevenLabs API key** (optional, for text-to-speech) ### 1. Clone and Install Backend ```bash git clone cd portfolio-cio # Create and activate a virtual environment python -m venv .venv && source .venv/bin/activate # Install Python dependencies pip install -r requirements.txt ``` ### 2. Configure Environment Create a `.env` file in the project root: ```env ANTHROPIC_API_KEY=sk-ant-... ELEVENLABS_API_KEY=... # Optional WHITECIRCLE_API_KEY=... # Optional ``` ### 3. Start the Backend ```bash uvicorn main:app --reload --port 8000 ``` ### 4. Install and Start the Frontend ```bash cd frontend npm install npm run dev ``` The app will be available at **http://localhost:3000**. The Vite dev server automatically proxies API requests to the backend on port 8000. ### 5. Use the Platform 1. Open http://localhost:3000 and **create an account** 2. Configure your portfolio tickers, weights, and financial profile in the sidebar 3. Click **Run Analysis** to compute metrics and view the dashboard 4. Click **Run Agents** to get AI-powered interpretations 5. Use the **CIO Chat** to ask follow-up questions 6. Click **Run Insights** for deep-dive analysis modules 7. **Export PDF** or **save snapshots** for record-keeping --- ## Future Possibilities & Roadmap We are actively expanding the ecosystem with cutting-edge integrations from our partners: ### 1. Financial Literacy & Education (Powered by **Finny**) We plan to integrate **Finny's** gamified education API directly into the CIO Chat. * **Functionality**: When the CIO mentions complex terms like "Sharpe Ratio" or "Beta," users can click for a "Finny Bite"—a short, gamified lesson. * **Value**: Transforms the platform from a pure analytics tool into a "Learn-to-Earn" financial education hub. ### 2. Intelligent UI Generation (Powered by **Lovable**) Using **Lovable's** generative UI capabilities to allow users to build custom dashboards via natural language. * **Functionality**: Users can type "Show me a 3D heatmap of my sector correlation vs. interest rates," and the system will generate the React component on the fly. * **Value**: Infinite customizability without dev time. ### 3. Alternative Data Signals (Powered by **Bizcrush**) Integrating **Bizcrush** to bring private market intelligence into public equity analysis. * **Functionality**: Correlate a public stock's performance with B2B interaction data and supply chain signals from the private sector. * **Value**: Provides "Alpha" that isn't available in standard retail tools. ### 4. Hardware-Secured Management (Powered by **Perle Labs**) Leveraging **Perle Labs** for eventual hardware wallet / secure enclave integration. * **Functionality**: For high-net-worth portfolios, critical changes (like rebalancing execution) would require physical confirmation via a Perle-enabled device. * **Value**: Institutional-grade security for digital wealth management. --- ## Disclaimer *This platform is for **informational and educational purposes only**. It does not constitute financial, legal, or investment advice. Portfolio metrics are based on historical data and simulations, which do not guarantee future performance. Always consult with a qualified financial advisor before making investment decisions.*