Skip to main content
Glama
Portfolio Rotation MCP Server

Portfolio Rotation MCP Server

by mothanaprime

Portfolio Rotation MCP Server

PyPI Python

MCP server for portfolio rotation analysis. Score holdings and candidates across 5 dimensions, identify optimal swaps, validate with risk checks and backtests.

Works with any MCP client: Claude Desktop, ChatGPT, Gemini, LangChain, Cursor, Windsurf, VS Code, Ollama clients, and more.

What It Does

You give it a portfolio and candidate tickers. It returns:

ROTATION SCORECARD (GARP Style)
Ticker | Thesis | Valuation | Momentum | Catalyst | Technical | Composite | Action
META   |   75   |    80     |    78    |    85    |    74     |   78.4    | Strong Buy
AVGO   |   70   |    72     |    75    |    70    |    80     |   73.1    | Buy
AAPL   |   70   |    65     |    62    |    60    |    68     |   65.5    | Hold
MSFT   |   65   |    60     |    58    |    55    |    62     |   60.2    | Hold
JPM    |   50   |    55     |    45    |    40    |    42     |   47.4    | Watch

SWAP RECOMMENDATIONS
Sell JPM (47.4) → Buy META (78.4) | Delta: +31.0 | Strong Swap
Sell JPM (47.4) → Buy AVGO (73.1) | Delta: +25.7 | Strong Swap

RISK FLAGS
⚠️ Technology sector: 35% (>30% limit)

BACKTEST (2y)
Strategy: +42.3% | Benchmark (SPY): +28.1% | Sharpe: 1.24 | Max Drawdown: -14.2%

Related MCP server: Sablier MCP Server

Quick Start

# Install from PyPI
pip install portfolio-rotation-mcp

# Or run directly (no install needed)
uvx portfolio-rotation-mcp

# Set API key (optional -- falls back to yfinance without it)
export FINANCIAL_DATASETS_API_KEY=your-key

Prerequisites

  • Python >= 3.10

  • Optional: financial-datasets.ai API key for premium data (without it, prices come from yfinance and financial statements are unavailable)

11 Tools

Tool

Description

fetch_prices

Historical OHLCV prices (API + yfinance fallback)

fetch_financials

Income/balance/cashflow statements

fetch_ff_factors

Fama-French 5-factor + momentum data

score_tickers

5-dimension scoring (auto + manual)

analyze_risk

Concentration, correlation, volatility

compare_swaps

Pairwise swap recommendations (delta >= 15)

run_backtest

Historical strategy simulation

stress_test

Scenario replay, Monte Carlo, factor decomposition

compute_attribution

Trade attribution and swap alpha

run_pipeline

Full 6-stage rotation analysis

get_skill

Retrieve domain knowledge (scoring rules, swap logic, risk thresholds)

Platform Setup

Claude Desktop

Add to your config file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

  • Linux: ~/.config/claude/claude_desktop_config.json

{
  "mcpServers": {
    "portfolio-rotation": {
      "command": "uvx",
      "args": ["portfolio-rotation-mcp"],
      "env": {
        "FINANCIAL_DATASETS_API_KEY": "your-key"
      }
    }
  }
}

Then in Claude Desktop, just say:

My portfolio is AAPL 20%, MSFT 15%, JPM 10%. Evaluate META and AVGO as swap candidates.

Claude will automatically call the MCP tools.

Claude Code (CLI)

claude mcp add portfolio-rotation -- uvx portfolio-rotation-mcp

Cursor / Windsurf / VS Code

Add to your MCP settings (.cursor/mcp.json, .windsurf/mcp.json, or VS Code MCP config):

{
  "mcpServers": {
    "portfolio-rotation": {
      "command": "uvx",
      "args": ["portfolio-rotation-mcp"],
      "env": {
        "FINANCIAL_DATASETS_API_KEY": "your-key"
      }
    }
  }
}

LangChain (any model: DeepSeek, GPT, Llama, etc.)

from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain_openai import ChatOpenAI

