Skip to main content
Glama
NightDevilPT

StockSage AI MCP Server

by NightDevilPT
README.md
## šŸŽÆ **StockSage AI - MCP Server Complete Documentation (Updated)**

---

## šŸ“Š **OVERVIEW**

**Purpose:** Standalone server providing tools for stock data, technical calculations, trading signals, and monitoring for short-term trading

**Data Sources:** yfinance (Primary - Free) + Multi-Provider Support (Future)

**Architecture:** Provider-Agnostic (Easy to switch/add providers)

**Total Tools:** 51

---

## šŸ“¦ **FOLDER STRUCTURE**

```
mcp-server/
│
ā”œā”€ā”€ server.py                          # Main entry point - starts MCP server
ā”œā”€ā”€ config.py                          # Configuration & provider settings
│
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ __init__.py                    # Main registry - imports all tools
│   │
│   ā”œā”€ā”€ stock_data/                    # Category: Stock Data (10 tools)
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ get_all_stocks.py          # Data Source: yfinance (Provider)
│   │   ā”œā”€ā”€ get_stock_info.py          # Data Source: yfinance (Provider)
│   │   ā”œā”€ā”€ get_real_time_price.py     # Data Source: yfinance (Provider)
│   │   ā”œā”€ā”€ get_quote.py               # Data Source: yfinance (Provider)
│   │   ā”œā”€ā”€ get_batch_quotes.py        # Data Source: yfinance (Provider)
│   │   ā”œā”€ā”€ get_historical_data.py     # Data Source: yfinance (Provider)
│   │   ā”œā”€ā”€ get_market_status.py       # Data Source: yfinance (Provider)
│   │   ā”œā”€ā”€ get_premarket_data.py      # Data Source: yfinance (Provider)
│   │   ā”œā”€ā”€ get_afterhours_data.py     # Data Source: yfinance (Provider)
│   │   └── get_multiple_timeframes.py # Data Source: yfinance (Provider)
│   │
│   ā”œā”€ā”€ technical/                     # Category: Technical Analysis (8 tools)
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ calculate_rsi.py           # Calculate from historical data
│   │   ā”œā”€ā”€ calculate_macd.py          # Calculate from historical data
│   │   ā”œā”€ā”€ calculate_ma.py            # Calculate from historical data
│   │   ā”œā”€ā”€ calculate_volatility.py    # Calculate from historical data
│   │   ā”œā”€ā”€ calculate_beta.py          # Calculate from historical data
│   │   ā”œā”€ā”€ detect_trend.py            # Calculate from historical data
│   │   ā”œā”€ā”€ detect_support_resistance.py # Calculate from historical data
│   │   └── analyze_volume.py          # Calculate from historical data
│   │
│   ā”œā”€ā”€ trading/                       # Category: Trading Signals (6 tools)
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ generate_buy_signal.py     # Uses technical tools
│   │   ā”œā”€ā”€ generate_sell_signal.py    # Uses technical tools
│   │   ā”œā”€ā”€ suggest_entry.py           # Uses support/resistance
│   │   ā”œā”€ā”€ suggest_exit.py            # Uses support/resistance
│   │   ā”œā”€ā”€ suggest_stop_loss.py       # Uses support/volatility
│   │   └── calculate_risk_reward.py   # Uses entry/stop/target
│   │
│   ā”œā”€ā”€ risk/                          # Category: Risk Management (4 tools)
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ assess_risk.py             # Uses volatility/beta/drawdown
│   │   ā”œā”€ā”€ calculate_var.py           # Calculate from historical data
│   │   ā”œā”€ā”€ calculate_drawdown.py      # Calculate from historical data
│   │   └── suggest_position.py        # Uses risk tools
│   │
│   ā”œā”€ā”€ sentiment/                     # Category: Sentiment Analysis (4 tools)
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ get_news.py                # Data Source: yfinance
│   │   ā”œā”€ā”€ analyze_sentiment.py       # Calculate from news data
│   │   ā”œā”€ā”€ get_analyst_ratings.py     # Data Source: yfinance
│   │   └── detect_rating_changes.py   # Data Source: yfinance
│   │
│   ā”œā”€ā”€ portfolio/                     # Category: Portfolio Management (6 tools)
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ get_portfolio_value.py     # Uses stock data tools
│   │   ā”œā”€ā”€ calculate_portfolio_beta.py # Calculate from historical data
│   │   ā”œā”€ā”€ detect_concentration.py    # Uses yfinance data
│   │   ā”œā”€ā”€ track_positions.py         # Uses stock data tools
│   │   ā”œā”€ā”€ calculate_pnl.py           # Uses stock data tools
│   │   └── suggest_rebalance.py       # Uses portfolio tools
│   │
│   ā”œā”€ā”€ prediction/                    # Category: Price Prediction (4 tools)
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ predict_direction.py       # Calculate from historical data
│   │   ā”œā”€ā”€ predict_target.py          # Calculate from historical data
│   │   ā”œā”€ā”€ get_confidence.py          # Calculate from analysis
│   │   └── backtest.py                # Calculate from historical data
│   │
│   └── monitoring/                    # Category: Monitoring & Alerts (9 tools)
│       ā”œā”€ā”€ __init__.py
│       ā”œā”€ā”€ start_streaming.py         # WebSocket (Future: Alpaca)
│       ā”œā”€ā”€ stop_streaming.py          # WebSocket (Future: Alpaca)
│       ā”œā”€ā”€ get_stream_data.py         # Cache
│       ā”œā”€ā”€ set_price_alert.py         # Database
│       ā”œā”€ā”€ set_volume_alert.py        # Database
│       ā”œā”€ā”€ set_pattern_alert.py       # Database
│       ā”œā”€ā”€ check_alerts.py            # Database
│       ā”œā”€ā”€ clear_alert.py             # Database
│       └── detect_anomalies.py        # Calculate from stream data
│
ā”œā”€ā”€ services/                          # Provider-Agnostic Services
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ provider_manager.py            # Routes to correct provider
│   │
│   ā”œā”€ā”€ providers/
│   │   ā”œā”€ā”€ __init__.py
│   │   ā”œā”€ā”€ base_provider.py           # Provider interface
│   │   ā”œā”€ā”€ yfinance_provider.py       # Current: yfinance (Free)
│   │   ā”œā”€ā”€ alpaca_provider.py         # Future: Alpaca (Real-time)
│   │   └── finnhub_provider.py        # Future: Finnhub (News)
│   │
│   └── cache_service.py               # Redis cache management
│
└── utils/                             # Utility functions
    ā”œā”€ā”€ __init__.py
    ā”œā”€ā”€ calculations.py                # Financial calculations
    ā”œā”€ā”€ indicators.py                  # Technical indicator formulas
    └── formatters.py                  # Data formatting helpers
```

