Skip to content

About

Multi-agent assistant for vectorbtpro strategy development and backtesting, with a Next.js web UI.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

6 Commits

Folders and files

Repository files navigation

VectorBT Pro Agent System

A sophisticated multi-agent system for vectorbtpro that uses specialized AI agents to help with trading strategy development, backtesting, optimization, and analysis.

Status: personal research project. Not investment advice and not production software.

🎨 Web Interface Available!

NEW: Beautiful web interface built with Next.js, shadcn/ui, and Tailwind CSS v3!

# Quick start the web interface
./start_web.sh

# Or manually:
# Terminal 1: cd backend && python main.py
# Terminal 2: cd frontend && npm run dev
# Open http://localhost:3000

See WEB_README.md for complete web interface documentation.

Overview

This system consists of:

  • 7 Specialist Agents - Each expert in a specific domain of vectorbtpro
  • 1 Master Coordinator - Delegates tasks and synthesizes results
  • Web Interface - Beautiful UI for interacting with agents (NEW!)
  • CLI Interface - Interactive command-line interface
  • Python API - Programmatic access

The Master Agent intelligently routes requests to the appropriate specialist agents, coordinates multi-step workflows, and provides comprehensive summaries.

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚           Master Agent                       β”‚
β”‚  (Coordination, Delegation, Synthesis)       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                  β”‚
                  β”‚ Delegates to
                  β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚                            β”‚
    β–Ό                            β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚Portfolioβ”‚  β”‚Indicatorβ”‚  β”‚Backtest β”‚  ...
β”‚ Agent   β”‚  β”‚ Agent   β”‚  β”‚ Agent   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Specialist Agents

1. Portfolio Agent

Expertise: Portfolio construction, optimization, and rebalancing

Capabilities:

  • Portfolio construction
  • Asset allocation strategies
  • Rebalancing methodologies
  • Risk-parity portfolios
  • Efficient frontier analysis

Example Tasks:

  • "Create an equal-weighted portfolio"
  • "Optimize weights for maximum Sharpe ratio"
  • "Implement a monthly rebalancing strategy"

2. Indicator Agent

Expertise: Technical indicators and signal generation

Capabilities:

  • Technical indicators (RSI, MACD, Bollinger Bands, etc.)
  • Signal generation
  • Custom indicator development
  • Indicator combinations

Example Tasks:

  • "Create RSI-based entry signals"
  • "Combine MACD and Bollinger Bands"
  • "Build a custom momentum indicator"

3. Backtest Agent

Expertise: Strategy backtesting and performance analysis

Capabilities:

  • Strategy backtesting
  • Performance metrics calculation
  • Trade analysis
  • Benchmark comparison
  • Walk-forward testing

Example Tasks:

  • "Backtest a moving average crossover"
  • "Calculate Sharpe and Sortino ratios"
  • "Compare strategy vs S&P 500"

4. Data Agent

Expertise: Data fetching, cleaning, and preparation

Capabilities:

  • Data fetching from various sources
  • Data cleaning and validation
  • Missing data handling
  • Multi-asset alignment
  • Time series preparation

Example Tasks:

  • "Fetch OHLCV data for tech stocks"
  • "Clean and align multi-asset data"
  • "Handle missing values in price data"

5. Optimization Agent

Expertise: Parameter optimization and hyperparameter tuning

Capabilities:

  • Parameter optimization
  • Grid search
  • Walk-forward optimization
  • Overfitting prevention
  • Sensitivity analysis

Example Tasks:

  • "Optimize RSI periods"
  • "Perform walk-forward analysis"
  • "Find optimal moving average lengths"

6. Visualization Agent

Expertise: Data visualization and reporting

Capabilities:

  • Interactive charts
  • Equity curves
  • Drawdown visualization
  • Heatmaps
  • Performance reports

Example Tasks:

  • "Plot equity curve with drawdowns"
  • "Create indicator overlay chart"
  • "Visualize optimization results"

7. Risk Agent

Expertise: Risk management and analysis

Capabilities:

  • Risk metrics (VaR, CVaR, etc.)
  • Position sizing
  • Drawdown analysis
  • Risk-adjusted returns
  • Stop-loss strategies

Example Tasks:

  • "Calculate Value at Risk"
  • "Implement volatility-based position sizing"
  • "Analyze maximum drawdown"

Installation

  1. Clone the repository:
git clone <repository-url>
cd FernandoGatti
  1. Install dependencies:
pip install -r requirements.txt
  1. Set up environment variables:
# Create .env file
echo "ANTHROPIC_API_KEY=your_api_key_here" > .env

Usage

Web Interface (Recommended) 🌐

The easiest way to use the system is through the beautiful web interface:

# Quick start (runs both backend and frontend)
./start_web.sh

