Skip to main content
Glama
vivizero

futures-analysis-mcp

by vivizero

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


Related MCP server: A股实时行情MCP服务器

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

F
license - not found
-
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • F
    license
    -
    quality
    C
    maintenance
    MCP server that wraps SFC financial data API into 32 tools for comprehensive A-share market data, including real-time quotes, rankings, limit-up statistics, news, themes, financials, charts, research reports, and watchlists.
  • A
    license
    -
    quality
    D
    maintenance
    MCP server providing professional financial data access for LLMs through providers like Tushare, Wind, and DataYes.
    1
    Apache 2.0
  • A
    license
    B
    quality
    B
    maintenance
    MCP server exposing 43 financial data tools for A-share, HK, US stocks, crypto, and market news via open-stock-data.
    43
    14
    MIT

View all related MCP servers

Related MCP Connectors

  • MCP server exposing the Backtest360 engine API as tools for AI agents.

  • Open-source MCP server for Zerodha Kite Connect. Portfolio, market data, backtesting, alerts.

  • 7-factor stock scoring MCP server. US/HK/CN, 74 stocks. Free + Premium (USDC/Base). x402 ready.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/vivizero/futures-analysis-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server