Skip to main content
Glama
irohan0

Quant Research Assistant

by irohan0
README.md
# πŸ“ˆ Quant Research Assistant β€” MCP Server & Claude Plugin

> A one-stop quantitative-finance toolkit that gives Claude live financial reasoning β€”
> price & risk analysis, strategy backtesting, **HMM market-regime detection**, options
> greeks, fundamentals & DCF valuation, news sentiment, **regime-aware Monte Carlo**,
> pairs trading, Fama-French factor attribution, portfolio optimisation, and a single
> **composite quant score**. Every data source is free β€” no API keys.

Built by **Rohan Inamdar** Β· [imrohaninamdar.com](https://imrohaninamdar.com) Β· [GitHub](https://github.com/irohan0)

---

## What makes this different

Most quant tools give you a notebook or a dashboard. This gives Claude *live financial
reasoning*: you talk to it in plain English, it calls production-grade financial tools under
the hood, returns charts and structured data, and narrates the results.

Two standout, non-library features:
- **HMM Market Regime Detection** β€” an unsupervised Gaussian Hidden Markov Model trained on
  return, realised-volatility, momentum and z-score features that classifies market states
  (Bull / Bear / High-Volatility / Sideways) in real time.
- **Regime-aware Monte Carlo** β€” forward price simulation that switches between calm and
  stressed regimes using the HMM's transition matrix, so the downside tail looks like real
  markets instead of a tidy bell curve.

---

## Tools (20)

### Analysis
| Tool | What it does |
|------|-------------|
| `price_history` | OHLCV fetch with candlestick + Bollinger + volume chart |
| `risk_metrics` | Sharpe, Sortino, Calmar, VaR, CVaR, beta, Jensen's alpha, skew, kurtosis |
| `backtest` | Vectorised SMA / RSI / Momentum / MACD vs buy-and-hold |
| `market_regime` | **Gaussian HMM** regime classification + transition matrix + posteriors |
| `portfolio_optimisation` | Max-Sharpe, Min-Vol, Risk-Parity + efficient frontier + correlation heatmap |
| `macro_overlay` | FRED macro indicators (rates, CPI YoY, VIX, yield curve) + rolling correlation |
| `options_analytics` | IV skew, put/call ratio, max pain, IV term structure, in-house **Black-Scholes greeks** |
| `fundamentals` | Ratios + **two-stage DCF / reverse-DCF** + **Piotroski F-Score** + **Altman Z-Score** |
| `sentiment` | Multi-source news headline sentiment (VADER over yfinance + Yahoo/Google RSS) |
| `monte_carlo` | **Regime-aware** / GBM / bootstrap forward simulation, fan chart, hit-probability, projected VaR |
| `technicals` | RSI, MACD, Bollinger, ADX, Stochastic, ATR, OBV, S/R, patterns β†’ composite signal |
| `pairs` | Engle-Granger + ADF cointegration, hedge ratio, half-life, z-score backtest |
| `factors` | **Fama-French 3-factor + momentum** regression (betas, alpha, RΒ², contributions) |
| `composite_score` | **One 0–100 score + Strong-Buyβ†’Strong-Sell verdict** blending all lenses |

### Persistent state
`add_to_watchlist` Β· `remove_from_watchlist` Β· `show_watchlist` Β· `save_portfolio_tool` Β· `load_portfolio_tool` Β· `list_portfolios_tool`

### Slash command
`/quant-deep-dive <TICKER>` β€” chains the tools into one narrated deep-dive report.

---

## Architecture

```
Claude (MCP client)
        β”‚  MCP protocol
        β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  MCP Server (Python / FastMCP) β€” 20 tools                β”‚
β”‚  prices Β· metrics Β· backtest Β· regime Β· portfolio Β· macro β”‚
β”‚  options Β· fundamentals Β· sentiment Β· montecarlo          β”‚
β”‚  technicals Β· pairs Β· factors Β· score Β· watchlist         β”‚
β”‚  Shared compute: pandas Β· numpy Β· scipy Β· hmmlearn Β·      β”‚
β”‚                  scikit-learn Β· statsmodels               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
        β”‚
        β–Ό  data sources (all free, no keys)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚yfinanceβ”‚ β”‚ FRED CSV β”‚ β”‚ Ken French Lib β”‚ β”‚ Yahoo/Google  β”‚ β”‚SQLite cacheβ”‚
β”‚(prices,β”‚ β”‚ (macro)  β”‚ β”‚ (FF factors)   β”‚ β”‚ RSS (news)    β”‚ β”‚+watchlist  β”‚
β”‚options,β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚fund.)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## Quick start

### 1. Install
```bash
git clone https://github.com/irohan0/quant-mcp.git
cd quant-mcp
python -m venv .venv && . .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install -r requirements.txt
```

### 2. Run the MCP server
```bash
python server.py
```

### 3a. Use as a Claude Code plugin (recommended: clone + local marketplace)
The tools run a **local Python process**, so the machine needs the dependencies. The reliable
install is to clone, build the `.venv` (step 1 above), then add the local checkout as a marketplace:
```
/plugin marketplace add /path/to/quant-mcp     # CLAUDE_PLUGIN_ROOT β†’ your checkout (has .venv)
/plugin install quant-research-assistant
```
The 20 tools and the `/quant-deep-dive` command then appear in your session. Verify with
`claude mcp list` β†’ look for `plugin:quant-research-assistant … √ Connected`.

> **Why local (not a bare GitHub-marketplace install):** the plugin's MCP config
> ([mcp-config.json](mcp-config.json)) launches `${CLAUDE_PLUGIN_ROOT}/.venv/Scripts/python.exe`.
> A local-path install points `CLAUDE_PLUGIN_ROOT` at your checkout, where the `.venv` lives. A
> pure `marketplace add <github-url>` clones the repo *without* the (git-ignored) `.venv`, so the
> server has no interpreter. If you install from GitHub, create a `.venv` + `pip install` inside
> the plugin's cache dir, or edit its `mcp-config.json` to point at a Python that has the deps.
> **On macOS/Linux** change the path to `${CLAUDE_PLUGIN_ROOT}/.venv/bin/python`.

### 3b. Use with Claude Desktop
Add to `claude_desktop_config.json`:
```json
{
  "mcpServers": {
    "quant-research-assistant": {
      "command": "/path/to/quant-mcp/.venv/bin/python",
      "args": ["/path/to/quant-mcp/server.py"]
    }
  }
}
```

### 4. (Optional) Gradio web UI for demos
```bash
python web/app.py      # http://localhost:7860 β€” a tab per tool
```

---

## Example prompts

```
"Give me the quant score for NVDA and explain the breakdown"

"/quant-deep-dive AAPL"

"Run a regime-aware Monte Carlo on TSLA for the next quarter β€” what's the
 probability it reaches $400, and what's the projected downside?"

"Show me AAPL's options: IV skew, put/call positioning, max pain and ATM greeks"

"Is KO–PEP cointegrated, and what does the pairs backtest look like?"

"What are SPY's Fama-French factor exposures and alpha over 3 years?"

"Build a max-Sharpe portfolio from AAPL, MSFT, GOOGL, SPY, BND, GLD and save it as 'core'"
```

---

## Running tests

```bash
pytest tests/ -v       # 51 unit tests, fully network-free (synthetic data + mocks)
```

---

## Tech stack

- **MCP**: `mcp[cli]` (FastMCP)
- **Data (all free)**: `yfinance` (prices, options, fundamentals), FRED CSV, Ken French Data
  Library, Yahoo/Google Finance RSS
- **Compute**: `pandas`, `numpy`, `scipy`, `statsmodels`
- **ML**: `hmmlearn` (Gaussian HMM), `scikit-learn`
- **Sentiment**: `vaderSentiment`, `feedparser`
- **Charts**: `matplotlib` (dark theme, base64 PNG)
- **Web UI**: `gradio`
- **Cache & state**: `sqlite3` (price cache + watchlist/portfolios)

---

## Project structure

```
quant-mcp/
β”œβ”€β”€ server.py                  ← MCP server (registers all 20 tools)
β”œβ”€β”€ mcp-config.json            ← MCP server config (referenced by the plugin)
β”œβ”€β”€ .claude-plugin/
β”‚   β”œβ”€β”€ plugin.json            ← Claude Code plugin manifest
β”‚   └── marketplace.json       ← single-plugin marketplace
β”œβ”€β”€ commands/
β”‚   └── quant-deep-dive.md     ← /quant-deep-dive slash command
β”œβ”€β”€ tools/
β”‚   β”œβ”€β”€ utils.py               ← caching, fetch, FRED, chart helpers
β”‚   β”œβ”€β”€ prices.py  metrics.py  backtest.py  regime.py  portfolio.py  macro.py
β”‚   β”œβ”€β”€ options.py  fundamentals.py  sentiment.py  montecarlo.py
β”‚   β”œβ”€β”€ technicals.py  pairs.py  factors.py  score.py  watchlist.py
β”œβ”€β”€ web/app.py                 ← Gradio web UI (tab per tool)
β”œβ”€β”€ tests/test_tools.py        ← 51 network-free unit tests
└── pyproject.toml
```

---

## Notes
- All data sources are free β€” no API keys required.
- Charts are base64-encoded PNGs in the `chart_png_b64` field β€” render them for the user.
- SQLite cache avoids redundant fetches (12h TTL for prices, 24h for fundamentals/factors).
- yfinance and RSS are scrapers; tools degrade gracefully when a source is unavailable.
- **Educational only β€” past performance does not guarantee future results.**

## License
MIT Β© Rohan Inamdar