# Or start manually:
# Terminal 1 - Backend:
cd backend && python main.py

# Terminal 2 - Frontend:
cd frontend && npm install && npm run dev

# Open browser to http://localhost:3000

Features:

  • Modern dashboard with real-time stats
  • Visual agent cards showing capabilities
  • Task submission with examples
  • Beautiful results display
  • Task history tracking
  • Dark mode by default

See WEB_README.md for detailed web interface documentation.

Interactive CLI

Command-line interface for terminal users:

python examples/interactive_cli.py

Commands:

  • Type any question or request in natural language
  • agents - Show all available agents
  • history - Show task history
  • info <agent> - Get details about a specific agent
  • help - Show help
  • exit - Exit the system

Example Interactions:

You: Create a simple moving average crossover strategy and backtest it

[Master Agent processes and delegates to indicator and backtest agents]

You: Optimize the parameters for best Sharpe ratio

[Master Agent delegates to optimization agent]

You: Show me the risk metrics and equity curve

[Master Agent delegates to risk and visualization agents]

Programmatic Usage

from agents import MasterAgent

# Initialize
master = MasterAgent()

# Display available agents
master.display_agents()

# Process a request
result = master.process_request(
    "Create a momentum strategy using RSI and backtest it"
)

# Access results
print(result["summary"])
print(result["task_plan"])

# Get agent info
info = master.get_agent_info("portfolio")
print(info)

# View history
history = master.get_task_history()

Basic Examples

python examples/basic_usage.py

This runs several predefined examples demonstrating different capabilities.

How It Works

  1. User Request β†’ You ask a question or make a request
  2. Analysis β†’ Master Agent analyzes the request
  3. Planning β†’ Creates a task plan identifying which agents are needed
  4. Delegation β†’ Delegates tasks to specialist agents
  5. Execution β†’ Each agent processes their assigned task
  6. Synthesis β†’ Master Agent combines results into a coherent summary
  7. Response β†’ You receive a comprehensive answer with code examples

Example Workflows

Simple Workflow

Request: "Create RSI indicator signals"
β†’ Indicator Agent generates signals
β†’ Master Agent returns code and explanation

Complex Multi-Agent Workflow

Request: "Build and optimize a complete trading system"
β†’ Data Agent: Fetches historical data
β†’ Indicator Agent: Creates technical indicators
β†’ Backtest Agent: Backtests the strategy
β†’ Optimization Agent: Optimizes parameters
β†’ Risk Agent: Analyzes risk metrics
β†’ Visualization Agent: Creates charts
β†’ Master Agent: Synthesizes complete report

Configuration

Environment Variables

Create a .env file:

# Required
ANTHROPIC_API_KEY=your_api_key_here

# Optional
DEFAULT_MODEL=claude-3-5-sonnet-20241022

Agent Configuration

You can customize agents by modifying their system prompts in agents/<agent_name>_agent.py.

Advanced Usage

Using Individual Agents

from agents import PortfolioAgent, BacktestAgent

# Use a specific agent directly
portfolio_agent = PortfolioAgent()

# Get capabilities
capabilities = portfolio_agent.get_capabilities()

# Process a task
from utils.message_types import TaskRequest
import uuid

task = TaskRequest(
    task_id=str(uuid.uuid4()),
    requester="user",
    agent_type="portfolio",
    description="Create an equal-weighted portfolio",
    parameters={"symbols": ["AAPL", "GOOGL", "MSFT"]}
)

response = portfolio_agent.process_task(task)
print(response.result)

Custom Agents

Create your own specialist agent:

from agents.base_agent import BaseAgent
from utils.message_types import AgentCapability

class MyCustomAgent(BaseAgent):
    def __init__(self):
        super().__init__(agent_type="custom")

    def get_capabilities(self) -> AgentCapability:
        return AgentCapability(
            agent_type=self.agent_type,
            description="My custom agent description",
            capabilities=["capability1", "capability2"],
            example_tasks=["Example task 1", "Example task 2"]
        )

    def get_system_prompt(self) -> str:
        return "Your custom system prompt here..."

Project Structure