# Use any model -- DeepSeek, GPT, Llama, etc.
llm = ChatOpenAI(
    model="deepseek-chat",  # or "gpt-4o", etc.
    base_url="https://api.deepseek.com/v1",
    api_key="sk-...",
)

async with MultiServerMCPClient({
    "portfolio-rotation": {
        "command": "uvx",
        "args": ["portfolio-rotation-mcp"],
        "env": {"FINANCIAL_DATASETS_API_KEY": "your-key"},
    }
}) as client:
    tools = client.get_tools()
    # Create agent with tools and invoke

OpenAI Agents SDK

from agents import Agent
from agents.mcp import MCPServerStdio

async with MCPServerStdio(
    command="uvx",
    args=["portfolio-rotation-mcp"],
) as server:
    tools = await server.list_tools()
    agent = Agent(name="Rotation Analyst", tools=tools)

Ollama + Continue / LibreChat

Configure in the MCP settings of your Ollama frontend:

{
  "command": "uvx",
  "args": ["portfolio-rotation-mcp"],
  "env": {
    "FINANCIAL_DATASETS_API_KEY": "your-key"
  }
}

Usage Examples

Quick: Full Pipeline (one tool call)

Ask your AI agent:

Analyze my portfolio: AAPL 20% (Technology), MSFT 15% (Technology), JPM 10% (Financials). Candidates: META, AVGO. Use GARP style.

The agent will call run_pipeline which runs all 6 stages automatically: data fetch -> scoring -> risk check -> swap comparison -> backtest -> report.

Targeted: Score Specific Tickers

Score AAPL, META, and AVGO. My thesis score for META is 80 and catalyst is 85.

The agent will call fetch_prices, then score_tickers with your manual overrides.

Deep Dive: Stress Test

Stress test my portfolio under a 2008-style crash scenario. Include Monte Carlo simulation.

The agent will call fetch_prices, fetch_ff_factors, then stress_test.

Post-Trade: Attribution

I sold INTC and bought NVDA on Jan 15 at $120. How did that swap perform?

The agent will call fetch_prices, then compute_attribution to measure swap alpha.

Development

# Clone and install in development mode
git clone git@github.com:mothanaprime/Rebalance-MCP.git
cd Rebalance-MCP
pip install -e .

# Run the server
portfolio-rotation-mcp

# Test with MCP inspector
mcp dev src/portfolio_rotation/server.py

Scoring Framework

5 dimensions, 0-100 each, weighted by investment style:

Dimension

GARP Weight

Auto?

Thesis Integrity

25%

Manual (via overrides)

Valuation Attractiveness

25%

Auto (needs financials)

Fundamental Momentum

20%

Auto (from prices)

Catalyst Proximity

15%

Manual (via overrides)

Technical Trend

15%

Auto (MA/RSI/relative strength)

Swap threshold: Buy Score - Hold Score >= 15

Style presets: garp (default), value, growth, momentum, event_driven -- each has different dimension weights.

See docs/scoring-framework.md for full details.

Agent Prompt

See docs/agent-prompt.md for a model-agnostic system prompt you can use to configure any AI agent for rotation analysis.

Environment Variables

Variable

Required

Default

Description

FINANCIAL_DATASETS_API_KEY

No

--

API key for financial-datasets.ai. Without it, prices fall back to yfinance and financials are unavailable.

PORTFOLIO_ROTATION_SOURCE

No

auto

Data source: auto (API first, yfinance fallback), api, financial-datasets, or yfinance. Can be overridden per-call.

License

MIT

Available Tools

11 tools
analyze_riskA

Analyze portfolio risk: concentration, correlation, volatility.

Checks position concentration (>10% single stock), sector concentration (>30% single sector), pairwise correlation, and portfolio volatility. Optionally includes candidate tickers in correlation matrix to see how they correlate with existing holdings before executing swaps.

