# IB Analytics - Project Summary
**Version**: 0.1.0
**Created**: 2025-10-06
**Author**: Kenichiro Nishioka
---
## ๐ Project Overview
**IB Analytics** is a professional-grade portfolio analytics library for Interactive Brokers with comprehensive multi-account support. Built with modern Python best practices, type safety, and extensible architecture.
### Key Features
โ
**Multi-Account Support** - Analyze multiple IB accounts simultaneously
โ
**Type-Safe** - Pydantic v2 models with runtime validation
โ
**Async Support** - Parallel data fetching with httpx
โ
**Modular Design** - Easy to extend with new analyzers
โ
**CLI Tools** - User-friendly command-line interface
โ
**Rich Reports** - Beautiful console output with Rich library
โ
**Latest Dependencies** - Using stable 2024 versions
---
## ๐๏ธ Architecture
### Layer Structure
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CLI Layer (typer + rich) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Reports Layer (console/html) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Analyzers Layer (5 analyzers) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Core Logic (parser/calc/agg) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Models Layer (Pydantic v2) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ API Layer (sync + async) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
### Components
| Component | Files | Purpose |
|-----------|-------|---------|
| **API Client** | 3 | IB Flex Query API integration |
| **Models** | 4 | Type-safe domain models |
| **Core Logic** | 3 | Parsers, calculations, aggregation |
| **Analyzers** | 6 | Performance, cost, bond, tax, risk |
| **Reports** | 2 | Console and base report classes |
| **CLI** | 3 | Fetch, analyze, report commands |
| **Utils** | 2 | Config and validators |
**Total**: 23 Python modules, ~3,500 lines of code
---
## ๐ฆ Dependencies (Latest Stable)
| Library | Version | Purpose |
|---------|---------|---------|
| **requests** | 2.32.5+ | HTTP API client |
| **pandas** | 2.2.3+ | Data analysis |
| **pydantic** | 2.10.0+ | Data validation |
| **httpx** | 0.27.0+ | Async HTTP |
| **rich** | 13.7.0+ | Console UI |
| **typer** | 0.12.0+ | CLI framework |
### Python Support
- โ
Python 3.9
- โ
Python 3.10
- โ
Python 3.11
- โ
Python 3.12
---
## ๐ Available Analyzers
### 1. PerformanceAnalyzer
**Metrics**: Win rate, profit factor, ROI, risk/reward ratio
**Use Case**: Overall trading performance evaluation
### 2. CostAnalyzer
**Metrics**: Commission rates, cost efficiency, impact on P&L
**Use Case**: Cost optimization and broker comparison
### 3. BondAnalyzer
**Metrics**: YTM, duration, maturity analysis
**Use Case**: Zero-coupon bond (STRIPS) analytics
### 4. TaxAnalyzer
**Metrics**: Phantom income (OID), capital gains tax
**Use Case**: Tax liability estimation
### 5. RiskAnalyzer
**Metrics**: Interest rate scenarios, concentration risk
**Use Case**: Portfolio risk assessment
---
## ๐ Quick Start
### Installation
```bash
# Clone or navigate to project
cd ib-sec
# Install dependencies
pip install -e .
# Verify installation
ib-sec-fetch --help
ib-sec-analyze --help
```
### Configuration
Create `.env` file:
```env
QUERY_ID=your_query_id_here
TOKEN=your_token_here
```
### Basic Usage
```bash
# 1. Fetch data
ib-sec-fetch --start-date 2025-01-01 --end-date 2025-10-05
# 2. Run analysis
ib-sec-analyze data/raw/U1234567_2025-01-01_2025-10-05.csv --all
# 3. View results in console
```
### Programmatic Usage
```python
from ib_sec_mcp import FlexQueryClient
from ib_sec_mcp.analyzers import PerformanceAnalyzer
from ib_sec_mcp.core.parsers import CSVParser
# Fetch data
client = FlexQueryClient(query_id="...", token="...")
statement = client.fetch_statement(start_date, end_date)
# Parse
account = CSVParser.to_account(statement.raw_data, start_date, end_date)
# Analyze
analyzer = PerformanceAnalyzer(account=account)
results = analyzer.analyze()
print(results)
```
---
## ๐ Project Structure
```
ib-sec/
โโโ .claude/ # Claude Code configuration
โ โโโ CLAUDE.md # Project context (313 lines)
โ โโโ README.md # .claude directory guide
โ โโโ commands/ # Custom slash commands (5)
โ โโโ analyze-all.md
โ โโโ fetch-latest.md
โ โโโ add-analyzer.md
โ โโโ explain-architecture.md
โ โโโ debug-api.md
โโโ ib_sec_mcp/ # Main library package
โ โโโ api/ # API client (3 files)
โ โโโ core/ # Business logic (3 files)
โ โโโ models/ # Data models (4 files)
โ โโโ analyzers/ # Analyzers (6 files)
โ โโโ reports/ # Report generators (2 files)
โ โโโ utils/ # Utilities (2 files)
โ โโโ cli/ # CLI tools (3 files)
โโโ scripts/ # Example scripts
โ โโโ example_usage.py
โโโ tests/ # Test framework (to be implemented)
โโโ legacy/ # Original scripts (10 files)
โโโ data/ # Data storage
โ โโโ raw/ # Raw CSV files
โ โโโ processed/ # Analysis results
โโโ pyproject.toml # Project metadata
โโโ requirements.txt # Pip dependencies
โโโ README.md # User documentation
โโโ INSTALL.md # Installation guide
โโโ CHANGELOG.md # Version history
โโโ .env # API credentials (not committed)
```
---
## ๐ฏ Design Patterns Used
### Template Method (BaseAnalyzer)
```python
class BaseAnalyzer(ABC):
@abstractmethod
def analyze(self) -> AnalysisResult:
pass
class PerformanceAnalyzer(BaseAnalyzer):
def analyze(self) -> AnalysisResult:
# Implementation
return self._create_result(...)
```
### Strategy (Reports)
```python
class BaseReport(ABC):
@abstractmethod
def render(self) -> str:
pass
class ConsoleReport(BaseReport):
def render(self) -> str:
# Console-specific rendering
```
### Factory (Parsers)
```python
account = CSVParser.to_account(csv_data, from_date, to_date)
```
### Builder (Portfolio)
```python
portfolio = Portfolio.from_accounts(accounts, base_currency="USD")
```
---
## ๐ง Development Workflow
### Adding New Features
1. **New Analyzer**
```bash
# Use custom command
/add-analyzer Sharpe "Calculate Sharpe ratio"
```
2. **Update Context**
```bash
# Press # in Claude Code
# "New analyzers must calculate annualized metrics"
```
3. **Format & Lint**
```bash
black ib_sec_mcp tests
ruff check ib_sec_mcp tests
mypy ib_sec_mcp
```
### Testing (Future)
```bash
# Run tests
pytest
# With coverage
pytest --cov=ib_sec_mcp --cov-report=html
# Specific test
pytest tests/test_analyzers/test_performance.py
```
---
## ๐ Documentation
### User Documentation
- **README.md**: Quick start and usage guide
- **INSTALL.md**: Detailed installation instructions
- **CHANGELOG.md**: Version history and changes
### Developer Documentation
- **.claude/CLAUDE.md**: Project context for Claude Code
- **.claude/README.md**: Claude Code configuration guide
- **Inline Docstrings**: Google-style in all modules
### API Documentation (Future)
- Sphinx auto-generated docs
- GitHub Pages deployment
- Interactive examples
---
## ๐จ Code Quality Standards
### Style
- **Formatter**: Black (100 char line length)
- **Linter**: Ruff (E, F, I, N, W, UP, B, A, C4, T20, SIM)
- **Type Checker**: mypy (strict mode)
### Conventions
- **Classes**: PascalCase
- **Functions**: snake_case
- **Constants**: UPPER_SNAKE_CASE
- **Private**: _leading_underscore
### Documentation
- **Docstrings**: Required for all public APIs
- **Type Hints**: Required for all functions
- **Comments**: Explain why, not what
---
## ๐ฎ Future Roadmap
### Phase 1 (Current) โ
- [x] Core library structure
- [x] Multi-account support
- [x] 5 core analyzers
- [x] CLI tools
- [x] Console reports
### Phase 2 (Next)
- [ ] Unit tests with pytest
- [ ] HTML reports with charts
- [ ] XML parser implementation
- [ ] Additional analyzers (Sharpe, Drawdown)
- [ ] Documentation site
### Phase 3 (Future)
- [ ] PDF report generation
- [ ] Web dashboard (Streamlit)
- [ ] Real-time data streaming
- [ ] Backtesting framework
- [ ] Portfolio optimization
### Phase 4 (Advanced)
- [ ] Machine learning predictions
- [ ] Automated trading signals
- [ ] Risk management alerts
- [ ] Mobile app integration
---
## ๐ Migration from Legacy Scripts
### Before (Legacy Scripts)
```
ib-sec/
โโโ analyze_performance.py # Standalone script
โโโ trading_cost_analysis.py # Standalone script
โโโ phantom_income_tax_analysis.py
โโโ bond_analysis.py
โโโ interest_rate_scenario_analysis.py
โโโ comprehensive_summary_report.py
```
**Issues**:
- โ Code duplication
- โ No type safety
- โ Hard to test
- โ No multi-account support
- โ Monolithic structure
### After (New Library)
```
ib_sec_mcp/
โโโ analyzers/
โ โโโ performance.py # Modular
โ โโโ cost.py # Reusable
โ โโโ bond.py # Type-safe
โ โโโ tax.py # Testable
โ โโโ risk.py # Extensible
```
**Benefits**:
- โ
Modular architecture
- โ
Type safety (Pydantic)
- โ
Easy to test
- โ
Multi-account support
- โ
CLI + programmatic API
---
## ๐ค Contributing
### Adding New Analyzer
1. Create `ib_sec_mcp/analyzers/your_analyzer.py`
2. Inherit from `BaseAnalyzer`
3. Implement `analyze()` method
4. Add to `__init__.py` exports
5. Update `ConsoleReport` rendering
6. Add CLI integration
7. Write tests
8. Update documentation
### Custom Slash Commands
1. Create `.claude/commands/your-command.md`
2. Write natural language instructions
3. Use `$ARGUMENTS` for parameters
4. Test with `/your-command`
5. Commit to git
---
## ๐ Support
### Issues
- Check existing issues in git
- Include error messages and logs
- Provide minimal reproduction steps
### Questions
- Review `.claude/CLAUDE.md`
- Check README and INSTALL guides
- Use `/explain-architecture` command
---
## ๐ License
MIT License - See LICENSE file for details
---
## ๐ Acknowledgments
- **Interactive Brokers**: Flex Query API
- **Pydantic**: Type-safe data models
- **Rich**: Beautiful console output
- **Typer**: User-friendly CLI
- **Anthropic**: Claude Code integration
---
**Last Updated**: 2025-10-06
**Status**: Production Ready (v0.1.0)
**Maintainer**: Kenichiro Nishioka
For detailed information, see:
- [README.md](README.md) - User guide
- [INSTALL.md](INSTALL.md) - Installation
- [CHANGELOG.md](CHANGELOG.md) - Version history
- [.claude/CLAUDE.md](.claude/CLAUDE.md) - Developer context