Skip to main content
Glama
Omgarg1

Stock_Advisor_MCP

by Omgarg1
README.md
# Stock Advisor

A [FastMCP](https://github.com/jlowin/fastmcp) server that provides stock research, technical analysis, fundamental analysis, and scoring — all exposed as MCP tools, resources, and prompts for AI agents.

---

## Features

- **Real-time quotes** – Fetch near-real-time stock prices via Finnhub with an automatic yfinance fallback.
- **Price history** – Retrieve OHLCV history for any ticker with configurable periods and intervals.
- **Price & market-cap classification** – Classify a stock by share-price band and market-cap band.
- **Technical indicators** – Compute RSI, MACD, moving averages (SMA 50/200), golden/death cross detection, Bollinger Bands, volume ratio, and volatility.
- **Fundamental analysis** – Collect trailing & forward P/E, EPS, dividend yield, debt-to-equity, ROE, revenue growth, profit margin, beta, and sector context.
- **Scoring engine** – Combine technical and fundamental inputs into a transparent 0–100 score with a **Strong Buy / Buy / Hold / Avoid** label. Customisable technical vs. fundamental weighting.
- **Multi-stock comparison** – Compare several tickers side-by-side on price, valuation, RSI, and overall score.
- **Watchlist resource** – Exposes a simple, persisted watchlist for the current session.
- **Agent prompts** – Built-in prompts (`analyze_stock`, `compare_portfolio`) that guide AI agents through the analysis workflow.

---

## Architecture

```
stock-advisor/
├── server.py                 # Entry point (PATH setup + main call)
├── pyproject.toml            # Project metadata & dependencies
├── requirements.txt           # Pinned dependencies
├── Dockerfile                 # Docker image
├── .env.example               # Environment template
├── README.md
├── src/
│   └── stock_advisor/
│       ├── __init__.py
│       ├── server.py          # FastMCP server: tools, resources, prompts, transport config
│       ├── data_source.py     # Finnhub (primary) + yfinance (fallback) data fetching
│       ├── indicators.py      # Technical indicator computations (RSI, MACD, SMA, Bollinger, volatility)
│       ├── models.py          # Pydantic models for all tool inputs & outputs
│       ├── scoring.py         # Scoring engine: combines technical & fundamental signals
│       └── utils.py           # Ticker normalisation, period/interval validation
└── tests/
    └── test_core.py           # Pytest suite (150+ lines of test coverage)
```

---

## Quick Start

### Prerequisites

- Python 3.11+
- A [Finnhub API key](https://finnhub.io/register) (free tier available)

### Installation

```bash
# Clone the repository
git clone <repo-url>
cd stock-advisor

# Create and activate a virtual environment
python -m venv .venv
source .venv/bin/activate   # macOS/Linux
# .venv\Scripts\activate    # Windows

# Install dependencies
pip install -r requirements.txt

# Configure your Finnhub API key
cp .env.example .env
# Edit .env and add your Finnhub API key:
#   FINNHUB_API_KEY=your_key_here
```

### Running

Start the server over HTTP (default):

```bash
python server.py
```

The server listens on `http://127.0.0.1:8765/mcp` by default.

**Using stdio transport:**

```bash
MCP_TRANSPORT=stdio python server.py
```

**Custom host / port:**

```bash
HOST=0.0.0.0 PORT=8080 python server.py
```

---

## MCP Tools

All tools are registered with the FastMCP server and are automatically available to any MCP-compatible AI agent (Claude, Cline, etc.).

| Tool | Description |
|---|---|
| `get_quote_tool(ticker)` | Fetch a near-real-time quote (Finnhub → yfinance fallback). Returns price, change %, day high/low, open, previous close. |
| `get_price_history_tool(ticker, period, interval)` | OHLCV history with configurable period (`1d`, `5d`, `1mo`, `6mo`, `1y`, `5y`, `max`) and interval (`1m`, `5m`, `1h`, `1d`, `1wk`). |
| `classify_by_price_range_tool(ticker)` | Classify by share-price band (penny / small-cap / mid-range / high-price) and market-cap band (micro / small / mid / large). |
| `get_technical_indicators_tool(ticker, period)` | RSI, MACD (line + signal + histogram), SMA 50/200, golden/death cross, Bollinger Bands, volume ratio, annualised volatility. |
| `get_fundamentals_tool(ticker)` | Trailing & forward P/E, EPS, dividend yield, D/E, ROE, revenue growth YoY, profit margin, beta, sector. |
| `score_stock_tool(ticker, technical, fundamentals, tech_weight, fundamental_weight)` | 0–100 composite score with transparent breakdown and label. Default weights: 40 % technical, 60 % fundamental. |
| `compare_stocks_tool(tickers)` | Side-by-side comparison of price, P/E, RSI, and score for up to several tickers. |

---

## MCP Resources

| Resource URI | Description |
|---|---|
| `watchlist://` | Exposes a simple comma-separated watchlist (e.g. `AAPL,MSFT,NVDA,TSLA`) for the current session. |

---

## MCP Prompts

| Prompt | Description |
|---|---|
| `analyze_stock` | Guides an AI agent to call tools in the correct order: quote → technicals → fundamentals → scoring, then summarise. |
| `compare_portfolio` | Guides an AI agent to call `compare_stocks_tool` and summarise trade-offs across price, valuation, momentum, and score. |

---

## Scoring Engine

The scoring engine produces a transparent, explainable 0–100 score:

| Score Range | Label |
|---|---|
| 80–100 | **Strong Buy** |
| 65–79 | **Buy** |
| 45–64 | **Hold** |
| 0–44 | **Avoid** |

**Technical factors scored (40 % default weight):**

- RSI oversold / neutral / overbought
- Price relative to SMA trend (above → bullish, below → bearish)
- Volume confirmation (ratio > 1.0)

**Fundamental factors scored (60 % default weight):**

- P/E ratio (sector-relative when sector is known, absolute otherwise)
- Debt-to-equity ratio (< 1.0 → healthy)
- Revenue growth (positive → good)
- Profit margin (positive → good)

Weights are fully customisable via the `tech_weight` and `fundamental_weight` parameters in `score_stock_tool`.

---

## Data Sources

| Data | Primary Source | Fallback |
|---|---|---|
| Real-time quote | [Finnhub API](https://finnhub.io/) | yfinance |
| Price history | yfinance | — |
| Fundamentals | yfinance | — |
| Technical indicators | Computed in-house from yfinance history | — |

---

## Configuration

All configuration is via environment variables:

| Variable | Default | Description |
|---|---|---|
| `FINNHUB_API_KEY` | — | Your Finnhub API key (required for quote tool) |
| `MCP_TRANSPORT` | `http` | Transport protocol (`http` or `stdio`) |
| `HOST` | `127.0.0.1` | Bind address |
| `PORT` | `8765` | Listen port |
| `MCP_PATH` | `/mcp` | HTTP path for the MCP endpoint |
| `SSL_CERTFILE` | — | Path to SSL certificate (enables HTTPS) |
| `SSL_KEYFILE` | — | Path to SSL private key (enables HTTPS) |

---

## Docker

```bash
# Build
docker build -t stock-advisor .

# Run
docker run -e FINNHUB_API_KEY=your_key_here -p 8765:8765 stock-advisor
```

---

## Development

### Running tests

```bash
pytest
```

### Code structure

- `src/stock_advisor/server.py` — FastMCP server definition; all tools, resources, and prompts are registered here.
- `src/stock_advisor/data_source.py` — Data fetching layer (Finnhub API + yfinance).
- `src/stock_advisor/indicators.py` — Pure-function technical indicator computations.
- `src/stock_advisor/models.py` — Pydantic models for input validation and structured output.
- `src/stock_advisor/scoring.py` — Composite scoring logic with weighted technical/fundamental signals.
- `src/stock_advisor/utils.py` — Ticker normalisation and period/interval validation.

---

## Disclaimer

All tools and outputs from Stock Advisor are for **educational and informational purposes only**. Nothing provided by this server constitutes financial advice. Always do your own research before making investment decisions.