Skip to main content
Glama
locupleto

mcp-strategy-research-db

by locupleto
README.md
# mcp-strategy-research-db

A Model Context Protocol (MCP) server that provides Claude Code access to a strategy research SQLite database for analyzing trading strategy backtest results.

## Features

- Analyze strategy performance across multiple market periods
- Find strategies that work across all market regimes (robust strategies)
- Compare strategies against Buy & Hold benchmarks
- Query risk-adjusted metrics (Calmar ratio, Sharpe ratio)
- Find alpha-generating strategies that beat benchmarks
- Analyze strategy consistency across different symbols
- Run custom SQL queries (read-only) for advanced analysis

## Installation

```bash
# Clone the repository
git clone https://github.com/locupleto/mcp-strategy-research-db.git
cd mcp-strategy-research-db

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt
```

## Configuration

Set the required environment variable:

```bash
export STRATEGY_DB_PATH=/path/to/strategy_research.db
```

The database is typically generated by the `trading-lab` project's strategy search scripts.

## Register with Claude Code

MCP servers can be registered at two scopes:

### Project Level (Recommended)

Registers the server for the current project only. The configuration is stored in `~/.claude.json` under the project's path. This is the recommended approach for project-specific tools.

```bash
cd /Volumes/Work/development/projects/git/mcp-strategy-research-db

claude mcp add strategy-research-db \
    "$(pwd)/venv/bin/python3" \
    "$(pwd)/strategy_research_mcp_server.py"
```

This adds the server to `~/.claude.json` under the project's `mcpServers` configuration:
```json
{
  "projects": {
    "/Volumes/Work/development/projects/git/mcp-strategy-research-db": {
      "mcpServers": {
        "strategy-research-db": {
          "type": "stdio",
          "command": "/Volumes/Work/development/projects/git/mcp-strategy-research-db/venv/bin/python3",
          "args": [
            "/Volumes/Work/development/projects/git/mcp-strategy-research-db/strategy_research_mcp_server.py"
          ]
        }
      }
    }
  }
}
```

### User Level (Global)

Registers the server globally, available in all projects. Use the `-s user` flag:

```bash
claude mcp add -s user strategy-research-db \
    "$(pwd)/venv/bin/python3" \
    "$(pwd)/strategy_research_mcp_server.py"
```

### Verify Registration

```bash
# List all registered MCP servers
claude mcp list

# Debug mode for troubleshooting
claude --mcp-debug
```

## Tools (17 total)

### Database Overview
| Tool | Description |
|------|-------------|
| `get_database_status` | Database statistics: runs, strategies, symbols, date ranges |
| `list_search_runs` | List all backtest runs with filtering options |
| `get_run_details` | Get detailed information about a specific search run |

### Strategy Analysis
| Tool | Description |
|------|-------------|
| `get_top_strategies` | Get top-ranked strategies with customizable sorting and filters |
| `get_strategy_details` | Get full details for a specific strategy ID |
| `compare_strategy_across_periods` | Analyze how a strategy performs across different market periods |

### Cross-Period Robustness
| Tool | Description |
|------|-------------|
| `find_robust_strategies` | Find strategies that work consistently across ALL market periods |
| `get_period_summary` | Summary statistics for each market period tested |

### Benchmark Analysis
| Tool | Description |
|------|-------------|
| `find_alpha_generators` | Find strategies that beat Buy & Hold benchmark |
| `get_risk_adjusted_rankings` | Rank strategies by Calmar ratio or other risk-adjusted metrics |

### Symbol Analysis
| Tool | Description |
|------|-------------|
| `get_symbol_performance` | Performance breakdown by individual symbol |
| `find_best_symbols_for_strategy` | Find which symbols work best with a given strategy |

### Capital Deployment Analysis
| Tool | Description |
|------|-------------|
| `get_capital_deployment_analysis` | Analyze portfolio capital utilization across periods using time-in-market data |
| `get_daily_position_counts` | Get exact daily position counts from trade-level data (requires Dec 2025+ runs) |
| `compare_timing_modes` | Compare Conservative (T+1) vs Aggressive (same-day) trade timing |

### Advanced
| Tool | Description |
|------|-------------|
| `run_custom_query` | Execute custom SQL queries (read-only) |
| `get_schema` | Get database schema documentation |
| `list_strategy_ids` | List strategy IDs with optional pattern filtering |

## Key Metrics Explained

### Performance Metrics
- **Expectancy**: Expected return per trade (%)
- **Win Rate**: Percentage of winning trades
- **Profit Factor**: Gross profit / Gross loss ratio
- **CAGR**: Compound Annual Growth Rate

### Risk Metrics
- **Max Drawdown**: Largest peak-to-trough decline
- **Calmar Ratio**: CAGR / Max Drawdown (higher = better risk-adjusted returns)
- **Sharpe Ratio**: Risk-adjusted return relative to risk-free rate

### Consistency Metrics
- **Consistency Score**: % of symbols where strategy is profitable
- **Symbols Beating Benchmark**: % of symbols that outperform Buy & Hold

## Example Usage

```
# Get overview of the database
> get_database_status

# Find strategies that work in ALL market periods
> find_robust_strategies min_periods=6 min_consistency=0.7

# Get top strategies for a specific period
> get_top_strategies period_name="2008 Financial Crisis" sort_by="median_calmar_ratio" limit=10

# Compare a strategy across all periods
> compare_strategy_across_periods strategy_id="buy_adm_momentum_low__sell_adm_momentum_high"

# Find alpha generators
> find_alpha_generators min_alpha=5.0 min_beat_rate=0.6
```

## Database Schema

The SQLite database contains four main tables:

### search_runs
Metadata about each backtest run (study, period, date range, benchmark data)

### aggregated_results
Strategy-level aggregated metrics using MEDIAN values across all symbols tested

### symbol_results
Per-symbol backtest results for detailed analysis

### trade_results (Dec 2025+)
Individual trade records with entry/exit dates for daily position count analysis. Enables exact portfolio-level capital deployment tracking over time.

## Requirements

- Python 3.10+
- MCP SDK (`mcp>=2,<3`)
- SQLite strategy research database (from trading-lab project)

## Related Projects

- `trading-lab`: Strategy backtesting and signal research platform
- `mcp-marketdata-db`: Market data MCP server

## License

MIT