Args: portfolio_json: JSON array of holdings, e.g. '[{"ticker": "AAPL", "weight": 0.20, "sector": "Technology"}, ...]'. period: History period for correlation/volatility calculation (default "1y"). Uses yfinance period format: "1y", "2y", "6mo", etc. corr_threshold: Flag pairs with correlation above this (default 0.85). candidates: Optional comma-separated candidate tickers to include in correlation analysis (e.g. "META,AVGO"). These are included in the correlation matrix but not in concentration/weight checks.

Returns: JSON with concentration analysis, correlation matrix (holdings only and with candidates if provided), portfolio volatility, risk flags, and overall risk level (LOW/MEDIUM/HIGH).

Inputs: portfolio_json (required), period, corr_threshold, candidates. Returns: result

compare_swapsA

Generate pairwise swap recommendations from scored tickers.

Compares each holding against each candidate. Recommends a swap when the candidate's composite score exceeds the holding's score by >= threshold.

Args: scores_json: JSON array of score dicts from score_tickers tool. holdings: Comma-separated current holding tickers. candidates: Comma-separated candidate tickers. threshold: Minimum score delta to recommend a swap (default 15).

Returns: JSON with swap recommendations and full scorecard ranking.

Inputs: scores_json (required), holdings (required), candidates (required), threshold. Returns: result

compute_attributionA

Analyze trade attribution and rotation effectiveness.

Matches BUY/SELL trades into round-trips, computes swap alpha (what the replaced stock did), benchmark-relative returns, and pattern analysis with calibration recommendations.

Args: trades_json: JSON array of trades, e.g. '[{"date": "2025-01-15", "action": "BUY", "ticker": "NVDA", "shares": 50, "price": 120.00, "score": 75, "replaced": "INTC"}, ...]'. prices_json: JSON of price data from fetch_prices (the "prices" array). benchmark: Benchmark ticker (default "SPY").

Returns: JSON with round_trips (per-trade attribution, swap alpha) and patterns (win rate, avg return, score-return correlation, recommendations).

Inputs: trades_json (required), prices_json (required), benchmark. Returns: result

fetch_ff_factorsA

Download Fama-French 5-factor + momentum daily data.

Data is freely available from Kenneth French's Data Library. Used for factor decomposition in stress testing.

Args: start_date: Filter to dates on or after this date (default "2020-01-01").

Returns: JSON with factor records: [{date, MKT-RF, SMB, HML, RMW, CMA, MOM, RF}, ...]. All values are decimals (not percent).

Inputs: start_date. Returns: result

fetch_financialsA

Fetch financial statements (income, balance sheet, cashflow) from the API.

Requires FINANCIAL_DATASETS_API_KEY env var.

Args: tickers: Comma-separated ticker symbols (e.g. "AAPL,MSFT"). stmt_type: Statement type -- "income", "balance", "cashflow", or "all". period: "annual" or "quarterly". limit: Number of periods per ticker (default 5).

Returns: JSON with financial statement records.

Inputs: tickers (required), stmt_type, period, limit. Returns: result

fetch_pricesA

Fetch historical daily OHLCV prices for given tickers.

Uses financial-datasets API with automatic yfinance fallback. Set FINANCIAL_DATASETS_API_KEY env var for API access. Set PORTFOLIO_ROTATION_SOURCE env var to change the default source.

Args: tickers: Comma-separated ticker symbols (e.g. "AAPL,MSFT,NVDA,SPY"). start_date: Start date in YYYY-MM-DD format (e.g. "2023-01-01"). end_date: End date in YYYY-MM-DD format (e.g. "2026-03-05"). source: Data source -- "auto" (API first, yfinance fallback), "api", "financial-datasets" (same as "api"), or "yfinance". If empty, reads PORTFOLIO_ROTATION_SOURCE env var (default: "auto").

Returns: JSON with price records: [{date, ticker, open, high, low, close, volume}, ...].

Inputs: tickers (required), start_date (required), end_date (required), source. Returns: result

get_skillA

Get domain knowledge for portfolio rotation analysis.

