futures-analysis-mcp

futures-analysis-mcp

MCP server for domestic futures analytics, providing tools to fetch OHLCV data, check data quality, analyze market metrics, and generate markdown reports via the Model Context Protocol.

Category
Visit Server

README

Futures Analysis MCP Demo

Domestic Futures Analytics + MCP Tooling

A lightweight domestic futures analytics workflow built with Python, AKShare, and MCP (Model Context Protocol). Designed as a 2-3 hour project demo for a financial data analyst internship interview.

Python Tests

Key design points:

  • Core analytics does not depend on an LLM.
  • MCP exposes analytics capabilities as standardized tools.
  • A future MCP-compatible Agent Client can reuse these tools.

Why This Project

This project demonstrates a complete financial data analysis workflow, from data ingestion to visualization:

  1. Financial Data Ingestion — Historical main-continuous futures data via AKShare
  2. Data Quality — Structured quality checks for OHLC data integrity
  3. Analytics — Returns, volatility, drawdown, moving averages, volume activity
  4. MCP Tooling — Standardized tool exposure via Model Context Protocol
  5. Visualization — Streamlit dashboard + A4 printable report
  6. Resilience — Local CSV fallback when network is unavailable

Architecture

flowchart LR
    A[Market Data<br/>AKShare / CSV] --> B[Data Service]
    B --> C[Data Quality]
    C --> D[Indicator Engine]
    D --> E[Analyzer]
    
    E --> F[MCP Server]
    E --> G[CLI Demo]
    E --> H[Streamlit UI]
    E --> I[Printable Report]

Dependency direction:

         Python Core (src/)
         ↑           ↑
         │           │
    MCP Server    Streamlit

Both MCP Server and Streamlit depend on Python Core — never the reverse. This keeps the architecture clean and the client layer replaceable.


Features

  • AKShare Integration — Historical daily domestic futures data from Sina Finance
  • CSV Fallback — Automatic local data fallback on network failure
  • Data Quality Checks — Missing values, duplicates, OHLC constraint violations
  • Financial Metrics — Cumulative return, annualized volatility, maximum drawdown
  • Moving Averages — MA5 and MA20 (true SMA: requires full window before first value)
  • Volume Activity — Short-term vs. medium-term volume ratio
  • MCP Tools — 4 standardized tools via Model Context Protocol
  • Streamlit Dashboard — Interactive web UI for analysis
  • A4 Printable Report — PNG + PDF landscape financial data dashboard
  • Markdown Report — Structured analysis report with quality and metrics

Supported Instruments

Symbol Name Exchange Sina Code
AU Gold Futures SHFE AU0
RB Rebar Futures SHFE RB0
SC Crude Oil Futures INE SC0

Project Structure

futures-analysis-mcp/
│
├── README.md                  # Project documentation
├── requirements.txt           # Python dependencies
├── .gitignore
├── demo.py                    # CLI demo entry point
├── app.py                     # Streamlit dashboard
├── generate_print_report.py   # A4 printable report generator
├── pytest.ini                 # Pytest configuration
│
├── data/                      # Local CSV fallback data
│   ├── README.md
│   ├── sample_AU.csv
│   ├── sample_RB.csv
│   └── sample_SC.csv
│
├── src/                       # Core analytics library
│   ├── __init__.py
│   ├── data_service.py        # AKShare fetch + CSV fallback
│   ├── data_quality.py        # OHLC data quality checks
│   ├── indicators.py          # Financial indicators
│   ├── analyzer.py            # Integrated market analysis
│   ├── report.py              # Markdown report generation
│   └── visualization.py       # Matplotlib A4 report charts
│
├── mcp_server/                # MCP server module
│   ├── __init__.py
│   └── server.py              # MCP tool definitions & handlers
│
├── outputs/                   # Generated outputs
│   ├── charts/
│   ├── reports/               # Markdown reports
│   └── print/                 # A4 PNG + PDF reports
│
└── tests/                     # Pytest test suite (30 tests)
    ├── test_data_quality.py
    ├── test_indicators.py
    ├── test_fallback.py
    └── test_mcp_server.py     # MCP client-server integration tests

Installation

Prerequisites

  • Python 3.10 or higher
  • Windows / macOS / Linux

Setup (Windows PowerShell)

# Clone or navigate to project directory
cd E:\job\projects\jinrong\futures-analysis-mcp

# Create virtual environment (recommended)
python -m venv .venv
.\.venv\Scripts\Activate.ps1

# Install dependencies
pip install -r requirements.txt

Setup (macOS / Linux)

cd futures-analysis-mcp
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Quick Start

# Default: AU, 60 trading days
python demo.py

# Custom instrument and window
python demo.py --symbol AU --days 60
python demo.py --symbol RB --days 120
python demo.py --symbol SC --days 20

Sample output:

==================================================
  Domestic Futures Market Analysis
==================================================

Instrument: Gold Futures (AU)
Window: 60 trading days

[1/4] Loading market data...
  OK 60 records loaded
  Source: AKShare

[2/4] Checking data quality...
  OK PASS

[3/4] Calculating metrics...

  Latest Close                 936.76
  Cumulative Return             -6.73%
  Annualized Volatility         22.82%
  Maximum Drawdown            -13.40%
  MA5                          909.44
  MA20                         892.00
  Volume Ratio                   1.40

[4/4] Report generated
  outputs/reports/AU_60d_report.md

==================================================
  Descriptive analytics only. No investment advice.
==================================================

Streamlit Dashboard

streamlit run app.py

Opens an interactive dashboard with:

  • Key metric cards (Close, Return, Volatility, Drawdown)
  • Price & MA line chart
  • Daily return bar chart
  • Drawdown area chart
  • Data quality overview
  • Market observation text

MCP Server

The MCP server exposes 4 tools following the Model Context Protocol. It uses the official MCP Python SDK v2.0.0.

Start the server

python -m mcp_server.server

MCP Tools

Tool Parameters Description
get_futures_data symbol, days Fetch standardized OHLCV data as JSON
check_data_quality symbol, days Run data quality checks, return structured report
analyze_market symbol, days Full market analysis with metrics and descriptions
generate_market_report symbol, days Execute full pipeline and generate Markdown report

All tools validate symbol (AU/RB/SC) and days (20/60/120) parameters and return clear error messages on invalid input.

Tool input examples

{
  "symbol": "AU",
  "days": 60
}

Configuration for MCP Client

Add to your MCP client configuration (e.g., Claude Desktop):

{
  "mcpServers": {
    "futures-analysis": {
      "command": "python",
      "args": ["-m", "mcp_server.server"],
      "cwd": "E:/job/projects/jinrong/futures-analysis-mcp"
    }
  }
}

Printable Report

Generate an A4 landscape financial data dashboard ready for print:

python generate_print_report.py --symbol AU --days 60

Outputs:

  • outputs/print/AU_60d_analysis.png (200 DPI)
  • outputs/print/AU_60d_analysis.pdf (vector)

The printable page contains only financial data visualizations:

  1. Close Price + MA5 + MA20 line chart
  2. Daily Return bar chart
  3. Drawdown area chart
  4. Volume bar chart
  5. Key metric cards and data quality summary

Running Tests

pytest -v

Test coverage (30 tests):

  • test_data_quality.py — Normal OHLC, high < low, negative prices, missing values, duplicates, empty data
  • test_indicators.py — Daily return, cumulative return, max drawdown, moving average, volume activity, volatility, MA NaN behavior
  • test_fallback.py — AKShare failure fallback, CSV column integrity, AKShare success path, input validation
  • test_mcp_server.py — MCP client-server integration: tool discovery, all 4 tool calls, error handling, sequential calls

Financial Metrics

Metric Formula Notes
Daily Return r_t = P_t / P_{t-1} - 1 Percentage change
Cumulative Return R = P_T / P_0 - 1 Total return over window
Annualized Volatility σ_daily × √252 252 trading days convention
Maximum Drawdown min(close / cummax(close) - 1) Peak-to-trough decline
Moving Average SMA(n) = mean(close[-n:]) True SMA: first n-1 values are NaN
Volume Activity avg_vol(5d) / avg_vol(20d) Short vs medium term volume

Note: 252 trading days is used as a conventional annualization assumption for this demonstration. Actual futures market trading days may vary slightly by market and year.


Data Fallback

Try AKShare  →  Success?  →  Return data (source: "AKShare")
     │
     ↓ Fail
Load Local CSV  →  Success?  →  Return data (source: "Local CSV Fallback")
     │
     ↓ Fail
Raise RuntimeError with details from both attempts

The system will never silently fail. It always reports which data source was used.

Sample CSV files contain real market data downloaded from AKShare, not synthetic/random data.


Design Decisions

Why No LLM Dependency

This project is designed as a MCP-ready financial analytics workflow, not an AI agent. It exposes standardized tools that any MCP-compatible client (including LLM-based clients) can consume. The core analytics are deterministic, testable, and auditable.

Why MCP Is Separated from Core Analytics

Following separation of concerns:

  • src/ contains pure Python business logic
  • mcp_server/ wraps that logic into MCP tools
  • app.py (Streamlit) is a separate UI layer

This means any layer can be replaced independently.

Why No Trading Signals

This project is descriptive analytics, not predictive modeling. All observations are statistical descriptions of historical data. It does not and should not be interpreted as investment advice.


Limitations

  • This project uses historical/continuous futures data for analytics demonstration.
  • Continuous/main contract series may contain contract-roll effects (price gaps at roll dates).
  • The system does not model transaction costs, slippage, execution latency, margin requirements, or contract-specific trading rules.
  • No backtesting framework is included.
  • No price prediction is performed.
  • No investment advice is provided.
  • Only 3 instruments (AU, RB, SC) are supported for simplicity.
  • Lookback windows are limited to 20, 60, and 120 trading days.

Future Work

  • LLM-based MCP Client integration
  • Cross-asset comparison analysis
  • Contract roll adjustment
  • Backtesting framework
  • Additional instruments
  • Correlation analysis between instruments

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured
E2B

E2B

Using MCP to run code via e2b.

Official
Featured