FernandoGatti/
β”œβ”€β”€ agents/                     # Agent system
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ base_agent.py           # Base agent class
β”‚   β”œβ”€β”€ master_agent.py         # Master coordinator
β”‚   β”œβ”€β”€ portfolio_agent.py      # Portfolio specialist
β”‚   β”œβ”€β”€ indicator_agent.py      # Indicator specialist
β”‚   β”œβ”€β”€ backtest_agent.py       # Backtest specialist
β”‚   β”œβ”€β”€ data_agent.py           # Data specialist
β”‚   β”œβ”€β”€ optimization_agent.py   # Optimization specialist
β”‚   β”œβ”€β”€ visualization_agent.py  # Visualization specialist
β”‚   └── risk_agent.py           # Risk specialist
β”œβ”€β”€ utils/                      # Utilities
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── message_types.py        # Message types for communication
β”œβ”€β”€ examples/                   # CLI examples
β”‚   β”œβ”€β”€ basic_usage.py          # Basic examples
β”‚   β”œβ”€β”€ interactive_cli.py      # Interactive CLI
β”‚   └── test_setup.py           # Setup verification
β”œβ”€β”€ backend/                    # FastAPI backend (NEW!)
β”‚   β”œβ”€β”€ main.py                 # API server
β”‚   └── requirements.txt        # Backend dependencies
β”œβ”€β”€ frontend/                   # Next.js frontend (NEW!)
β”‚   β”œβ”€β”€ app/                    # Next.js app directory
β”‚   β”‚   β”œβ”€β”€ globals.css         # Tailwind + theme
β”‚   β”‚   β”œβ”€β”€ layout.tsx          # Root layout
β”‚   β”‚   └── page.tsx            # Main dashboard
β”‚   β”œβ”€β”€ components/             # React components
β”‚   β”‚   β”œβ”€β”€ ui/                 # shadcn/ui components
β”‚   β”‚   β”œβ”€β”€ agent-card.tsx      # Agent display
β”‚   β”‚   β”œβ”€β”€ task-form.tsx       # Task submission
β”‚   β”‚   β”œβ”€β”€ result-display.tsx  # Results view
β”‚   β”‚   └── stats-card.tsx      # Statistics
β”‚   β”œβ”€β”€ lib/                    # Utilities
β”‚   β”œβ”€β”€ package.json            # Frontend dependencies
β”‚   └── tailwind.config.ts      # Tailwind config
β”œβ”€β”€ requirements.txt            # Core dependencies
β”œβ”€β”€ start_web.sh                # Web interface launcher
β”œβ”€β”€ README.md                   # This file
└── WEB_README.md               # Web interface docs

Requirements

Core System

  • Python 3.8+
  • vectorbtpro >= 1.0.0
  • anthropic >= 0.18.0
  • rich >= 13.0.0
  • pydantic >= 2.0.0
  • python-dotenv >= 1.0.0

Web Interface (Optional)

  • Node.js 18+ (for frontend)
  • FastAPI (for backend API)
  • Next.js 14 (frontend framework)
  • See backend/requirements.txt and frontend/package.json for details

Tips for Best Results

  1. Be specific - The more specific your request, the better the results
  2. Use multiple steps - Break complex tasks into steps for the agents
  3. Review code - Always review generated code before using in production
  4. Iterate - Refine your requests based on the results
  5. Combine agents - Complex workflows often benefit from multiple agents

Example Requests

Data & Preparation:

  • "Fetch OHLCV data for AAPL, GOOGL, MSFT from 2020 to 2024"
  • "Clean the data and handle missing values"

Indicators & Signals:

  • "Create RSI indicator with 14-period"
  • "Generate buy signals when RSI crosses above 30"
  • "Combine MACD and Bollinger Bands for entry signals"

Backtesting:

  • "Backtest a simple moving average crossover strategy"
  • "Calculate all performance metrics including Sharpe ratio"
  • "Compare against buy-and-hold benchmark"

Optimization:

  • "Optimize RSI periods from 10 to 30"
  • "Perform walk-forward optimization to prevent overfitting"
  • "Find parameters that maximize risk-adjusted returns"

Portfolio:

  • "Create a risk-parity portfolio with 5 assets"
  • "Optimize portfolio weights for maximum Sharpe ratio"
  • "Implement monthly rebalancing"

Risk Management:

  • "Calculate Value at Risk at 95% confidence"
  • "Implement volatility-based position sizing"
  • "Analyze maximum drawdown and recovery periods"

Visualization:

  • "Plot equity curve with drawdown overlay"
  • "Create heatmap of optimization results"
  • "Visualize rolling Sharpe ratio"

Troubleshooting

Issue: API Key Error

  • Make sure ANTHROPIC_API_KEY is set in .env file
  • Verify the API key is valid

Issue: Module Not Found

  • Run pip install -r requirements.txt
  • Make sure you're in the correct directory

Issue: Agent Not Responding

  • Check your internet connection
  • Verify API rate limits haven't been exceeded

Contributing

Contributions are welcome! Areas for improvement:

  • Additional specialist agents
  • Enhanced task planning algorithms
  • Better result synthesis
  • More example workflows
  • Performance optimizations

License

No license has been set for this repository yet.

Support

For issues, questions, or contributions, please open an issue on GitHub.


Built with ❀️ using Claude 3.5 Sonnet and vectorbtpro

About

Multi-agent assistant for vectorbtpro strategy development and backtesting, with a Next.js web UI.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages