Skip to main content
Glama
zomma-dev

QuantContext

by zomma-dev

QuantContext

QuantContext is an MCP server that turns plain-English strategy descriptions into executable quant research: screen stocks by any criteria, backtest over historical data, and run factor analysis to see where the returns come from. Every number is computed from real market data, not generated by an LLM. Results are fully reproducible.

Works with Claude, Codex, OpenCode, or any other MCP-compatible coding agent.

Install

pip install quantcontext-mcp

Claude Code:

claude mcp add quantcontext -- quantcontext

Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "quantcontext": {
      "command": "quantcontext"
    }
  }
}

No API keys. No configuration.

Related MCP server: panther-mcp

Tools

Three tools that compose into a full research workflow:

screen_stocks -> backtest_strategy -> factor_analysis

Tool

What it does

screen_stocks

Filter S&P 500, Nasdaq 100, or Russell 2000 by fundamentals, momentum, quality, technical signals, or a multi-factor blend. Returns ranked candidates.

backtest_strategy

Test a strategy over history with a rebalance-loop engine. Returns CAGR, Sharpe, max drawdown, equity curve, and trade log.

factor_analysis

Decompose strategy returns into Fama-French factors (market, size, value, momentum). Returns alpha with t-statistic, factor loadings, and R-squared.

Sample Prompts

Stock screening:

Screen S&P 500 for value stocks: PE under 15, ROE above 12%
Find the top 20% momentum stocks in the Nasdaq 100 over the last 200 days
Rank S&P 500 stocks by a blend of value, momentum, and quality, equal weight each factor
Find S&P 500 stocks with RSI under 40 and price above the 200-day moving average

Backtesting:

Backtest a top-20% momentum strategy on Nasdaq 100, monthly rebalance, last 2 years
How would a value screen (PE under 15, ROE above 12%) have performed on S&P 500 over the last 3 years?
Test a momentum strategy with a 15% stop loss and 20% max portfolio drawdown circuit breaker

Full research workflow:

Screen S&P 500 for cheap, high-quality stocks. Backtest monthly over 3 years,
then run factor analysis. Is the return real alpha or just factor exposure?

Screen Types

Screen

Description

Key parameters

fundamental_screen

Filter by PE, ROE, leverage, revenue growth

pe_lt, roe_gt, debt_equity_lt, revenue_growth_gt

quality_screen

Profitability and balance sheet health

roe_gt, debt_equity_lt, profit_margin_gt

momentum_screen

Rank by N-day price momentum

lookback_days, top_pct

value_screen

Cheapest stocks by valuation

pe_lt, top_n

factor_model

Multi-factor composite score

weights (value/momentum/quality/volatility), top_n

technical_signal

RSI and SMA crossover signals

rsi_period, sma_short, sma_long

mean_reversion

Stocks below z-score threshold

lookback_days, z_threshold

Use from Python

The tools are also importable directly — no agent required. Useful if you have an existing script and want to plug in backtesting or factor analysis.

from quantcontext.server import screen_stocks, backtest_strategy, factor_analysis
import asyncio, json

# Screen
result = json.loads(asyncio.run(screen_stocks(
    universe="sp500",
    screen_type="fundamental_screen",
    config={"pe_lt": 15, "roe_gt": 12},
)))

# Backtest
bt = json.loads(asyncio.run(backtest_strategy(
    stages=[{"order": 1, "type": "screen", "skill": "fundamental_screen", "config": {"pe_lt": 15, "roe_gt": 12}}],
    universe="sp500",
    rebalance="monthly",
    start_date="2022-01-01",
)))
print(bt["metrics"])

# Factor analysis — pipe the equity curve straight in
fa = json.loads(asyncio.run(factor_analysis(
    equity_curve=bt["full_equity_curve"]
)))
print(fa["alpha_annualized"], fa["alpha_tstat"])

Strategies are expressed using the built-in screen types from the table above. All functions are async and return JSON strings.

Data

All public data, no API keys required.

Data

Source

Cache

Daily OHLCV prices

Yahoo Finance (yfinance)

~/.cache/quantcontext/prices.parquet

Fundamentals (PE, ROE, margins, etc.)

Yahoo Finance

~/.cache/quantcontext/financials/, 24h TTL

Fama-French factors (Mkt-RF, SMB, HML, Mom)

Kenneth French Data Library

~/.cache/quantcontext/ff_factors.parquet

Universe lists (S&P 500, Nasdaq 100)

Wikipedia

~/.cache/quantcontext/sp500_tickers.json

The first tool call downloads and caches data (10-30 seconds). All subsequent calls use the local cache: screening under 1s, backtesting 3-8s.