---

## šŸ“Š **COMPLETE TOOLS TABLE & IMPLEMENTATION STATUS**

---

## CATEGORY 1: STOCK DATA TOOLS (10 Tools)

| #   | Tool Name               | Data Source         | Description                                                                                                      | Status    |
| --- | ----------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------- | --------- |
| 1   | get_all_stocks          | yfinance (Provider) | Fetches complete list of all US stocks for dropdown. Users search and select stocks to get buy/sell suggestions. | āœ… **DONE**   |
| 2   | get_stock_info          | yfinance (Provider) | Gets company name, sector, industry, description. Helps user understand what company they're trading.            | āœ… **DONE**   |
| 3   | get_real_time_price     | yfinance (Provider) | Gets current stock price. Critical for short-term trading decisions.                                             | āœ… **DONE**   |
| 4   | get_quote               | yfinance (Provider) | Gets bid/ask prices and sizes. Used to determine spread and best execution price.                                | āœ… **DONE**   |
| 5   | get_batch_quotes        | yfinance (Provider) | Gets quotes for multiple stocks in one call. Used for watchlist display showing real-time prices.                | āœ… **DONE**   |
| 6   | get_historical_data     | yfinance (Provider) | Gets OHLCV historical data for technical analysis, pattern detection, and backtesting.                           | āœ… **DONE**   |
| 7   | get_market_status       | yfinance (Provider) | Checks if market is open or closed and current session.                                                          | āœ… **DONE**   |
| 8   | get_premarket_data      | yfinance (Provider) | Gets pre-market trading data for gap detection and early signals.                                                | āœ… **DONE**   |
| 9   | get_afterhours_data     | yfinance (Provider) | Gets after-hours trading data for overnight analysis.                                                            | āœ… **DONE**   |
| 10  | get_multiple_timeframes | yfinance (Provider) | Gets data across 1Min, 5Min, 15Min, 1Hour, 1Day timeframes for comprehensive analysis.                           | āœ… **DONE**   |

