Skip to main content
Glama
mothanaprime

Portfolio Rotation MCP Server

by mothanaprime

Server Configuration

Describes the environment variables required to run the server.

NameRequiredDescriptionDefault
PORTFOLIO_ROTATION_SOURCENoData source: auto (API first, yfinance fallback), api, financial-datasets, or yfinance. Can be overridden per-call.auto
FINANCIAL_DATASETS_API_KEYNoAPI key for financial-datasets.ai. Without it, prices fall back to yfinance and financials are unavailable.

Capabilities

Features and capabilities supported by this server

CapabilityDetails
tools
{
  "listChanged": false
}
prompts
{
  "listChanged": false
}
resources
{
  "subscribe": false,
  "listChanged": false
}
experimental
{}

Tools

Functions exposed to the LLM to take actions

NameDescription
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}, ...].

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.

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).

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}, ...].

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).

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.

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.

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.

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).

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.

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.

Prompts

Interactive templates invoked by user choice

NameDescription

No prompts

Resources

Contextual data attached and managed by the client

NameDescription

No resources

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/mothanaprime/Rebalance-MCP'

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