Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@IB Analytics MCP Servershow me my portfolio performance for the last quarter"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
IB Analytics
Interactive Brokers portfolio analytics library with AI-powered investment analysis and development automation.
Overview
IB Analytics enables systematic analysis of trading performance across multiple IB accounts with type-safe, modular, and extensible architecture.
For Investors (Modes 1 & 2):
95% faster investment strategy generation (6-8 hours → 15-20 minutes)
Parallel market analysis of all holdings simultaneously
Consolidated multi-account view with accurate portfolio metrics
Professional options strategies with specific strikes, Greeks, and Max Pain
Tax-optimized execution plans across multiple accounts
Multi-timeframe technical analysis with entry/exit signals
For Developers (Mode 3):
90% faster issue resolution (80 minutes → 8 minutes via
/resolve-gh-issue)Automated quality gates (black, ruff, mypy, pytest)
Complete TDD workflow (tests → code → PR automation)
11 specialized AI agents + 20 slash commands
Task | Manual | Automated | Savings |
Investment Strategy | 6-8 hours | 15-20 min | 95% |
Stock Analysis | 1-2 hours | 2-3 min | 97% |
Options Strategy | 45-60 min | 3-5 min | 93% |
Portfolio Analysis | 3-4 hours | 5 min | 95% |
GitHub Issue → PR | 80 min | 8 min | 90% |
Installation
Quick Start
1. Configuration
Create a .env file with your IB Flex Query credentials:
Note: To analyze multiple accounts, configure them in your IB Flex Query settings. A single query can return data for multiple accounts.
2. Fetch Data
3. Run Analysis
4. Generate Reports
Docker Usage
Run IB Analytics in an isolated container with security hardening (non-root user, read-only filesystem, resource limits).
See docs/docker.md for full setup, docker-compose configuration, and troubleshooting.
Programmatic Usage
Project Structure
Architecture
Layer Structure
Design Patterns
Template Method (BaseAnalyzer):
Strategy (Reports):
Factory Method (Parsers, Portfolio):
See docs/architecture.md for data flow diagrams, layer responsibilities, and new feature decision guide.
Available Analyzers
PerformanceAnalyzer: Overall trading performance metrics
TaxAnalyzer: Tax liability calculations (OID, capital gains)
CostAnalyzer: Commission and cost efficiency analysis
RiskAnalyzer: Interest rate and market risk scenarios
BondAnalyzer: Bond-specific analytics (YTM, duration, etc.)
Investment Analysis Tools (MCP)
45 MCP tools for stock, options, and portfolio analysis via Yahoo Finance and IB portfolio data.
Category | Tools | Representative Tools |
Portfolio Analysis | 15 |
|
Stock & Market Data | 12 |
|
Options Analysis | 8 |
|
Tax & Costs | 6 |
|
Position History | 4 |
|
Full reference (all arguments, return values, examples): docs/mcp-tools-reference.md
Usage Examples in Claude Desktop
Once you've set up the MCP server in Claude Desktop, you can use natural language:
Usage Modes
IB Analytics supports three distinct usage modes optimized for different user types:
Mode | Target | Characteristics |
1: Claude Desktop | Investors, analysts | Natural language queries, zero coding, complete analysis from single question |
2: Claude Code + MCP | Data scientists | Direct tool composition, fine-grained data access, custom analysis workflows |
3: Claude Code + Repo | Developers | Sub-agents, slash commands, GitHub integration, TDD workflow automation |
Mode 3 example:
Detailed architecture, workflow examples, and implementation guide: CLAUDE.md
See .claude/README.md for all 11 sub-agents and 20 slash commands.
Feature Comparison
Feature | Mode 1: Desktop | Mode 2: MCP | Mode 3: Repository |
Investment Analysis | ✅ Natural language | ✅ Composable tools | ✅ Advanced automation |
Multi-Account Support | ✅ Automatic | ✅ Manual selection | ✅ Consolidated analysis |
Market Analysis | ✅ Basic | ✅ Detailed | ✅ Parallel + Advanced |
Options Strategies | ✅ Basic | ✅ Detailed | ✅ Professional-grade |
Tax Optimization | ✅ Recommendations | ✅ Custom analysis | ✅ Multi-account optimization |
Development Tools | ❌ | ❌ | ✅ 11 AI specialists |
GitHub Integration | ❌ | ❌ | ✅ Issue → PR automation |
Quality Gates | ❌ | ❌ | ✅ Automated enforcement |
Time to Analysis | 2 minutes | 15 minutes | 15-20 minutes (comprehensive) |
Time to Implementation | N/A | N/A | 8 minutes (vs 80 manual) |
Learning Curve | None | Low | Medium |
Customization | Low | High | Very High |
Recommendation:
Start with Mode 1 if you're an investor looking for quick insights
Use Mode 2 if you need custom analysis or programmatic access
Adopt Mode 3 if you're developing features or need advanced automation
Position History & Time-Series Analysis
IB Analytics automatically stores daily position snapshots in SQLite (data/processed/positions.db) for historical analysis and time-series tracking.
Features: Automatic sync on data fetch, multi-account support, 5 MCP tools for querying history.
Tool | Description |
| Time series for a symbol over a date range |
| All positions on a specific date |
| Portfolio changes between two dates |
| Min/max/average statistics over time |
| List all dates with snapshot data |
Full schema, indexes, and migration procedures: docs/database-schema.md
MCP Server Integration
IB Analytics provides a Model Context Protocol (MCP) server for integration with Claude Desktop and Claude Code.
Features
45 Tools: Portfolio analysis, market data, risk/tax/cost analytics, rebalancing, dividend/sector/FX analysis
9 Resources: Portfolio data, account info, trades, positions, and strategy context via URI patterns
5 Prompts: Pre-configured analysis templates for common workflows
Setup Options
Option 1: Git リポジトリから直接実行(推奨・クローン不要)
インストール不要。設定ファイルに追記するだけで使用できます。
Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json):
Claude Code (プロジェクトの .mcp.json):
Note:
[mcp]extra の指定が必須です(fastmcp,scipy,pyyamlが含まれます)。
キャッシュ: 初回のみ依存関係をダウンロード(
~/.cache/uv)。2回目以降は即座に起動します。最新版を取得したい場合はuvx --refreshオプションを使用してください。
Option 2: ローカルリポジトリから実行(開発者向け)
リポジトリをクローンして開発する場合:
.mcp.json:
Prerequisites
uv インストール済み:
brew install uvまたはcurl -LsSf https://astral.sh/uv/install.sh | shIB Flex Query の
QUERY_IDとTOKEN(IB ポータルで取得)
See MCP Tools Reference for complete documentation of all 45 tools, 9 resources, and 5 prompts.
See .claude/CLAUDE.md for development guide and usage patterns.
Documentation
Document | Description |
Data flow diagrams, layer responsibilities, and new feature decision guide | |
Calculation formulas (YTM, duration, Sharpe, Sortino, phantom income) | |
SQLite position history schema, indexes, and migration procedures | |
Complete reference for all 45 tools, 9 resources, and 5 prompts | |
Docker and docker-compose setup | |
Common errors and solutions | |
ETF calculation accuracy strategy |
Development
Requirements
Python 3.12+
Interactive Brokers account with Flex Query access
Dependencies
requests (2.32.5+): HTTP client for API calls
pandas (2.2.3+): Data analysis and manipulation
pydantic (2.10.0+): Data validation and settings management
httpx (0.27.0+): Async HTTP client for parallel requests
rich (13.7.0+): Beautiful console output
typer (0.12.0+): CLI framework
yfinance (0.2.40+): Yahoo Finance data integration
fastmcp (2.0.0+): Model Context Protocol server framework
Security
MCP Server Security
Error Masking: Internal error details are masked from clients (configurable with
IB_DEBUG=1)Input Validation: All inputs are validated before processing
File Path Protection: Path traversal attacks are prevented
File Size Limits: Maximum file size: 10MB
Timeout Protection: All operations have timeout limits
Retry Logic: Automatic retry for transient errors (max 3 attempts)
Debug Mode
Warning: Never enable debug mode in production as it exposes internal error details.
Credentials Security
Never commit
.envfiles to version controlStore credentials in environment variables or secure secret management systems
Regularly rotate API tokens
Command Selection Guide
For an interactive decision flowchart and full command reference table, see .claude/README.md.
Quick reference:
Investors:
/investment-strategy→/analyze-symbol SYMBOL→/options-strategy SYMBOLDevelopers:
/resolve-gh-issue N→/quality-check→/test
Troubleshooting
For a comprehensive troubleshooting guide with detailed error cases, prevention tips, and the full exception hierarchy, see docs/troubleshooting.md.
Testing
MCP Server Testing
Performance Optimization
If experiencing slow performance:
Reduce date ranges: Fetch smaller time periods
Use file caching: Reuse previously fetched data
Limit technical indicators: Only request needed indicators
License
MIT
Author
Kenichiro Nishioka
Support
For issues and questions, please check the IB Flex Query documentation.