---

## CATEGORY 2: TECHNICAL TOOLS (8 Tools)

| #   | Tool Name                 | Data Source                    | Description                                                                        | Status      |
| --- | ------------------------- | ------------------------------ | ---------------------------------------------------------------------------------- | ----------- |
| 11  | calculate_rsi             | Calculate from historical data | Calculates RSI (0-100) to identify overbought (>70) and oversold (<30) conditions. | āœ… **DONE** |
| 12  | calculate_macd            | Calculate from historical data | Calculates MACD line, signal line, and histogram for trend detection.              | āœ… **DONE** |
| 13  | calculate_ma              | Calculate from historical data | Calculates moving averages (50-day, 200-day) for trend and golden/death cross.     | āœ… **DONE** |
| 14  | calculate_volatility      | Calculate from historical data | Calculates price volatility to determine risk level for position sizing.           | āœ… **DONE** |
| 15  | calculate_beta            | Calculate from historical data | Calculates stock beta to measure market sensitivity.                               | āœ… **DONE** |
| 16  | detect_trend              | Calculate from historical data | Detects trend direction (up/down/sideways) and strength.                           | āœ… **DONE** |
| 17  | detect_support_resistance | Calculate from historical data | Identifies support (entry) and resistance (exit) levels.                           | āœ… **DONE** |
| 18  | analyze_volume            | Calculate from historical data | Analyzes current volume vs average, detects unusual activity.                      | āœ… **DONE** |

---

## CATEGORY 3: TRADING TOOLS (6 Tools)

| #   | Tool Name             | Data Source                         | Description                                                                                                                          | Status      |
| --- | --------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------- |
| 19  | generate_buy_signal   | Uses RSI, MACD, Trend, Volume tools | Checks all buy conditions (RSI < 30, MACD bullish, high volume, above support, uptrend) and generates buy recommendation with score. | ā³ PENDING  |
| 20  | generate_sell_signal  | Uses RSI, MACD, Trend, Volume tools | Checks all sell conditions (RSI > 70, MACD bearish, declining volume, near resistance, downtrend) and generates sell recommendation. | ā³ PENDING  |
| 21  | suggest_entry         | Uses Support/Resistance, RSI tools  | Calculates best entry price near support level for safety.                                                                           | ā³ PENDING  |
| 22  | suggest_exit          | Uses Support/Resistance tools       | Calculates exit price at resistance level with multiple targets.                                                                     | ā³ PENDING  |
| 23  | suggest_stop_loss     | Uses Support, Volatility tools      | Calculates stop-loss level below support to limit losses.                                                                            | ā³ PENDING  |
| 24  | calculate_risk_reward | Uses Entry, Stop, Target            | Calculates risk/reward ratio. Minimum 1:2 required.                                                                                  | ā³ PENDING  |

---

## CATEGORY 4: RISK TOOLS (4 Tools)

| #   | Tool Name          | Data Source                     | Description                                                                  | Status      |
| --- | ------------------ | ------------------------------- | ---------------------------------------------------------------------------- | ----------- |
| 25  | assess_risk        | Uses Volatility, Beta, Drawdown | Assesses overall risk level (Low/Medium/High) by analyzing multiple factors. | ā³ PENDING  |
| 26  | calculate_var      | Calculate from historical data  | Calculates Value at Risk - maximum potential loss at confidence level.       | ā³ PENDING  |
| 27  | calculate_drawdown | Calculate from historical data  | Calculates maximum drawdown from peak to trough.                             | ā³ PENDING  |
| 28  | suggest_position   | Uses Risk tools                 | Suggests position size ensuring maximum 2% risk per trade.                   | ā³ PENDING  |

