Finance Agent MCP Server
README.md
# Personal Finance & Investment Agent
A production-ready AI agent for personal finance management, investment tracking, and financial recommendations using MCP (Model Context Protocol), FastAPI, and real-time market data.
## Features
- š° **Expense Tracking** - Automatic categorization and budgeting
- š **Portfolio Management** - Real-time portfolio tracking and analysis
- š¤ **AI Financial Advisor** - Personalized investment recommendations
- š **Tax Optimization** - Tax-loss harvesting and optimization strategies
- š **Smart Alerts** - Price alerts and investment notifications
- š¦ **Bank Integration** - Connect to Plaid for automatic transaction sync
## Tech Stack
- **FastAPI** - High-performance async API
- **MCP (Model Context Protocol)** - Agentic AI framework
- **Ollama** - Local LLM for financial analysis
- **PostgreSQL** - Transaction and portfolio storage
- **Redis** - Caching and real-time data
- **yfinance** - Real-time market data
- **Plaid API** - Banking integration
- **Celery** - Background task processing
## Architecture
```
finance-agent/
āāā src/
ā āāā agent/
ā ā āāā finance_advisor.py # Core financial analysis
ā ā āāā portfolio_manager.py # Portfolio optimization
ā ā āāā expense_tracker.py # Expense categorization
ā ā āāā tax_optimizer.py # Tax strategy engine
ā ā āāā mcp_server.py # MCP server implementation
ā āāā api/
ā ā āāā main.py # FastAPI application
ā ā āāā routes/ # API endpoints
ā āāā models/
ā ā āāā database.py # SQLAlchemy models
ā ā āāā schemas.py # Pydantic schemas
ā āāā services/
ā ā āāā market_data.py # Real-time market data
ā ā āāā plaid_service.py # Banking integration
ā ā āāā notification.py # Alert system
ā āāā utils/
ā āāā calculations.py # Financial calculations
ā āāā indicators.py # Technical indicators
āāā mcp/
ā āāā tools/ # MCP tool definitions
ā āāā prompts/ # MCP prompt templates
āāā alembic/ # Database migrations
āāā tests/
āāā requirements.txt
āāā docker-compose.yml
```
## Installation
### Prerequisites
- Python 3.10+
- PostgreSQL 14+
- Redis 7+
- Ollama ([ollama.ai](https://ollama.ai))
- Plaid API keys (optional)
### Setup
```bash
cd finance-agent
# Create virtual environment
python -m venv venv
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Setup database
createdb finance_agent
alembic upgrade head
# Pull Ollama model
ollama pull llama3.2
# Configure environment
cp .env.example .env
# Edit .env with your configuration
# Start services
docker-compose up -d # PostgreSQL, Redis
# Run API server
uvicorn src.api.main:app --reload
# Run MCP server (separate terminal)
python src/agent/mcp_server.py
```
## Usage
### API Endpoints
#### Track Expense
```bash
POST /api/v1/expenses
{
"amount": 45.50,
"description": "Grocery shopping",
"date": "2024-01-15",
"category": "auto" # AI auto-categorizes
}
```
#### Get Budget Analysis
```bash
GET /api/v1/budget/analysis?month=2024-01
```
#### Add Investment
```bash
POST /api/v1/portfolio/positions
{
"symbol": "AAPL",
"quantity": 10,
"purchase_price": 175.50,
"purchase_date": "2024-01-10"
}
```
#### Get Portfolio Performance
```bash
GET /api/v1/portfolio/performance
```
#### Ask Financial Question
```bash
POST /api/v1/ask
{
"question": "Should I rebalance my portfolio?",
"context": "current_holdings"
}
```
### Python Client
```python
from finance_agent import FinanceAgent
# Initialize agent
agent = FinanceAgent(api_key="your_key")
# Track expense with auto-categorization
expense = agent.track_expense(
amount=125.00,
description="Dinner at Italian restaurant"
)
print(f"Categorized as: {expense.category}")
# Analyze portfolio
analysis = agent.analyze_portfolio()
print(f"Total Value: ${analysis.total_value:,.2f}")
print(f"Return: {analysis.total_return_pct:.2f}%")
print(f"Risk Score: {analysis.risk_score}/10")
# Get AI recommendations
recommendations = agent.get_recommendations(
risk_tolerance="moderate",
investment_horizon="long-term"
)
for rec in recommendations:
print(f"{rec.action}: {rec.symbol} - {rec.reason}")
# Tax optimization
tax_strategies = agent.optimize_taxes(tax_year=2024)
print(f"Potential Tax Savings: ${tax_strategies.estimated_savings:,.2f}")
```
### MCP Integration
The agent implements MCP for advanced agentic capabilities:
```python
# MCP tools available:
# - get_portfolio_value: Get current portfolio value
# - analyze_stock: Analyze individual stock
# - calculate_risk: Calculate portfolio risk metrics
# - suggest_rebalance: Get rebalancing suggestions
# - find_tax_opportunities: Find tax-loss harvesting opportunities
# Example MCP conversation
from mcp import MCPClient
client = MCPClient("http://localhost:5000")
response = client.send_message(
"I have $10,000 to invest. I'm 30 years old and want moderate risk. What should I do?"
)
# Agent uses MCP tools to:
# 1. Assess risk tolerance
# 2. Analyze current portfolio
# 3. Research suitable investments
# 4. Generate allocation strategy
# 5. Provide actionable recommendations
```
## Features in Detail
### Expense Tracking
- **Auto-categorization** using AI
- **Receipt OCR** - Extract data from receipts
- **Recurring expense detection**
- **Budget alerts** when overspending
- **Category-wise analytics**
### Portfolio Management
- **Real-time tracking** with yfinance
- **Performance metrics**: ROI, Sharpe ratio, alpha, beta
- **Asset allocation** analysis
- **Rebalancing suggestions**
- **Risk assessment**
### AI Financial Advisor
- **Personalized recommendations** based on:
- Age and income
- Risk tolerance
- Investment goals
- Time horizon
- **Market analysis** and insights
- **Diversification suggestions**
### Tax Optimization
- **Tax-loss harvesting** opportunities
- **Capital gains optimization**
- **Retirement account optimization**
- **Estimated tax calculation**
### Smart Alerts
- **Price alerts** (target prices reached)
- **Portfolio rebalancing** alerts
- **Budget warnings**
- **Market news** affecting holdings
- **Tax deadline reminders**
## Configuration
Edit `.env`:
```env
# Database
DATABASE_URL=postgresql://user:pass@localhost/finance_agent
# Redis
REDIS_URL=redis://localhost:6379/0
# Ollama
OLLAMA_HOST=http://localhost:11434
OLLAMA_MODEL=llama3.2
# Plaid (optional)
PLAID_CLIENT_ID=your_client_id
PLAID_SECRET=your_secret
PLAID_ENV=sandbox
# Market Data
ALPHA_VANTAGE_KEY=your_key # optional
# MCP Server
MCP_HOST=0.0.0.0
MCP_PORT=5000
# Security
JWT_SECRET=your_secret_key
ENCRYPTION_KEY=your_encryption_key
```
## Security Features
- š **End-to-end encryption** for financial data
- š **JWT authentication** for API access
- š”ļø **Role-based access control**
- š **Audit logging** for all transactions
- š **Encrypted database storage**
## Performance
- **Expense categorization:** < 1 second
- **Portfolio analysis:** 2-3 seconds
- **AI recommendations:** 5-10 seconds
- **Real-time price updates:** < 500ms
## Testing
```bash
# Run all tests
pytest tests/
# Test with coverage
pytest --cov=src tests/
# Test specific module
pytest tests/test_portfolio_manager.py
```
## Deployment
```bash
# Docker Compose (recommended)
docker-compose -f docker-compose.prod.yml up -d
# Kubernetes
kubectl apply -f k8s/
# Environment variables
kubectl create secret generic finance-agent-secrets \
--from-env-file=.env.prod
```
## Roadmap
- [ ] Mobile app (React Native)
- [ ] Cryptocurrency portfolio tracking
- [ ] Multi-currency support
- [ ] Social trading features
- [ ] Advanced ML models for prediction
- [ ] Integration with more banks and brokers
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md)
## License
MIT License - see [LICENSE](LICENSE)
## Disclaimer
ā ļø **Important:** This software is for informational purposes only. It does not constitute financial advice. Always consult with a qualified financial advisor before making investment decisions.
## Support
- Website: [useagenticai.in](https://useagenticai.in)
- Issues: [GitHub Issues](https://github.com/AgenticAI-Ind/finance-agent/issues)
- Email: info@useagenticai.in
---
Built with ā¤ļø by the AgenticAI team
This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo issues