Finance Agent MCP Server

Finance Agent MCP Server

MCP server for personal finance management and investment tracking with real-time market data, expense tracking, portfolio management, and AI financial advisor capabilities.

Category
访问服务器

README

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)
  • Plaid API keys (optional)

Setup

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

POST /api/v1/expenses
{
  "amount": 45.50,
  "description": "Grocery shopping",
  "date": "2024-01-15",
  "category": "auto"  # AI auto-categorizes
}

Get Budget Analysis

GET /api/v1/budget/analysis?month=2024-01

Add Investment

POST /api/v1/portfolio/positions
{
  "symbol": "AAPL",
  "quantity": 10,
  "purchase_price": 175.50,
  "purchase_date": "2024-01-10"
}

Get Portfolio Performance

GET /api/v1/portfolio/performance

Ask Financial Question

POST /api/v1/ask
{
  "question": "Should I rebalance my portfolio?",
  "context": "current_holdings"
}

Python Client

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:

# 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:

# 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

# Run all tests
pytest tests/

# Test with coverage
pytest --cov=src tests/

# Test specific module
pytest tests/test_portfolio_manager.py

Deployment

# 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

License

MIT License - see 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


Built with ❤️ by the AgenticAI team

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选