MaverickMCP

repository·main·Indexed 20 days ago

https://github.com/wshobson/maverick-mcp

A personal-use FastMCP server (v1.0.0) for AI interfaces like Claude Desktop, providing professional-grade stock analysis, technical indicators, stock screening, and portfolio tracking tools. It features 37 core tools for market data and technical analysis, with optional extras for backtesting and research.

Tokens
46.3K
Snippets
105
Records
232
Agent score
70%

What's inside maverick-mcp

  1. Overview of MaverickMCP Capabilities

    main

    MaverickMCP is a personal-use Model Context Protocol (MCP) server designed for Claude Desktop. It provides tools for professional-grade financial analysis, including:

    • Market Data: Access to real-time and historical market data with built-in caching.
    • Technical Analysis: Support for advanced indicators such as RSI, MACD, and Bollinger Bands.
    • Stock Screening: Multiple strategies including Maverick Bullish/Bearish, breakouts, and supply/demand analysis.
    • Portfolio Management: Tracking of cost basis, position averaging, and live P&L.
    • Deep Research: Optional integrations with OpenRouter and web search providers for extended analysis.
  2. Overview of the MaverickMCP tech stack

    main

    MaverickMCP is built on a modern Python stack designed for high-performance financial data analysis and MCP (Model Context Protocol) integration.

    Core Components:

    • Language: Python 3.12
    • MCP & API: Built using fastmcp and mcp primitives, with fastapi and uvicorn handling the server transport.
    • Data & Analysis: Leverages pandas, numpy, pandas-ta, TA-Lib, and vectorbt for technical analysis and backtesting.
    • Market Data Providers: Primarily uses tiingo with yfinance as a fallback/supplemental source.
    • Persistence: Uses sqlalchemy with aiosqlite (default) or asyncpg (PostgreSQL).
  3. Understand MaverickMCP reliability and error handling

    main

    MaverickMCP (v1.0.0) implements several resilience patterns to ensure stability during market data fetching and search operations:

    • Circuit Breakers: Outbound HTTP calls (used by market data fetchers and the Exa search provider) are protected by per-service circuit breakers via maverick.platform.http.get_breaker.
    • Rate Limiting: Outbound HTTP requests are managed by a shared rate limiter controlled by the DATA_PROVIDER_RATE_LIMIT environment variable (defaults to 5/s) via maverick.platform.http.request_resilient.
    • Graceful Degradation of Extras: If [backtesting] or [research] domains are absent, tools.register() will log a warning and register zero tools for those domains rather than crashing, allowing the base server to boot.
    • Tiered Caching: The system uses a tiered caching strategy (Memory $\rightarrow$ Redis $\rightarrow$ SQLite). If Redis is unavailable or disabled, the system automatically degrades to in-memory or SQLite caching.
    • Clean Startup Errors: The primary entry point maverick.server.app.main catches server-building exceptions to report a clean one-line error and a non-zero exit code instead of a raw traceback.
  4. Overview of MaverickMCP Server Architecture

    main

    MaverickMCP is a personal stock analysis MCP server built using FastMCP and maverick.platform. The server architecture follows a dependency injection pattern where a shared Engine and Cache are used to initialize the MarketDataService. This service is then injected into screening, portfolio, and technical services. Backtesting and research services are constructed only when their specific extras are required. Each domain follows a two-step registration pattern: configure(service) followed by register(mcp).

    Tech Stack Requirements:

    • Python: 3.12+ (Note: Python < 3.13 is required due to ta-lib compatibility).
    • Frameworks: FastMCP, maverick.platform.
  5. Manage Portfolio features and analysis

    main
    MaverickMCP includes features for portfolio management, including persistence, cost basis tracking, P&L calculation, and position-aware analysis. See the portfolio feature guide for details on how these capabilities work.
  6. How SignalService evaluation and event publishing works

    main

    The evaluate_all method in SignalService implements a stateful evaluation loop for technical signals:

    1. Data Fetching: It groups signals by ticker to minimize API calls, using a provided data_fetcher (which must be a callable returning a pd.DataFrame) to fetch up to 60 days of data.
    2. Condition Evaluation: It uses evaluate_condition to check the signal's condition against the fetched data.
    3. Triggering: If a condition is met, it calls record_trigger to save the event and publishes a signal.triggered event to the EventBus containing the signal_id, label, ticker, price, and condition.
    4. Clearing: If a signal was previously triggered but the condition is no longer met, it publishes a signal.cleared event.
    5. State Management: The service maintains previous_state on the Signal model to track stateful transitions (e.g., ensuring a 'cleared' event only fires once when moving from triggered to non-triggered).
    # Example of the expected data_fetcher signature for evaluate_all
    async def my_data_fetcher(ticker: str, days: int): 
        # returns a pandas DataFrame
        pass
    
    await signal_service.evaluate_all(my_data_fetcher)
  7. Understand the MaverickMCP Portfolio Domain Architecture

    main

    The maverick/portfolio/ domain is structured as a layered architecture to ensure strict mathematical precision for financial data. The layers follow this dependency flow:

    tools $\rightarrow$ service $\rightarrow$ {data, ledger} $\rightarrow$ config $\rightarrow$ types

    Key Architectural Principles

    • Decimal Discipline: All money and share calculations use Decimal end-to-end. Floats are only permitted at the tools' JSON boundary, where they are converted to strings to prevent precision loss.
    • Ledger vs. Data:
      • The ledger layer contains pure functions for position math (e.g., average-cost formulas).
      • The data layer handles persistence (SQLAlchemy) and contains no mathematical logic.
    • Service Layer: Composes the ledger and data layers within single session_scope transactions and integrates with market_data and technical domains.
    • Tool Layer: Exposes the domain via MCP tools, providing a uniform interface for interacting with portfolios.
  8. Supported Indicators and Operators

    main

    The Signal Condition Engine supports several indicators and operators for stock analysis.

    Indicators

    • price: Uses the most recent value from the close column.
    • rsi: Computes the Relative Strength Index. Requires a period key in the condition (default 14).
    • volume: Uses the most recent value from the volume column.
    • sma: Computes the Simple Moving Average. Requires a period key in the condition (default 20).

    Operators

    • lt, gt, lte, gte: Standard comparison operators (<, >, <=, >=) against a value.
    • spike: Triggers if the current value is greater than the mean plus std_devs standard deviations. Works on volume or close.
    • crosses_above: Triggers when the indicator moves from below a reference to above it. Requires previous_state to track the transition.
    • crosses_below: Triggers when the indicator moves from above a reference to below it. Requires previous_state to track the transition.

    Reference Indicators

    For crossover operators, the reference key can specify an SMA with a period using the format sma_N (e.g., "sma_50").

  9. Understand the MaverickMCP Screening Domain Architecture

    main

    The screening domain in MaverickMCP is designed to handle both querying and computation of stock screens. Unlike the legacy implementation which relied on external CLI scripts and pre-populated tables, the modern implementation uses a pure-Python technical indicator core (maverick/technical/) to compute real-time screens with zero native dependencies (no talib, numba, or pandas-ta required at runtime).

    Key Architectural Principles:

    • Compute & Query Integration: The screening service methods (e.g., run_*_screen()) perform the actual computation using pure-Python indicators based on thresholds defined in ScreeningSettings.
    • Data Isolation: The new domain uses dedicated tables prefixed with scr_*. It does not migrate legacy mcp_maverick_* rows; instead, it computes fresh snapshots.
    • Dependency Management: The system avoids heavy native dependencies. Indicators are implemented using pandas and numpy functions. pandas-ta is strictly used for fixture-recording during development and is never imported by the core maverick/ package or its tests.
    • Layered Design: Following the market-data domain template, the screening domain uses layer contracts, injectable dependencies, and deterministic generators for testing to ensure no network calls occur during tests.
  10. How the Service Registry works

    main

    The Service Registry is a lightweight dictionary mapping service names to their initialized instances. It is created at server startup, where services register themselves. Consumers can then look up these services by name to interact with them.

    registry = ServiceRegistry()
    registry.register("signals", SignalService(event_bus, scheduler))
    registry.register("screening", ScreeningPipelineService(event_bus, scheduler))
    # ...
    signal_svc = registry.get("signals")
  11. Understand the screening result data structures

    main

    The maverick.screening.types module defines the Pydantic models used for all screening outputs. This ensures a consistent schema across different screening rubrics (bullish, bearish, and supply/demand).

    Key Types:

    • ScreeningResult: Represents a single qualified symbol.
      • symbol: The stock ticker.
      • screen: One of "bullish", "bearish", or "supply_demand".
      • date_analyzed: The date of the analysis.
      • close: The closing price.
      • combined_score: The integer score calculated by the rubric.
      • momentum_score: Optional float score.
      • indicators: A dictionary of technical indicator values.
      • flags: A dictionary of boolean technical flags.
      • reason: A string explanation of the signal.
    • AllScreeningResults: A container for all results from a single run, grouped by screen type.
    • ScreenRun: Metadata about a screening execution (e.g., symbols_screened, symbols_qualified, duration_seconds).
    • ScreeningCriteria: Used to filter results by min_momentum_score, min_volume, max_price, or min_combined_score.
  12. How data seeding and market data works

    main

    As of v1.0.0, MaverickMCP does not include a pre-seeded universe (like a fixed S&P 500 list). Instead, data is populated on demand:

    1. Market Data: Tools like market_data_get_price_history or market_data_get_quote fetch data from yfinance. Calling these tools for a specific ticker automatically registers that symbol in the local md_stocks table.
    2. Screening: The screening_run_screens tool operates only on symbols already present in the local md_stocks table.

    Tip: To get meaningful results from a screen, you must first fetch price history for the tickers you are interested in to ensure they exist in the local database.