Returns detailed methodology, decision rules, scoring criteria, and interpretation guidelines. Call this BEFORE using other tools to understand how to interpret their outputs correctly.

Available skills:

  • "scoring-framework": 5-dimension scoring system (0-100), criteria matrices, decision thresholds, auto vs manual dimensions

  • "swap-methodology": Swap decision rules, delta thresholds, ranking logic, edge cases, post-swap monitoring

  • "risk-management": Concentration limits, correlation checks, volatility thresholds, risk level classification

  • "style-presets": GARP/value/growth/momentum/event-driven weight matrices and when to use each style

  • "rotation-pipeline": 6-stage pipeline orchestration, stage dependencies, partial run options

Args: name: Skill name to retrieve. Use "" or "all" to list available skills with brief descriptions.

Returns: Markdown content with the requested domain knowledge, or a list of available skills if no name is provided.

Inputs: name. Returns: result

run_backtestA

Backtest a rotation strategy on historical price data.

Uses price momentum ranking by default. Simulates monthly rebalancing with trailing stops and transaction costs.

Args: prices_json: JSON of price data from fetch_prices (the "prices" array). strategy_json: Optional JSON strategy config, e.g. '{"rebalance": "monthly", "max_positions": 5, "sizing": "equal_weight", "entry": {"min_score": 60}, "exit": {"trailing_stop": 0.15}}'. If empty, uses sensible defaults. benchmark: Benchmark ticker (default "SPY"). cost_bps: Transaction cost in basis points (default 10). scores_json: Optional JSON of score results from score_tickers tool. When provided with ranking_mode="score", uses composite scores for initial allocation instead of price momentum. ranking_mode: "momentum" (default, rank by 3M price return) or "score" (rank by composite scores for initial allocation). When "score", the entry.min_score threshold from strategy is honored. Note: subsequent rebalances use momentum since scores can't be recomputed mid-backtest without financials at each date.

Returns: JSON with metrics (total_return, CAGR, Sharpe, Sortino, max_drawdown, win_rate), equity_curve, trade_log, and monthly_returns.

Inputs: prices_json (required), strategy_json, benchmark, cost_bps, +2 more. Returns: result

run_pipelineA

Run the full 6-stage rotation analysis pipeline.

Stages: refresh (fetch prices) -> score (5-dimension scoring) -> risk (concentration/correlation) -> compare (swap recommendations) -> backtest (historical simulation) -> report (markdown summary).

This is the main entry point for a complete rotation analysis.

Args: portfolio_json: JSON array of current holdings, e.g. '[{"ticker": "AAPL", "weight": 0.20, "sector": "Technology"}, {"ticker": "MSFT", "weight": 0.15, "sector": "Technology"}, ...]'. candidates: Comma-separated candidate tickers to evaluate (e.g. "META,AVGO,LLY"). style: Investment style -- "garp" (default), "value", "growth", "momentum", "event_driven". overrides_json: Optional JSON of manual score overrides, e.g. '{"AAPL": {"thesis": 75, "catalyst": 60}}'. benchmark: Benchmark ticker (default "SPY"). stages: Comma-separated stages or "all" (default "all"). skip_refresh: Skip data fetching, use cached data (default False). start_date: Price data start date YYYY-MM-DD (default: 3 years ago). end_date: Price data end date YYYY-MM-DD (default: today). source: Data source for price fetching -- "auto" (API first, yfinance fallback), "api", "financial-datasets" (same as "api"), or "yfinance". If empty, reads PORTFOLIO_ROTATION_SOURCE env var (default: "auto").

Returns: JSON with complete pipeline results: scores, swap recommendations, risk analysis, backtest metrics, and markdown report.

Inputs: portfolio_json (required), candidates (required), style, overrides_json, +6 more. Returns: result

score_tickersA

Score tickers across 5 dimensions for rotation analysis.

Dimensions (0-100 each):

  • Thesis Integrity (manual via overrides)

  • Valuation Attractiveness (auto with financials, or manual)

  • Fundamental Momentum (auto from prices + financials)

  • Catalyst Proximity (manual via overrides)

  • Technical Trend (auto from prices: MA crossovers, RSI, relative strength)

