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
访问服务器

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

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选