futures-analysis-mcp
by vivizero
README.md
# 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.
[](https://python.org)
[](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
```mermaid
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)
```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)
```bash
cd futures-analysis-mcp
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
---
## Quick Start
```bash
# 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
```bash
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
```bash
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
```json
{
"symbol": "AU",
"days": 60
}
```
### Configuration for MCP Client
Add to your MCP client configuration (e.g., Claude Desktop):
```json
{
"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:
```bash
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
```bash
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
This server cannot be deployed
Maintenance
ActivitySlowing
ResponsivenessNo issues