Args: tickers: Comma-separated tickers to score (e.g. "AAPL,MSFT,NVDA,META"). prices_json: JSON string of price data from fetch_prices (the "prices" array). benchmark: Benchmark ticker for relative strength (default "SPY"). financials_json: Optional JSON string of financials from fetch_financials. overrides_json: Optional JSON string of manual overrides, e.g. '{"AAPL": {"thesis": 75, "catalyst": 60}, "MSFT": {"thesis": 70}}'. holdings: Comma-separated current holding tickers for action labeling. style: Investment style -- "garp", "value", "growth", "momentum", or "event_driven".

Returns: JSON with scored tickers: [{ticker, thesis, valuation, momentum, catalyst, technical, composite, action, style, auto_dimensions, manual_dimensions}, ...].

Inputs: tickers (required), prices_json (required), benchmark, financials_json, +3 more. Returns: result

stress_testA

Run comprehensive portfolio stress tests.

Includes: historical scenario replay (GFC, COVID, etc.), hypothetical rate/equity/sector shocks, Fama-French factor decomposition, and Monte Carlo simulation.

Args: portfolio_json: JSON array of holdings, e.g. '[{"ticker": "AAPL", "weight": 0.20, "sector": "Technology"}, ...]'. prices_json: JSON of price data from fetch_prices (the "prices" array). factor_data_json: Optional JSON of Fama-French factors from fetch_ff_factors. benchmark: Benchmark ticker (default "SPY"). run_scenarios: Run historical scenario replay (default True). run_shocks: Run hypothetical shocks (default True). run_factors: Run Fama-French factor decomposition (default True). run_montecarlo: Run Monte Carlo simulation (default True). n_simulations: Number of Monte Carlo simulations (default 10000).

Returns: JSON with scenario results, shock estimates, factor betas/alpha, Monte Carlo VaR/CVaR, risk flags, and overall risk level.

Inputs: portfolio_json (required), prices_json (required), factor_data_json, benchmark, +5 more. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 11 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose, from data fetching (fetch_prices, fetch_financials, fetch_ff_factors) to analysis (analyze_risk, score_tickers, compare_swaps, compute_attribution, stress_test, run_backtest) and orchestration (run_pipeline, get_skill). No two tools overlap in functionality; the pipeline tool is explicitly a meta-orchestrator, avoiding confusion.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern with lowercase and underscores: analyze_risk, compare_swaps, compute_attribution, fetch_ff_factors, fetch_financials, fetch_prices, get_skill, run_backtest, run_pipeline, score_tickers, stress_test. The naming is predictable and uniform.

    Tool Count5/5

    11 tools is well-scoped for a portfolio rotation analysis server. The count covers essential data retrieval, scoring, risk assessment, swap comparison, backtesting, attribution, stress testing, and a full pipeline orchestrator. No tools feel redundant or extraneous.

    Completeness5/5

    The tool surface covers the entire portfolio rotation workflow: data acquisition (prices, financials, factors), scoring, risk analysis, swap recommendations, backtesting, attribution, stress testing, and a knowledge skill. The pipeline tool ties everything together. No obvious gaps exist for the stated purpose.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Portfolio risk analytics MCP server — VaR, Monte Carlo simulation, stress testing, portfolio optimization, options Greeks, and correlation analysis. Real market data via Yahoo Finance. Free tier available, Pro at $29/mo.
      10
      94 npm
      2
      MIT
    • F
      license
      B
      quality
      D
      maintenance
      Enables unified access to portfolio management, market data, risk analysis, trade records, compliance checks, and Slack notifications through a single MCP server.
      18
      -
    • F
      license
      A
      quality
      D
      maintenance
      MCP server providing portfolio analytics tools: beta to a benchmark, sector correlation, and FIFO trade matching with realized/unrealized P&L using Yahoo Finance prices.
      3
      -