Skip to main content
Glama

monte_carlo_simulation

Simulate financial outcomes using Geometric Brownian Motion to project price paths and analyze risk through customizable Monte Carlo simulations.

Instructions

Runs a Monte Carlo simulation using Geometric Brownian Motion (Log Returns).

Args:
    simulations: Number of paths to simulate.
    days: Number of days to project forward.
    visualize: If True, returns a histogram of final outcomes.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
simulationsNo
daysNo
visualizeNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'monte_carlo_simulation' MCP tool. Performs Monte Carlo simulation of portfolio returns over specified days using geometric Brownian motion with correlated log returns via Cholesky decomposition of the covariance matrix. Supports visualization.
    def monte_carlo_simulation(simulations: int = 1000, days: int = 252, visualize: bool = False) -> str:
        """
        Runs a Monte Carlo simulation using Geometric Brownian Motion (Log Returns).
        
        Args:
            simulations: Number of paths to simulate.
            days: Number of days to project forward.
            visualize: If True, returns a histogram of final outcomes.
        """
        data, weights = _get_portfolio_data()
        if data is None:
            return "Portfolio is empty."
        
        # Use Log Returns for additivity
        log_returns = np.log(data / data.shift(1)).dropna()
        
        mean_log_returns = log_returns.mean()
        cov_matrix = log_returns.cov()
        
        # Cholesky Decomposition
        try:
            L = np.linalg.cholesky(cov_matrix)
        except np.linalg.LinAlgError:
            # Fallback for non-positive definite matrix (e.g., too few data points)
            return "Covariance matrix is not positive definite. Insufficient data history."
        
        portfolio_sims = np.zeros((days, simulations))
        initial_value = 1.0 
        
        for i in range(simulations):
            Z = np.random.normal(size=(days, len(weights)))
            # Correlated random shocks
            daily_shocks = np.dot(Z, L.T)
            
            # GBM: S_t = S_0 * exp( (mu - 0.5*sigma^2)*t + sigma*W_t )
            # Here we simulate daily steps
            daily_log_ret = mean_log_returns.values + daily_shocks
            
            # Portfolio level log return
            port_log_ret = np.dot(daily_log_ret, weights)
            
            # Accumulate log returns
            cum_log_ret = np.cumsum(port_log_ret)
            portfolio_sims[:, i] = initial_value * np.exp(cum_log_ret)
            
        final_values = portfolio_sims[-1, :]
        returns = (final_values - 1) * 100  # Convert to percentage
        expected_return = np.mean(final_values) - 1
        worst_case = np.percentile(final_values, 5) - 1
        best_case = np.percentile(final_values, 95) - 1
        
        result = (f"Monte Carlo Results ({simulations} sims, {days} days) [Log Normal]:\n"
                f"Expected Return: {expected_return:.2%}\n"
                f"5th Percentile (VaR 95%): {worst_case:.2%}\n"
                f"95th Percentile (Upside): {best_case:.2%}")
        
        if visualize:
            try:
                from tools.visualizer import plot_histogram
                chart = plot_histogram(
                    returns,
                    bins=50,
                    title=f"Monte Carlo Simulation - {simulations} Paths ({days} days)",
                    x_label="Return (%)",
                    percentiles=[5, 50, 95]
                )
                result += f"\n\n{chart}"
            except Exception as e:
                logger.error(f"Error generating visualization: {e}")
                result += f"\n(Visualization error: {str(e)})"
        
        return result
  • server.py:380-383 (registration)
    Registers 'monte_carlo_simulation' as an MCP tool via the register_tools helper function, which applies @mcp.tool() decorator. Part of the Risk Engine tool group.
    register_tools(
        [portfolio_risk, var, max_drawdown, monte_carlo_simulation],
        "Risk Engine"
    )
  • server.py:14-14 (registration)
    Imports the monte_carlo_simulation function from tools.risk_engine.py into the MCP server module for registration.
    from tools.risk_engine import portfolio_risk, var, max_drawdown, monte_carlo_simulation
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions that the simulation uses Geometric Brownian Motion and that 'visualize' returns a histogram, but it omits critical details like computational intensity, assumptions (e.g., log-normal distribution), error handling, or output format beyond the histogram. This is inadequate for a simulation tool with zero annotation coverage.

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 appropriately sized and front-loaded: the first sentence states the purpose, followed by a bulleted list of parameters with clear explanations. Every sentence earns its place without redundancy, making it efficient and easy to scan.

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

Completeness3/5

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

Given the tool's complexity (simulation with mathematical modeling) and the presence of an output schema, the description is partially complete. It covers the purpose and parameters but lacks details on behavioral aspects like performance or assumptions. The output schema likely handles return values, so the description's focus on parameters is adequate but not fully comprehensive for such a tool.

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

Parameters4/5

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

The description adds meaningful semantics beyond the input schema, which has 0% description coverage. It explains that 'simulations' is the 'Number of paths to simulate', 'days' is 'Number of days to project forward', and 'visualize' returns 'a histogram of final outcomes'. This compensates well for the schema's lack of descriptions, though it could elaborate on units or constraints.

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

Purpose4/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 Monte Carlo simulation using Geometric Brownian Motion (Log Returns)', which is a specific verb ('runs') with resource ('Monte Carlo simulation') and method details. It distinguishes from siblings like 'portfolio_risk' or 'var' by specifying the simulation method, though not explicitly contrasting them.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives such as 'portfolio_risk', 'var', or 'run_backtest'. It lacks context on typical use cases (e.g., financial forecasting, risk assessment) or prerequisites, offering only implied usage through parameter descriptions.

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

Install Server

Other Tools

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/N-lia/MonteWalk'

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