How Monte Carlo Simulations Reveal Portfolio Sensitivity: A Python Walkthrough
This article explains how Monte Carlo simulation can be used for sensitivity analysis in portfolio risk assessment, walks through a Python implementation, and demonstrates how varying asset allocations impacts expected return and volatility.
Monte Carlo Algorithm
Monte Carlo algorithm is a numerical method based on random sampling that estimates solutions by repeatedly drawing samples from probability distributions. Named after the Monte Carlo casino, it is widely used in physics, engineering, finance and many other fields, especially for problems that are difficult to solve analytically.
Sensitivity Analysis
Sensitivity analysis evaluates how changes or uncertainties in input parameters affect model outputs. By systematically varying inputs and observing output changes, we can identify which parameters most influence the model and understand sources of uncertainty.
Typically, we assume probability distributions for the inputs, then use Monte Carlo simulation to estimate the distribution of outputs. For each input parameter we define a distribution, sample repeatedly, compute the model output, and analyze statistics such as mean and variance to quantify the impact of input uncertainty.
Portfolio Risk Assessment
Consider a portfolio consisting of two stocks, A and B. We aim to assess how different investment proportions affect the portfolio's expected return. Let the proportion of stock A be x_A and that of stock B be 1 - x_A . The expected returns of A and B are mu_A and mu_B respectively.
Parameter setting: Define probability distributions for mu_A and mu_B , e.g., normal distributions with given means and standard deviations.
Random sampling: Draw a large number of samples from these distributions.
Compute expected return: For each pair of sampled returns, calculate the portfolio return R = x_A * R_A + (1 - x_A) * R_B .
Statistical analysis: Analyze the distribution of R (mean, variance) to see how different values of x_A affect the portfolio.
Python code implementation
<code>import numpy as
import matplotlib.pyplot as
# Set parameters
mu_A, sigma_A = 0.05, 0.02 # Stock A mean and std
delta_B, sigma_B = 0.07, 0.02 # Stock B mean and std
x_A = 0.5 # Investment proportion of Stock A
n_simulations = 10000 # Number of simulations
# Generate random samples
R_A_samples = np.random.normal(mu_A, sigma_A, n_simulations)
R_B_samples = np.random.normal(mu_B, sigma_B, n_simulations)
# Compute portfolio expected return
R = x_A * R_A_samples + (1 - x_A) * R_B_samples
# Statistical analysis
print(f"Average expected return: {np.mean(R):.4f}")
print(f"Standard deviation of return: {np.std(R):.4f}")
# Plot results
plt.hist(R, bins=50, alpha=0.7)
plt.xlabel('Expected Return')
plt.ylabel('Frequency')
plt.title('Portfolio Expected Return Distribution')
plt.show()
</code>By adjusting the investment proportions of stocks A and B, we can explore how different portfolio configurations affect the distribution of expected return, especially its mean and standard deviation, which are crucial indicators for investors.
The mean represents the average expected return, while the standard deviation reflects return volatility, i.e., risk. Sensitivity analysis enables investors to tailor the portfolio according to their risk tolerance and return expectations.
Further Steps in Sensitivity Analysis
Adjust investment proportions: Systematically vary x_A from 0 to 1 in increments (e.g., 0.1), automatically setting 1 - x_A for stock B.
Repeat simulation: For each proportion, repeat the random sampling and return calculation.
Collect and analyze data: Record the mean and standard deviation of the portfolio return for each proportion.
Compare and interpret results: Use charts to display how the mean and volatility change with different allocations, helping to assess the impact of asset weighting.
Exploratory code for varying investment proportions:
<code># Investment proportion from 0 to 1 with step 0.05
x_A_values = np.arange(0, 1.05, 0.05)
mean_returns = []
std_devs = []
for x_A in x_A_values:
# Recalculate portfolio return
R = x_A * R_A_samples + (1 - x_A) * R_B_samples
# Collect statistics
mean_returns.append(np.mean(R))
std_devs.append(np.std(R))
# Plot results
plt.figure(figsize=(14, 6))
plt.subplot(1, 2, 1)
plt.plot(x_A_values, mean_returns, '-o')
plt.xlabel('Proportion of Stock A')
plt.ylabel('Mean Expected Return')
plt.title('Mean Expected Return vs. Investment Proportion')
plt.subplot(1, 2, 2)
plt.plot(x_A_values, std_devs, '-o')
plt.xlabel('Proportion of Stock A')
plt.ylabel('Standard Deviation of Return')
plt.title('Return Volatility vs. Investment Proportion')
plt.tight_layout()
plt.show()
</code>The analysis clearly shows that the investment proportion significantly influences both the mean and volatility of the portfolio's expected return. Increasing the weight of stock A changes these metrics, providing valuable guidance for investors.
For risk‑averse investors, a configuration that yields a lower standard deviation may be preferred even if it sacrifices some expected return.
Monte Carlo simulation repeatedly draws samples from predefined probability distributions, enabling approximation of complex mathematical problems.
Sensitivity analysis reveals how model outputs respond to input variations, offering insight into key influencing factors. In portfolio management, this combined approach helps quantify the impact of asset allocation on return and risk, supporting more informed investment decisions.
By integrating these methods, we can better understand uncertainty and complexity in decision‑making, enhancing risk awareness and management across finance, engineering, scientific research, and other domains.
Model Perspective
Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.