To skip the cold start, run once after install:

quantcontext-warmup --url https://quantcontext.ai/api/data
  • Docs — full reference, examples, methodology

  • PyPI

License

MIT

Available Tools

3 tools
backtest_strategyA
Read-onlyIdempotent

Run a historical backtest on a stock screening strategy. Uses a rebalance-loop engine that re-runs the screening pipeline on each rebalance date, sizes positions, enforces risk limits, and tracks daily P&L.

Returns equity curve, trade log, and performance metrics including CAGR, Sharpe ratio, maximum drawdown, Calmar ratio, win rate, and turnover.

The backtest is fully deterministic — same inputs always produce identical results.

After backtesting, use factor_analysis on the equity_curve to decompose returns into Fama-French factors (market, size, value, momentum) and estimate true alpha.

ParametersJSON Schema
NameRequiredDescriptionDefault
stagesYesPipeline stages defining the strategy. Each stage is an object with: order (int), type ('screen'|'analyze'|'signal'), skill (skill name), config (dict). Example: [{order: 1, type: 'screen', skill: 'fundamental_screen', config: {pe_lt: 15}}, {order: 2, type: 'signal', skill: 'momentum_screen', config: {lookback_days: 200, top_pct: 0.3}}]
universeNoStock universe. Options: sp500, russell2000, nasdaq100sp500
rebalanceNoRebalance frequency. Options: daily, weekly, monthly, quarterlymonthly
sizingNoPosition sizing method. Options: equal_weight, inverse_volatilityequal_weight
start_dateNoBacktest start date in YYYY-MM-DD format2023-01-01
end_dateNoBacktest end date in YYYY-MM-DD format. Defaults to today.
max_position_sizeNoMaximum weight per position (0-1). E.g., 0.1 = 10% max per stock
stop_lossNoPer-position stop loss (0-1). E.g., 0.15 = sell if position drops 15%
max_drawdownNoMaximum portfolio drawdown before going to cash (0-1). E.g., 0.2 = 20%

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.5/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Discloses key behaviors beyond annotations: fully deterministic, rebalance-loop engine, risk enforcement, and output details (equity curve, trade log, performance metrics). No contradiction with annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Succinct and well-structured, with the main purpose front-loaded. Includes all necessary information without redundancy. Uses clear breaks for outputs and usage guidance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the existence of an output schema, the description sufficiently covers return values and behavioral context. It explains the engine, determinism, and provides post-backtest guidance, making it complete for agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters adequately. The description adds no extra parameter-level information, meeting the baseline expectation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool runs a historical backtest on a stock screening strategy, specifying the engine type, outputs, and determinism. It distinguishes from siblings like screen_stocks (screening) and factor_analysis (post-backtest decomposition).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides guidance on when to use this tool (for backtesting) and a clear next step to use factor_analysis. However, it doesn't explicitly state when not to use it or mention alternatives for live trading.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

factor_analysisA
Read-onlyIdempotent

Decompose strategy or portfolio returns into Fama-French factors using OLS regression.

Breaks down returns into exposures to four systematic factors:

  • Mkt-RF (market risk premium): how much return comes from overall market movement

  • SMB (small minus big): size factor exposure

  • HML (high minus low): value factor exposure

  • Mom (momentum): momentum factor exposure

Also estimates alpha (excess return not explained by factors) with t-statistic for statistical significance. A |t-stat| > 2 suggests statistically significant alpha.

Returns alpha (daily and annualized), factor loadings with t-statistics, R-squared (how much of return variance is explained by factors), and residual volatility.

Use this after backtest_strategy to understand WHERE your returns come from — is it genuine alpha or just factor exposure?

ParametersJSON Schema
NameRequiredDescriptionDefault
equity_curveYesEquity curve as a list of {date, value} objects. Typically from the output of backtest_strategy. Needs at least 30 data points. Example: [{date: '2023-01-03', value: 100000}, {date: '2023-01-04', value: 100500}, ...]

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already indicate read-only, non-destructive, and idempotent behavior. The description adds value by detailing the OLS regression process, factor interpretation, statistical significance thresholds, and the set of outputs (alpha, loadings, R-squared, residual vol). This goes beyond what annotations provide.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise and well-organized: it opens with the main action, breaks down factors, explains significance, lists outputs, and places the tool in context. Every sentence is informative with no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (statistical regression with multiple outputs), the description covers inputs, process, outputs, and usage scenario. The presence of an output schema (as indicated by context signals) reduces the need to detail return values, leaving the description sufficiently complete for an agent to invoke correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100% and the equity_curve parameter is well-described with format, source, requirement, and example. The tool description does not add further parameter details beyond what the schema already provides, so a baseline of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool decomposes returns into Fama-French factors using OLS regression, lists four factors, and explains alpha. It also specifies its place relative to siblings: 'Use this after backtest_strategy to understand WHERE your returns come from.' This distinguishes it from the sibling tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly directs usage after backtest_strategy and notes the requirement of at least 30 data points in the equity curve parameter description. It does not explicitly cover when not to use or contrast with screen_stocks, but the context is clear enough for typical use.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

