Portfolio Rotation MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Portfolio Rotation MCP Server My portfolio is AAPL 20%, MSFT 15%, JPM 10%. Evaluate META and AVGO as swap candidates."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Portfolio Rotation MCP Server
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-keyPrerequisites
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 |
| Historical OHLCV prices (API + yfinance fallback) |
| Income/balance/cashflow statements |
| Fama-French 5-factor + momentum data |
| 5-dimension scoring (auto + manual) |
| Concentration, correlation, volatility |
| Pairwise swap recommendations (delta >= 15) |
| Historical strategy simulation |
| Scenario replay, Monte Carlo, factor decomposition |
| Trade attribution and swap alpha |
| Full 6-stage rotation analysis |
| 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.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.jsonLinux:
~/.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-mcpCursor / 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 invokeOpenAI 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.pyScoring 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 |
| No | -- | API key for financial-datasets.ai. Without it, prices fall back to yfinance and financials are unavailable. |
| No |
| Data source: |
License
MIT
Available Tools
11 toolsanalyze_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
Scored across 11 tools
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.
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.
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.
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
Related MCP Connectors
Production MCP server for US equity and options intelligence: real-time IV radar, Monte Carlo simulation, options pressure, strategy backtesting, AI prediction, pre-trade risk analysis, and automated stock research reports.
Research-only MCP server: your AI as a quant research desk. 90 tools, no trades, no brokers.
7-factor stock scoring MCP server. US/HK/CN, 74 stocks. Free + Premium (USDC/Base). x402 ready.
MCP server for VC pitch-deck scoring, thesis-fit matching, and deal-flow management.
Related MCP Servers
- AlicenseAqualityDmaintenancePortfolio 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.1094 npm2MIT

Sablier MCP Serverofficial
AlicenseAqualityDmaintenanceAn MCP server that lets AI assistants analyze portfolios, stress-test scenarios, generate synthetic market paths, and scan SEC filings — in under 2 minutes.833MIT- FlicenseBqualityDmaintenanceEnables unified access to portfolio management, market data, risk analysis, trade records, compliance checks, and Slack notifications through a single MCP server.18-
- FlicenseAqualityDmaintenanceMCP 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-