---

## CATEGORY 5: SENTIMENT TOOLS (4 Tools)

| #   | Tool Name             | Data Source         | Description                                                   | Status      |
| --- | --------------------- | ------------------- | ------------------------------------------------------------- | ----------- |
| 29  | get_news              | yfinance            | Gets latest company news headlines for sentiment analysis.    | āœ… **DONE**     |
| 30  | analyze_sentiment     | Calculate from news | Analyzes news sentiment (positive/negative/neutral).          | ā³ PENDING  |
| 31  | get_analyst_ratings   | yfinance            | Gets analyst buy/hold/sell recommendations and price targets. | āœ… **DONE**     |
| 32  | detect_rating_changes | yfinance            | Detects recent analyst upgrades and downgrades.               | ā³ PENDING  |

---

## CATEGORY 6: PORTFOLIO TOOLS (6 Tools)

| #   | Tool Name                | Data Source                    | Description                                                 | Status      |
| --- | ------------------------ | ------------------------------ | ----------------------------------------------------------- | ----------- |
| 33  | get_portfolio_value      | Uses stock data tools          | Calculates total portfolio value with current prices.       | ā³ PENDING  |
| 34  | calculate_portfolio_beta | Calculate from historical data | Calculates portfolio beta for overall risk.                 | ā³ PENDING  |
| 35  | detect_concentration     | yfinance                       | Detects sector concentration in portfolio.                  | ā³ PENDING  |
| 36  | track_positions          | Uses stock data tools          | Tracks open positions with entry prices and current values. | ā³ PENDING  |
| 37  | calculate_pnl            | Uses stock data tools          | Calculates profit/loss for positions.                       | ā³ PENDING  |
| 38  | suggest_rebalance        | Uses Portfolio tools           | Suggests portfolio rebalancing for diversification.         | ā³ PENDING  |

---

## CATEGORY 7: PREDICTION TOOLS (4 Tools)

| #   | Tool Name         | Data Source                    | Description                                                          | Status      |
| --- | ----------------- | ------------------------------ | -------------------------------------------------------------------- | ----------- |
| 39  | predict_direction | Calculate from historical data | Predicts short-term price direction (up/down) using patterns and ML. | ā³ PENDING  |
| 40  | predict_target    | Calculate from historical data | Predicts target price for short-term trading.                        | ā³ PENDING  |
| 41  | get_confidence    | Calculate from analysis        | Returns confidence score for predictions.                            | ā³ PENDING  |
| 42  | backtest          | Calculate from historical data | Backtests predictions to measure accuracy.                           | ā³ PENDING  |

---

## CATEGORY 8: MONITORING TOOLS (9 Tools)

| #   | Tool Name         | Data Source           | Description                                 | Status      |
| --- | ----------------- | --------------------- | ------------------------------------------- | ----------- |
| 43  | start_streaming   | WebSocket (Provider)  | Starts real-time streaming for symbols.     | ā³ PENDING  |
| 44  | stop_streaming    | WebSocket (Provider)  | Stops streaming and closes connection.      | ā³ PENDING  |
| 45  | get_stream_data   | Cache                 | Gets latest cached real-time data.          | ā³ PENDING  |
| 46  | set_price_alert   | Database              | Sets alert when price crosses target level. | ā³ PENDING  |
| 47  | set_volume_alert  | Database              | Sets alert when volume exceeds threshold.   | ā³ PENDING  |
| 48  | set_pattern_alert | Database              | Sets alert for chart patterns.              | ā³ PENDING  |
| 49  | check_alerts      | Database              | Checks triggered alerts for notification.   | ā³ PENDING  |
| 50  | clear_alert       | Database              | Clears triggered alert from active list.    | ā³ PENDING  |
| 51  | detect_anomalies  | Calculate from stream | Detects price spikes and unusual volume.    | ā³ PENDING  |