screen_stocksA
Read-onlyIdempotent

Screen a stock universe with quantitative filters. Returns ranked candidates with scores and metrics.

Use this tool when you need to find stocks matching specific criteria — value stocks, momentum leaders, quality companies, or multi-factor ranked candidates. Supports 7 screen types across 3 universes (S&P 500, Russell 2000, Nasdaq 100).

After screening, use backtest_strategy to test the screen as a trading strategy, or factor_analysis to understand the factor exposures of the selected stocks.

ParametersJSON Schema
NameRequiredDescriptionDefault
universeNoStock universe to screen. Options: sp500, russell2000, nasdaq100sp500
screen_typeNoType of screen to run. Options: fundamental_screen (filter by PE/ROE/debt), quality_screen (filter by ROE/margins), momentum_screen (rank by price momentum), value_screen (rank by valuation), factor_model (multi-factor ranking), technical_signal (RSI/SMA/Bollinger), mean_reversion (z-score below threshold)fundamental_screen
configNoScreen-specific configuration. Examples: fundamental_screen: {pe_lt: 15, roe_gt: 12}. momentum_screen: {lookback_days: 200, top_pct: 0.2}. value_screen: {pe_lt: 20, top_n: 30}. factor_model: {weights: {value: 0.3, momentum: 0.3, quality: 0.2, volatility: 0.2}, top_n: 20}. mean_reversion: {lookback_days: 60, z_threshold: -1.5}. All parameters are optional — sensible defaults are used.
dateNoDate for the screen in YYYY-MM-DD format. Defaults to most recent trading day.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.5/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true and destructiveHint=false, and the description aligns by describing a read-only screening operation that returns results without side effects. The description adds context about the return format (ranked candidates with scores and metrics) and supported screen types and universes, going beyond what annotations provide.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is four sentences, front-loaded with the core action and output, followed by usage context and scope, and ending with guidance on next steps. Every sentence adds value with no redundancy or filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the existence of an output schema and complete schema descriptions, the description covers purpose, usage, scope, and follow-up tools. It provides sufficient context for an agent to understand when and how to use the tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, meaning all parameters are already well-documented in the input schema with their types, defaults, and examples. The description does not add significant new information about parameters beyond the schema, so it meets the baseline expectation for a high-coverage schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states the tool screens a stock universe with quantitative filters and returns ranked candidates. It clearly identifies the action (screen), resource (stock universe), and output (ranked candidates with scores). It also distinguishes from sibling tools by mentioning backtest_strategy and factor_analysis as follow-ups.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly says to use this tool to find stocks matching specific criteria, listing value, momentum, quality, or multi-factor. It provides guidance on what to do after screening (use backtest_strategy or factor_analysis). However, it does not explicitly state when not to use it or mention alternative tools for other tasks, though the context is clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 3 tool updatesv0.2.0
    • First observedbacktest_strategy
    • First observedfactor_analysis
    • First observedscreen_stocks

TDQS

A4.4/5.0
Disambiguation5/5

Each tool has a distinct purpose: screen_stocks finds candidates, backtest_strategy tests strategies, factor_analysis decomposes returns. No overlap in functionality.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern in snake_case: backtest_strategy, factor_analysis, screen_stocks.

Tool Count4/5

Three tools is minimal but well-scoped for the quantitative finance pipeline. Covers screening, backtesting, and analysis without excess.

Completeness4/5

The tools form a coherent workflow (screen → backtest → factor analysis). Minor gaps exist, such as no data retrieval or custom factor tools, but the core pipeline is complete.

Maintenance

ActivityStale
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

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

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables quantitative trading analysis with 12 tools for real-time market data, 28+ technical indicators, FinBERT-powered news sentiment analysis, and automated trading signal generation for stocks and forex.
    1
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to backtest trading strategies described in plain English, providing access to market data, technical indicators, and comprehensive performance reports.
    13
    1
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables quant research, strategy development, backtesting, and paper trading through natural language prompts, integrated with 20+ AI agents.
    134
    -

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/zomma-dev/quantcontext-mcp-server'

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