portfolio-mcp
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-mcp Optimize my tech_stocks portfolio for the maximum Sharpe ratio"
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-mcp
A portfolio analysis MCP server powered by mcp-refcache for building AI agent tools that handle financial data efficiently.
Features
Portfolio Management: Create, read, update, delete portfolios with persistent storage
Data Sources: Yahoo Finance (stocks/ETFs), CoinGecko (crypto), Synthetic (GBM simulation)
Analysis Tools: Returns, volatility, Sharpe ratio, Sortino ratio, VaR, drawdowns, correlations
Optimization: Efficient Frontier, Monte Carlo simulation, weight optimization
Reference-Based Caching: Large datasets cached via mcp-refcache to avoid context bloat
Related MCP server: FinMCP
Installation
Using uv (recommended)
# Clone the repository
git clone https://github.com/l4b4r4b4b4/portfolio-mcp
cd portfolio-mcp
# Install dependencies
uv sync
# Run the server
uv run portfolio-mcp stdioUsing pip
pip install portfolio-mcp
portfolio-mcp stdioQuick Start
Connect to Claude Desktop
Add to your Claude Desktop configuration (~/.config/claude/claude_desktop_config.json):
{
"mcpServers": {
"portfolio-mcp": {
"command": "uv",
"args": ["run", "--directory", "/path/to/portfolio-mcp", "portfolio-mcp", "stdio"]
}
}
}Basic Usage
Once connected, you can use natural language to:
"Create a portfolio called 'tech_stocks' with AAPL, GOOG, and MSFT"
"Analyze the returns and volatility of my tech_stocks portfolio"
"Optimize my portfolio for maximum Sharpe ratio"
"Show me the efficient frontier with 20 points"
"Compare my portfolios by Sharpe ratio"Available Tools
Portfolio Management (6 tools)
create_portfolio- Create a new portfolio with symbols and weightsget_portfolio- Retrieve portfolio details and metricslist_portfolios- List all stored portfoliosdelete_portfolio- Remove a portfolioupdate_portfolio_weights- Modify portfolio weightsclone_portfolio- Create a copy with optional new weights
Analysis Tools (8 tools)
get_portfolio_metrics- Comprehensive metrics (return, volatility, Sharpe, Sortino, VaR)get_returns- Daily, log, or cumulative returnsget_correlation_matrix- Asset correlation analysisget_covariance_matrix- Variance-covariance structureget_individual_stock_metrics- Per-asset statisticsget_drawdown_analysis- Maximum drawdown and recovery analysiscompare_portfolios- Side-by-side portfolio comparison
Optimization Tools (4 tools)
optimize_portfolio- Optimize weights (max Sharpe, min volatility, target return/vol)get_efficient_frontier- Generate efficient frontier curverun_monte_carlo- Monte Carlo simulation for portfolio analysisapply_optimization- Apply optimization and update stored portfolio
Data Tools (8 tools)
generate_price_series- Generate synthetic GBM price datagenerate_portfolio_scenarios- Create multiple scenario datasetsget_sample_portfolio_data- Get sample data for testingget_trending_coins- Trending cryptocurrencies from CoinGeckosearch_crypto_coins- Search for crypto assetsget_crypto_info- Detailed cryptocurrency informationlist_crypto_symbols- Available crypto symbol mappingsget_cached_result- Retrieve cached large results by reference ID
Architecture
portfolio-mcp/
├── app/
│ ├── __init__.py
│ ├── __main__.py # Typer CLI entry point
│ ├── config.py # Pydantic settings
│ ├── server.py # FastMCP server setup
│ ├── storage.py # RefCache-based portfolio storage
│ ├── models.py # Pydantic models for I/O
│ ├── data_sources.py # Yahoo Finance + CoinGecko APIs
│ └── tools/ # MCP tool implementations
│ ├── portfolio.py
│ ├── analysis.py
│ ├── optimization.py
│ └── data.py
└── tests/ # 163 tests, 81% coverageReference-Based Caching
This server uses mcp-refcache to handle large results efficiently:
Large results are cached - When a tool returns data that exceeds the preview size, it's stored in the cache
References are returned - The tool returns a
ref_idand a preview/sample of the dataFull data on demand - Use
get_cached_result(ref_id=...)to retrieve the complete data
This prevents context window bloat when working with large datasets like price histories or Monte Carlo simulations.
Development
Prerequisites
Python 3.12+
uv (recommended) or pip
Setup
# Clone and install
git clone https://github.com/l4b4r4b4b4/portfolio-mcp
cd portfolio-mcp
uv sync
# Run tests
uv run pytest --cov
# Lint and format
uv run ruff check .
uv run ruff format .Running Locally
# stdio mode (for MCP clients)
uv run portfolio-mcp stdio
# SSE mode (for web clients)
uv run portfolio-mcp sse --port 8080
# Streamable HTTP mode
uv run portfolio-mcp streamable-http --port 8080Configuration
Environment variables:
Variable | Description | Default |
| Logging level |
|
| Default cache TTL in seconds |
|
License
MIT License - see LICENSE for details.
Related Projects
mcp-refcache - Reference-based caching for MCP servers
fastmcp-template - Template this project was built from
FinQuant - Financial portfolio analysis library
Available Tools
26 toolsapply_optimizationA
Apply optimization and update portfolio weights.
Optimizes the portfolio using the specified method and updates the stored portfolio with the new optimal weights.
Args: name: The portfolio name. method: Optimization method (same as optimize_portfolio). target_return: Target return for "efficient_return" method. target_volatility: Target volatility for "efficient_volatility" method.
Returns: Updated portfolio information with new weights and metrics.
Example:
result = apply_optimization(name="tech_stocks", method="max_sharpe") print(f"New Sharpe: {result['new_metrics']['sharpe_ratio']:.2f}")
Inputs: name (required), method, target_return, target_volatility. Returns: object
clone_portfolioA
Clone an existing portfolio, optionally with new weights.
Creates a copy of a portfolio, useful for testing different allocation strategies on the same underlying assets.
Args: source_name: The name of the portfolio to clone. new_name: The name for the cloned portfolio. new_weights: Optional new weights. If None, uses source weights.
Returns: New portfolio information.
Example: ``` # Clone with same weights result = clone_portfolio( source_name="tech_stocks", new_name="tech_stocks_v2" )
# Clone with different weights
result = clone_portfolio(
source_name="tech_stocks",
new_name="tech_aggressive",
new_weights={"GOOG": 0.6, "AMZN": 0.3, "AAPL": 0.1}
)
```Inputs: source_name (required), new_name (required), new_weights. Returns: object
compare_portfoliosA
Compare multiple portfolios side by side.
Retrieves metrics for multiple portfolios and ranks them by key performance indicators.
Args: names: List of portfolio names to compare.
Returns: Dictionary containing: - portfolios: Dict of metrics per portfolio - rankings: Rankings by each metric - best_by_metric: Best portfolio for each metric
Example:
result = compare_portfolios( names=["stocks", "crypto", "metals"] ) print(f"Best Sharpe: {result['best_by_metric']['sharpe_ratio']}")
Inputs: names (required). Returns: object
create_portfolioA
Create a new portfolio and store it in RefCache.
Creates a portfolio from real market data, provided data, or synthetic data. The portfolio is stored persistently and can be retrieved, analyzed, and optimized.
Args: name: Unique name for the portfolio (e.g., 'stocks', 'crypto'). symbols: List of asset symbols. - For stocks/ETFs: ['AAPL', 'GOOG', 'MSFT', 'SPY'] - For crypto via Yahoo: ['BTC-USD', 'ETH-USD'] - For crypto via CoinGecko: ['BTC', 'ETH', 'SOL'] weights: Optional allocation weights per symbol. Must sum to 1.0. If None, equal weights are used. prices: Optional price data per symbol as dict of lists. If provided, overrides source parameter. dates: Optional list of date strings (ISO format) for price data. Required if prices is provided. days: Number of trading days for synthetic data (default: 252). risk_free_rate: Risk-free rate for calculations (default: 0.02). seed: Random seed for synthetic data generation. source: Data source for prices (default: "synthetic"): - "synthetic": Generate GBM simulated data - "yahoo": Fetch from Yahoo Finance (stocks, ETFs, crypto) - "crypto": Fetch from CoinGecko API (crypto only) period: Period for market data (default: "1y"). Options: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
Returns: Dictionary containing: - name: Portfolio name - ref_id: RefCache reference ID for retrieval - symbols: List of symbols in the portfolio - weights: Allocation weights - metrics: Initial portfolio metrics (return, volatility, sharpe) - source: Data source used - created_at: ISO timestamp
Example: ``` # Create portfolio with real stock data result = create_portfolio( name="tech_stocks", symbols=["AAPL", "GOOG", "MSFT"], source="yahoo", period="1y" )
# Create crypto portfolio from CoinGecko
result = create_portfolio(
name="crypto_portfolio",
symbols=["BTC", "ETH", "SOL"],
source="crypto"
)
# Create portfolio with synthetic data (for testing)
result = create_portfolio(
name="test_portfolio",
symbols=["A", "B", "C"],
source="synthetic",
seed=42
)
```Inputs: name (required), symbols (required), weights, prices, +6 more. Returns: object
delete_portfolioA
Delete a stored portfolio.
Permanently removes a portfolio from storage.
Args: name: The portfolio name to delete.
Returns: Dictionary with deletion status.
Example:
result = delete_portfolio(name="old_portfolio") if result['deleted']: print("Portfolio deleted successfully")
Inputs: name (required). Returns: object
generate_portfolio_scenariosA
Generate multiple portfolio scenarios with varying parameters.
Useful for testing optimization strategies across different market conditions.
Large results are cached and returned as a reference with preview. Use get_cached_result to paginate through the full scenario data.
Args: base_symbols: List of asset symbols for all scenarios. num_scenarios: Number of different scenarios to generate. days: Number of trading days per scenario. return_range: (min, max) annual return range for random generation. volatility_range: (min, max) annual volatility range. seed: Random seed for reproducibility.
Returns: Dictionary containing: - ref_id: Reference ID for accessing full cached data - num_scenarios: Number of scenarios generated - preview: Sample of scenarios - summary: Summary statistics across scenarios
Inputs: base_symbols (required), num_scenarios, days, return_range, +2 more. Returns: object
generate_price_seriesA
Generate synthetic price series using Geometric Brownian Motion.
Creates realistic-looking stock price data with customizable parameters for each asset. Supports correlated assets via a correlation matrix.
Large results are cached and returned as a reference with preview. Use get_cached_result to paginate through the full price series.
Args: symbols: List of asset symbols (e.g., ['GOOG', 'AMZN', 'AAPL']). days: Number of trading days to generate (default: 252, one year). initial_prices: Optional initial price per symbol. Defaults to 100.0 for all symbols. annual_returns: Optional expected annual return per symbol. Defaults to 0.08 (8%) for all symbols. annual_volatilities: Optional annual volatility per symbol. Defaults to 0.20 (20%) for all symbols. correlation_matrix: Optional correlation matrix for the assets. Should be a symmetric positive semi-definite matrix. Defaults to identity matrix (uncorrelated). seed: Random seed for reproducibility.
Returns: Dictionary containing: - ref_id: Reference ID for accessing full cached data - symbols: List of symbols - preview: Sample of the price data - total_items: Total number of data points (days) - parameters: Generation parameters used - message: Instructions for pagination
Example: ``` # Generate 1 year of data for 3 tech stocks result = generate_price_series( symbols=["GOOG", "AMZN", "AAPL"], days=252, annual_returns={"GOOG": 0.12, "AMZN": 0.15, "AAPL": 0.10}, annual_volatilities={"GOOG": 0.25, "AMZN": 0.30, "AAPL": 0.22}, seed=42 )
# Use ref_id to paginate
page2 = get_cached_result(ref_id=result["ref_id"], page=2)
```Inputs: symbols (required), days, initial_prices, annual_returns, +3 more. Returns: object
get_cached_resultA
Retrieve a cached result, optionally with pagination.
Use this to:
Get a preview of a cached value
Paginate through large sequences, price series, or returns data
Access specific pages of a cached result
Args: ref_id: The reference ID returned by tools (e.g., from generate_price_series). page: Page number (1-indexed). If not provided, returns the default preview. page_size: Items per page. Default varies by data type (typically 50).
Returns: Dictionary containing: - ref_id: The reference ID - preview: The data for the current page/preview - preview_strategy: How the preview was generated (sample, truncate, paginate) - total_items: Total number of items in the full dataset - page: Current page number (if paginated) - total_pages: Total pages available (if paginated)
Example: ``` # Generate large price series (returns ref_id + preview) result = generate_price_series(symbols=["AAPL", "GOOG"], days=500)
# Get page 2 of the cached data
page2 = get_cached_result(ref_id=result["ref_id"], page=2, page_size=50)
# Get page 5
page5 = get_cached_result(ref_id=result["ref_id"], page=5)
```Inputs: ref_id (required), page, page_size. Returns: object
get_correlation_matrixA
Get the correlation matrix for portfolio assets.
Calculates pairwise correlations between all assets in the
portfolio based on daily returns.
Args:
name: The portfolio name.
Returns:
Dictionary containing:
- symbols: List of symbols
- correlation_matrix: 2D correlation matrix
- correlations: Readable format with symbol pairs
Example:
```
result = get_correlation_matrix(name="tech_stocks")
# Check correlation between GOOG and AMZN
corr = result['correlations']['GOOG']['AMZN']
```Caching Behavior:
Any input parameter can accept a ref_id from a previous tool call
Large results return ref_id + preview; use get_cached_result to paginate
All responses include ref_id for future reference
Preview Size: server default. Override per-call with get_cached_result(ref_id, max_size=...).
Inputs: name (required). Returns: object
get_covariance_matrixA
Get the covariance matrix for portfolio assets.
Calculates pairwise covariances between all assets in the
portfolio based on daily returns.
Args:
name: The portfolio name.
annualized: If True, annualize the covariance (multiply by 252).
Returns:
Dictionary containing:
- symbols: List of symbols
- covariance_matrix: 2D covariance matrix
- variances: Individual asset variances (diagonal)
Example:
```
result = get_covariance_matrix(name="tech_stocks")
print(f"GOOG variance: {result['variances']['GOOG']}")
```Caching Behavior:
Any input parameter can accept a ref_id from a previous tool call
Large results return ref_id + preview; use get_cached_result to paginate
All responses include ref_id for future reference
Preview Size: server default. Override per-call with get_cached_result(ref_id, max_size=...).
Inputs: name (required), annualized. Returns: object
get_crypto_infoA
Get detailed information about a cryptocurrency.
Retrieves current price, market cap, volume, and 24h changes.
Args: symbol: Crypto symbol (e.g., 'BTC', 'ETH', 'SOL') or CoinGecko ID.
Returns: Dictionary containing coin information: - id, name, symbol - current_price, market_cap, total_volume - high_24h, low_24h, price_change_24h - market_cap_rank, categories
Example:
result = get_crypto_info(symbol="BTC") print(f"Bitcoin: ${result['current_price']:,.2f}") print(f"24h change: {result['price_change_percentage_24h']:.2f}%")
Inputs: symbol (required). Returns: object
get_drawdown_analysisB
Analyze portfolio drawdowns.
Calculates maximum drawdown and drawdown periods for the
portfolio, useful for risk assessment.
Args:
name: The portfolio name.
Returns:
Dictionary containing:
- max_drawdown: Maximum drawdown percentage
- max_drawdown_period: Start and end dates of max drawdown
- current_drawdown: Current drawdown from peak
- recovery_needed: Percentage gain needed to recover
Example:
```
result = get_drawdown_analysis(name="tech_stocks")
print(f"Max Drawdown: {result['max_drawdown']:.2%}")
```Caching Behavior:
Any input parameter can accept a ref_id from a previous tool call
Large results return ref_id + preview; use get_cached_result to paginate
All responses include ref_id for future reference
Preview Size: server default. Override per-call with get_cached_result(ref_id, max_size=...).
Inputs: name (required). Returns: object
get_efficient_frontierB
Generate efficient frontier data points for visualization.
Calculates points along the efficient frontier, which represents
the set of optimal portfolios offering the highest expected return
for a given level of risk.
Args:
name: The portfolio name.
num_points: Number of points to generate along the frontier.
Returns:
Dictionary containing:
- frontier_points: List of {volatility, expected_return} points
- optimal_sharpe: Maximum Sharpe ratio portfolio
- optimal_min_volatility: Minimum volatility portfolio
- individual_stocks: Individual stock positions
- current_portfolio: Current portfolio position
Example:
```
result = get_efficient_frontier(name="tech_stocks", num_points=100)
# Plot the frontier
for point in result['frontier_points']:
print(f"Vol: {point['volatility']:.2%}, Return: {point['expected_return']:.2%}")
```Caching Behavior:
Any input parameter can accept a ref_id from a previous tool call
Large results return ref_id + preview; use get_cached_result to paginate
All responses include ref_id for future reference
Preview Size: server default. Override per-call with get_cached_result(ref_id, max_size=...).
Inputs: name (required), num_points. Returns: object
get_individual_stock_metricsA
Get metrics for each individual stock in a portfolio.
Calculates return and volatility metrics for each stock
separately, useful for identifying best/worst performers.
Args:
name: The portfolio name.
Returns:
Dictionary containing metrics per stock:
- mean_return: Average daily return (annualized)
- volatility: Standard deviation (annualized)
- sharpe_ratio: Individual Sharpe ratio
- weight: Current allocation weight
Example:
```
result = get_individual_stock_metrics(name="tech_stocks")
for symbol, metrics in result['stocks'].items():
print(f"{symbol}: Return={metrics['mean_return']:.2%}")
```Caching Behavior:
Any input parameter can accept a ref_id from a previous tool call
Large results return ref_id + preview; use get_cached_result to paginate
All responses include ref_id for future reference
Preview Size: server default. Override per-call with get_cached_result(ref_id, max_size=...).
Inputs: name (required). Returns: object
get_portfolioA
Get detailed information about a stored portfolio.
Retrieves comprehensive information about a portfolio including its allocation, metrics, and settings.
Args: name: The portfolio name.
Returns: Dictionary containing full portfolio details, or error if not found.
Example:
info = get_portfolio(name="tech_stocks") print(f"Sharpe Ratio: {info['metrics']['sharpe_ratio']}")
Inputs: name (required). Returns: object
get_portfolio_metricsA
Get comprehensive metrics for a portfolio.
Calculates and returns all key portfolio metrics including
risk-adjusted returns, volatility measures, and risk metrics.
Args:
name: The portfolio name.
Returns:
Dictionary containing:
- expected_return: Annualized expected return
- volatility: Annualized volatility (standard deviation)
- sharpe_ratio: Risk-adjusted return (Sharpe)
- sortino_ratio: Downside risk-adjusted return (Sortino)
- value_at_risk: VaR at 95% confidence
- downside_risk: Target downside deviation
- skewness: Skewness per stock
- kurtosis: Kurtosis per stock
- beta: Portfolio beta (if market index available)
- treynor_ratio: Treynor ratio (if beta available)
Example:
```
metrics = get_portfolio_metrics(name="tech_stocks")
print(f"Expected Return: {metrics['expected_return']:.2%}")
print(f"Volatility: {metrics['volatility']:.2%}")
print(f"Sharpe Ratio: {metrics['sharpe_ratio']:.2f}")
```Caching Behavior:
Any input parameter can accept a ref_id from a previous tool call
Large results return ref_id + preview; use get_cached_result to paginate
All responses include ref_id for future reference
Preview Size: server default. Override per-call with get_cached_result(ref_id, max_size=...).
Inputs: name (required). Returns: object
get_returnsA
Get returns data for a portfolio.
Calculates different types of returns from the portfolio's
price data.
Args:
name: The portfolio name.
return_type: Type of returns to calculate:
- "daily": Daily percentage returns
- "log": Daily log returns
- "cumulative": Cumulative returns from start
as_percentage: If True, multiply by 100 for percentage display.
Returns:
Dictionary containing:
- return_type: The type of returns calculated
- dates: List of date strings
- returns: Dict of returns per symbol
- portfolio_returns: Weighted portfolio returns
- statistics: Summary statistics (mean, std, min, max)
Example:
```
# Get daily returns
result = get_returns(name="tech_stocks", return_type="daily")
# Get cumulative returns for growth chart
result = get_returns(name="tech_stocks", return_type="cumulative")
```Caching Behavior:
Any input parameter can accept a ref_id from a previous tool call
Large results return ref_id + preview; use get_cached_result to paginate
All responses include ref_id for future reference
Preview Size: server default. Override per-call with get_cached_result(ref_id, max_size=...).
Inputs: name (required), return_type, as_percentage. Returns: object
get_sample_portfolio_dataA
Get pre-defined sample portfolio data for quick testing.
Returns sample data for a diversified portfolio with realistic parameters based on historical market behavior.
Returns: Dictionary with sample portfolio data ready for use with create_portfolio().
Inputs: no named parameters. Returns: object
get_trending_coinsA
Get trending cryptocurrencies from CoinGecko.
Returns a list of coins that are trending in the last 24 hours, useful for discovering popular assets to analyze.
Returns: Dictionary containing: - coins: List of trending coin info (id, name, symbol, rank) - fetched_at: ISO timestamp
Example:
result = get_trending_coins() for coin in result['coins']: print(f"{coin['name']} ({coin['symbol']})")
Inputs: no named parameters. Returns: object
health_checkA
Check server health status.
Returns server health information including cache status and number of stored portfolios.
Returns: Health status information.
Inputs: no named parameters. Returns: object
list_crypto_symbolsA
List supported cryptocurrency symbols and their CoinGecko IDs.
Returns the mapping of common crypto symbols (like BTC, ETH) to their CoinGecko API identifiers.
Returns: Dictionary containing: - symbols: Dict mapping symbol to CoinGecko ID - count: Number of supported symbols - usage: How to use with create_portfolio
Example:
result = list_crypto_symbols() print(f"Supported: {list(result['symbols'].keys())[:10]}...")
Inputs: no named parameters. Returns: object
list_portfoliosA
List all stored portfolios with summary information.
Returns a list of all portfolios in the store with their key metrics and metadata.
Returns: Dictionary containing: - portfolios: List of portfolio summaries - count: Number of portfolios
Example:
result = list_portfolios() for pf in result['portfolios']: print(f"{pf['name']}: Sharpe={pf['metrics']['sharpe']:.2f}")
Inputs: no named parameters. Returns: object
optimize_portfolioA
Optimize portfolio weights using Efficient Frontier.
Finds optimal portfolio weights based on the specified optimization
method. Uses numerical optimization (scipy) to find the solution.
Args:
name: The portfolio name.
method: Optimization method:
- "max_sharpe": Maximize Sharpe ratio (default)
- "min_volatility": Minimize portfolio volatility
- "efficient_return": Minimize volatility for target return
- "efficient_volatility": Maximize return for target volatility
target_return: Required for "efficient_return" method.
The target annualized return to achieve.
target_volatility: Required for "efficient_volatility" method.
The target annualized volatility.
Returns:
Dictionary containing:
- method: Optimization method used
- optimal_weights: Dict of optimal weights per symbol
- expected_return: Expected return of optimal portfolio
- volatility: Volatility of optimal portfolio
- sharpe_ratio: Sharpe ratio of optimal portfolio
- original: Original portfolio metrics for comparison
- improvement: Improvement over original portfolio
Example:
```
# Maximize Sharpe ratio
result = optimize_portfolio(name="tech_stocks", method="max_sharpe")
# Minimize volatility
result = optimize_portfolio(name="tech_stocks", method="min_volatility")
# Target 15% return with minimum volatility
result = optimize_portfolio(
name="tech_stocks",
method="efficient_return",
target_return=0.15
)
```Caching Behavior:
Any input parameter can accept a ref_id from a previous tool call
Large results return ref_id + preview; use get_cached_result to paginate
All responses include ref_id for future reference
Preview Size: server default. Override per-call with get_cached_result(ref_id, max_size=...).
Inputs: name (required), method, target_return, target_volatility. Returns: object
run_monte_carloA
Run Monte Carlo simulation to find optimal portfolios.
Generates random portfolio weight combinations and evaluates their risk/return characteristics to find optimal allocations.
Note: This is computationally intensive. For large num_trials, consider using the Efficient Frontier method instead which provides mathematically optimal solutions.
Args: name: The portfolio name. num_trials: Number of random portfolios to generate (default: 5000).
Returns: Dictionary containing: - num_trials: Number of simulations run - min_volatility_portfolio: Portfolio with minimum volatility - max_sharpe_portfolio: Portfolio with maximum Sharpe ratio - simulation_stats: Statistics about the simulation - sample_portfolios: Sample of generated portfolios
Example:
result = run_monte_carlo(name="tech_stocks", num_trials=10000) best = result['max_sharpe_portfolio'] print(f"Best Sharpe: {best['sharpe_ratio']:.2f}") print(f"Optimal weights: {best['weights']}")
Inputs: name (required), num_trials. Returns: object
search_crypto_coinsA
Search for cryptocurrencies on CoinGecko.
Find coins by name, symbol, or keyword. Useful for discovering coin IDs to use with create_portfolio.
Args: query: Search query (e.g., 'bitcoin', 'defi', 'layer 2').
Returns: Dictionary containing: - coins: List of matching coins (id, name, symbol, market_cap_rank) - count: Number of results - fetched_at: ISO timestamp
Example:
# Search for DeFi coins result = search_crypto_coins(query="defi") for coin in result['coins']: print(f"{coin['name']} ({coin['symbol']}) - Rank: {coin['market_cap_rank']}")
Inputs: query (required). Returns: object
update_portfolio_weightsA
Update the allocation weights of an existing portfolio.
Changes the weight distribution across assets in a portfolio and recalculates all metrics.
Args: name: The portfolio name. weights: New allocation weights per symbol. Must sum to 1.0.
Returns: Updated portfolio information with new metrics.
Example:
result = update_portfolio_weights( name="tech_stocks", weights={"GOOG": 0.5, "AMZN": 0.3, "AAPL": 0.2} ) print(f"New Sharpe: {result['metrics']['sharpe_ratio']}")
Inputs: name (required), weights (required). Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 26 tools
Each tool has a distinct purpose: portfolio CRUD, analysis, optimization, data generation, crypto info, and utility. There is minimal overlap; even related tools like optimize_portfolio and apply_optimization are clearly differentiated.
Tool names follow a consistent verb_noun pattern (e.g., create_portfolio, get_portfolio_metrics, list_portfolios). The few phrase-based names like health_check are minor deviations but do not detract from overall clarity.
26 tools is a comprehensive but well-scoped set for a portfolio management server. Each tool addresses a specific aspect of portfolio creation, analysis, optimization, or data retrieval without redundancy.
The tool surface covers CRUD, analysis, optimization, data generation, and crypto support. Minor gaps exist, such as no tool for adding/removing individual assets or importing/exporting data, but core workflows are well-supported.
Maintenance
Related MCP Connectors
The Octagon MCP server provides specialized AI-powered financial research and analysis by integrating with the Octagon Market Intelligence API. It enables users to analyze public market data (SEC filings, earnings transcripts, financial metrics, and stock data for 8000+ companies), private market data (3M+ companies, 500k+ funding rounds, 2M+ M&A/IPO transactions), and conduct deep research including web scraping capabilities. The server also features autonomous research agents that search hundreds of sources and return fully cited reports in approximately one minute.
Connect Claude, ChatGPT, Codex, Claude Code or another MCP client to your real multi-broker investment portfolio. Fortunest tracks stocks, ETFs and crypto across brokers and exchanges; its MCP server lets your agent read holdings, returns, allocation, risk, trades and tax lots, calculated by Fortunest rather than guessed by the model. Reads run on their own; every change waits for your approval in the Fortunest app, and no tool places an order or moves money. Sign-in is OAuth 2.1 and needs Fortunest Pro (14-day trial, no card). A free demo that needs no account is listed as Fortunest demo.
MCP server exposing the Backtest360 engine API as tools for AI agents.
Official Intrinio MCP server. US stock prices, options and fundamentals for AI agents.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceAn MCP server for tracking and managing cryptocurrency portfolio allocations, enabling AI agents to query and optimize portfolio strategies in real time.10MIT
- AlicenseNot gradedqualityDmaintenanceAn MCP server that enables AI agents to query real-time financial data including stock quotes, market indices, company fundamentals, and portfolio tracking.MIT
- AlicenseBqualityDmaintenanceAn enhanced MCP server that provides financial data and analysis tools for stocks, crypto, precious metals, and more, empowering AI agents with professional financial intelligence, including backtesting, ASCII charts, and simulated portfolios.587MIT
- FlicenseNot gradedqualityDmaintenanceA Model Context Protocol server for managing and analyzing investment portfolios. It enables users to create and update portfolios, fetch real-time stock data and news, generate performance reports, and receive investment recommendations through natural language.-