---

## šŸ“Š **SUMMARY TABLE**

| Category   | Folder        | Total Tools  | Completed   | Pending     | Primary Data Source | Implementation Status |
| ---------- | ------------- | ------------ | ----------- | ----------- | ------------------- | --------------------- |
| Stock Data | stock_data/   | 10           | 10          | 0           | yfinance (Provider) | āœ… **100% COMPLETE**  |
| Technical  | technical/    | 8            | 8           | 0           | Calculate from data | āœ… **100% COMPLETE**  |
| Trading    | trading/      | 6            | 0           | 6           | Multiple tools      | ā³ PENDING            |
| Risk       | risk/         | 4            | 0           | 4           | Calculate from data | ā³ PENDING            |
| Sentiment  | sentiment/    | 4            | 2           | 2           | yfinance            | šŸ”„ **50% IN PROGRESS** |
| Portfolio  | portfolio/    | 6            | 0           | 6           | Multiple tools      | ā³ PENDING            |
| Prediction | prediction/   | 4            | 0           | 4           | Calculate from data | ā³ PENDING            |
| Monitoring | monitoring/   | 9            | 0           | 9           | Cache + Database    | ā³ PENDING            |
| **Total**  | **8 folders** | **51 tools** | **20 DONE** | **31 PEND** |                     | **20/51 DONE**        |


---

## šŸ“Š **PROVIDER ARCHITECTURE**

### **Current Provider: yfinance (Free, No API Key)**

```
PROVIDER_CONFIG = {
    "default": "yfinance",
    "features": {
        "stock_data": "yfinance",
        "historical_data": "yfinance",
        "fundamentals": "yfinance",
        "news": "yfinance",
        "streaming": None  # Future: Alpaca
    }
}
```

### **Future Providers (Easy to Add):**

| Provider     | Use Case              | API Key | Real-time         |
| ------------ | --------------------- | ------- | ----------------- |
| **yfinance** | Current - All data    | āŒ No   | āš ļø Near real-time |
| **Alpaca**   | Real-time + Streaming | āœ… Yes  | āœ… 0-delay        |
| **Finnhub**  | News + Sentiment      | āœ… Yes  | āœ… 0-delay        |
| **Polygon**  | Real-time + Options   | āœ… Yes  | āœ… 0-delay        |

---

## āœ… **REQUIREMENT COVERAGE CONFIRMATION**

| StockSage AI Requirement         | Tools Used         | Covered? |
| -------------------------------- | ------------------ | -------- |
| Multi-Perspective Stock Analysis | Tools 1-32         | āœ… YES   |
| Technical Analysis               | Tools 11-18        | āœ… YES   |
| Fundamental Analysis             | Tools 2, 29-32     | āœ… YES   |
| Sentiment Analysis               | Tools 29-32        | āœ… YES   |
| Risk Assessment                  | Tools 14-15, 25-28 | āœ… YES   |
| Portfolio Risk Management        | Tools 33-38        | āœ… YES   |
| Market Trend Prediction          | Tools 39-42        | āœ… YES   |
| 24/7 Watchlist Monitoring        | Tools 43-51        | āœ… YES   |
| Buy/Sell Signals                 | Tools 19-24        | āœ… YES   |
| Entry/Exit/Stop Loss             | Tools 21-24        | āœ… YES   |
| Real-time Data                   | Tools 3-5, 43-45   | āœ… YES   |
| Alerts & Notifications           | Tools 46-51        | āœ… YES   |

---

## šŸŽÆ **FINAL CONCLUSION**

**All 51 tools fully support StockSage AI with provider-agnostic architecture!**

- āœ… **Current:** yfinance (Free, No API Key)
- āœ… **Future:** Easy to add Alpaca, Finnhub, Polygon
- āœ… **Provider Manager:** Routes to correct provider
- āœ… **Config-Based:** Switch providers without code changes
- āœ… **All Requirements Covered:** 100%

**This is the complete updated MCP server documentation with provider-agnostic architecture!**