Download README.md from bhuvi3/CIOAgent: direct link, hf CLI and curl.
- Browser
- Download file 22.4 kB
-
https://huggingface.co/spaces/bhuvi3/CIOAgent/resolve/main/README.md
- Command line
-
hf download hf://spaces/bhuvi3/CIOAgent/README.md
-
curl -L -o README.md https://huggingface.co/spaces/bhuvi3/CIOAgent/resolve/main/README.md
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.
Click the thumbnail to watch the demo
Table of Contents
- Overview
- System Architecture
- Multi-Agent AI Engine
- Key Features
- Business Value
- User Journey
- Analytics and Metrics
- API Reference
- Tech Stack
- Project Structure
- Getting Started
- Future Possibilities and Roadmap
- 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
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:
- Frontend β React 19 SPA with a dark-themed dashboard, interactive charts (Recharts), and real-time state management
- Backend β FastAPI with async endpoints, parallel agent execution, and modular metric computation
- 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.
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:
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.
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).
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.
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
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
- Authenticate β Sign up or log in. Your portfolio and analysis history are restored automatically.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
git clone <repository-url>
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:
ANTHROPIC_API_KEY=sk-ant-...
ELEVENLABS_API_KEY=... # Optional
WHITECIRCLE_API_KEY=... # Optional
3. Start the Backend
uvicorn main:app --reload --port 8000
4. Install and Start the Frontend
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
- Open http://localhost:3000 and create an account
- Configure your portfolio tickers, weights, and financial profile in the sidebar
- Click Run Analysis to compute metrics and view the dashboard
- Click Run Agents to get AI-powered interpretations
- Use the CIO Chat to ask follow-up questions
- Click Run Insights for deep-dive analysis modules
- 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.
