Most financial modeling tutorials assume you already have a Python environment configured, a Jupyter notebook open, and three hours to spare. Claude Code assumes none of that. Anthropic’s code execution feature lets you write, run, debug, and visualize Python — including full Monte Carlo simulations — without leaving the chat interface. You describe what you want, Claude writes the code, runs it, and hands you results and charts on the spot.
This tutorial walks through building a working Monte Carlo portfolio risk simulator step by step. You’ll generate simulated return paths, calculate Value at Risk (VaR), and produce visualizations — all through prompts. The whole thing takes about 15 minutes if you follow along. Longer if you start actually reading the output, which you should.
One honest note before we start: this is a prototyping and learning tool. What you build here is genuinely useful for understanding portfolio risk concepts and rapid exploration. It is not a production risk system — those require regulatory compliance, audit trails, and validation frameworks that no chatbot can substitute for. With that said, let’s build something real.
What You’ll Actually Build
By the end of this tutorial you’ll have a Monte Carlo simulator that models a two-asset portfolio, runs 10,000 simulated price paths over a 252-trading-day horizon, calculates the 95th and 99th percentile Value at Risk, and outputs a clean histogram of final portfolio values with VaR lines marked. Every line of that code gets generated, executed, and debugged inside Claude Code — no copy-paste to a terminal, no local environment setup.
What You Need
You need a Claude account with access to Claude Code — currently available in Claude.ai on the Pro and Team plans. Claude Code’s Python execution environment includes standard data science libraries: NumPy, pandas, matplotlib, and seaborn. You don’t need to install anything locally. Basic familiarity with what Monte Carlo simulation does is helpful but not required — the prompts below will get you there regardless.
Step 1 — Set the Stage With a Context Prompt
Don’t just ask for code immediately. Give Claude the full problem context in your first message. This shapes every subsequent response and saves you from re-explaining halfway through.
I'm building a Monte Carlo portfolio risk simulator in Python. The portfolio has two assets: 60% equities (expected annual return 10%, annual volatility 18%) and 40% bonds (expected annual return 4%, annual volatility 6%). Asset correlation is 0.2. I want to simulate 10,000 portfolio paths over 252 trading days using geometric Brownian motion. Use NumPy for simulation, matplotlib for visualization. Start by confirming the parameters and the approach before writing any code.
That last sentence — “confirm before writing code” — is doing real work here. It forces Claude to restate the model assumptions so you can catch errors before they propagate through 10,000 simulations. If Claude’s interpretation of your parameters looks wrong, fix it now.
Pro tip ✅
Always ask Claude to confirm its interpretation of parameters before generating the simulation code. A misread correlation coefficient or a wrong annualization factor will produce plausible-looking but completely wrong results — and 10,000 iterations of wrong is still wrong.
Step 2 — Generate and Run the Core Simulation
Once Claude confirms the setup, ask for the simulation engine. Be specific about what the code should output so you don’t get a function stub with no example call.
Write and execute the Monte Carlo simulation based on those parameters. The code should: (1) generate correlated random returns using a Cholesky decomposition of the covariance matrix, (2) simulate 10,000 portfolio value paths starting at $100,000 initial investment, (3) store all final portfolio values in a NumPy array, (4) print the mean final value, median, and standard deviation. Run the code and show the output.
Claude will generate the simulation, execute it, and return the printed statistics. Typical output for these parameters looks like a mean final value somewhere in the $105,000–$115,000 range with substantial spread. If the numbers look wildly off — say, a mean final value of $500,000 or $5,000 — the most common culprits are a daily/annual return confusion (divide annual returns by 252 for daily) or a missing square root in the volatility scaling (divide annual volatility by √252). The next step handles exactly this.
Check the daily return and volatility calculations. Confirm that annual returns are divided by 252 for daily drift, and annual volatility is divided by the square root of 252 for daily volatility. Show the intermediate calculated values before running the simulation.
This is a debugging prompt, not a “please fix my code” prompt. The distinction matters — you’re asking Claude to walk through the math so you can verify it, not just silently patch the code.
Warning ⚠️
Geometric Brownian motion requires the Itô correction term in the drift: daily drift = (µ – σ²/2) / 252. Without it, the simulation overestimates expected returns at higher volatilities. Ask Claude explicitly whether this correction is included, because it won’t always apply it by default.
Step 3 — Calculate Value at Risk
With a working simulation, calculating VaR is a one-prompt job.
Using the array of 10,000 final portfolio values from the simulation, calculate: (1) 95% VaR — the loss exceeded by only 5% of scenarios, expressed as a dollar amount relative to the $100,000 initial investment, (2) 99% VaR using the same method, (3) Expected Shortfall (CVaR) at 95% — the average loss in the worst 5% of scenarios. Print all three values clearly labeled.
VaR is the most commonly misunderstood metric in finance, so a quick sanity check: if your 95% VaR comes back as $15,000, that means 5% of your simulated scenarios ended worse than a $15,000 loss over the year. Not “you will lose $15,000.” Not “the worst case is $15,000.” Five percent of paths were worse than that. Expected Shortfall tells you how bad things get in that tail — it’s a more honest number.
Now add a stress test: re-run the simulation with equity volatility doubled to 36% (a crisis scenario) and recalculate all three risk metrics. Compare the base case and stress case results in a formatted table.
This prompt does something useful pedagogically and practically — it shows how VaR scales nonlinearly with volatility, which is the kind of insight that takes five minutes to communicate in a presentation but five seconds to demonstrate with a table.
Step 4 — Visualize the Results
Numbers in a terminal are fine. A histogram with VaR lines marked is something you can actually show someone.
Create a matplotlib visualization with two subplots: (1) Top subplot: histogram of the 10,000 final portfolio values with 50 bins, a vertical line marking the initial $100,000 investment in green, vertical lines marking the 95% and 99% VaR thresholds in orange and red respectively, a legend, and a title "Monte Carlo Portfolio Simulation — Final Value Distribution (n=10,000)". (2) Bottom subplot: plot 100 randomly selected simulation paths (portfolio value over 252 days) in light blue with 10% opacity, plus the mean path in dark blue and the 5th percentile path in red. Label axes properly. Use a clean style — seaborn-v0_8-whitegrid. Save as portfolio_montecarlo.png at 150 DPI.
The two-subplot layout earns its keep here. The histogram shows the distribution of outcomes — where most paths ended up, where the tails are. The path chart shows how you get there — some paths spike early and crash, others grind steadily. Together they tell a more complete story than either alone.
Pro tip ✅
When asking for visualizations, specify the exact style, colors, and labels you want in the prompt. Claude will produce a chart either way, but a vague prompt produces default matplotlib aesthetics from 2012. Specify seaborn-v0_8-whitegrid, font sizes, and DPI upfront.
Step 5 — Add a Sensitivity Analysis
A single simulation is a point estimate dressed up as a distribution. A sensitivity analysis is where Monte Carlo starts earning its complexity cost.
Run a sensitivity analysis varying equity allocation from 20% to 100% in steps of 20% (with bonds making up the remainder). For each allocation, run a 5,000-path simulation and calculate the expected return, 95% VaR, and Sharpe ratio (assume a 4% risk-free rate). Plot the results as a line chart showing expected return vs. 95% VaR for each allocation, with points labeled by equity percentage. This is the efficient frontier approximation for this two-asset portfolio.
This is where Claude Code’s ability to run loops of simulations in one message pays off. Doing this manually in a Jupyter notebook involves running cells, checking output, adjusting parameters, running again. Here you describe the full sweep and get the complete output in one go.
Note 💡
The “efficient frontier” this produces is approximate — it assumes fixed correlations and normally distributed returns, which real asset returns aren’t. For a real allocation decision you’d want fat-tailed distributions (try asking Claude to swap the normal distribution for a Student’s t with 5 degrees of freedom) and time-varying correlations. Ask Claude to modify the simulation to use t-distributed returns and re-run — it’s a two-sentence prompt from here.
Step 6 — Handle Errors and Refine
Claude Code doesn’t always produce perfect code on the first try. When something breaks, the error message appears inline and you can ask for a fix in the same thread with full context.
The simulation is producing negative portfolio values in some paths, which is mathematically impossible for this model. Identify why this is happening — likely an issue with the return calculation or the GBM implementation — fix it, and explain what was wrong.
This prompt pattern — describe the symptom, hypothesize the cause, ask for explanation alongside the fix — is more valuable than “fix this error.” You end up understanding what went wrong, which matters when you’re validating a financial model.
Add input validation to the simulation function: raise a ValueError if allocation weights don't sum to 1.0 (within floating point tolerance), if any volatility input is negative, or if the number of simulations is below 1,000. Test the validation by intentionally passing bad inputs and confirming the errors are raised correctly.
Pro tip ✅
Always ask Claude to write tests for financial code, not just the code itself. A Monte Carlo simulator that passes garbage inputs silently is a liability. Input validation and a few assertion checks take one prompt and prevent the kind of errors that are embarrassing to explain to a risk committee.
Step 7 — Export a Clean, Documented Version
By now you’ve iterated through several versions in the thread. Ask for a clean final version before you close the conversation.
Write a clean, final version of the complete Monte Carlo portfolio simulator as a single Python script. Include: (1) docstrings for all functions, (2) type hints, (3) a main() function that runs the full analysis with the original parameters, (4) comments explaining the Cholesky decomposition step and the Itô correction, (5) all visualization code included. The script should run end-to-end when executed as __main__. No placeholder functions — everything working and complete.
This is your artifact. Copy this script into a .py file or notebook and it works without modification. More importantly, it has documentation that will make sense to you in three months when you’ve forgotten what Itô correction means.
Avoid 🚫
Don’t use AI-generated financial models in production without independent validation. The code Claude produces is structurally sound and statistically reasonable, but financial models require backtesting against historical data, stress testing against known crises, and sign-off from someone who understands the regulatory context. Use this for learning, prototyping, and presenting concepts — not for actual capital allocation decisions.
Prompt Variants Worth Trying
The tutorial above builds one specific model, but the same approach extends in several directions. Want to model options instead of a long-only portfolio? Try this:
Modify the simulator to price a European call option on the equity component using Monte Carlo. Strike price $110 on an underlying starting at $100, risk-free rate 4%, 1-year maturity. Calculate the option price as the discounted expected payoff and compare it to the Black-Scholes analytical price.
Want to use real return distributions instead of the normal approximation:
Replace the normal distribution in the return simulation with a Student's t-distribution with 5 degrees of freedom to model fat tails. Re-run the 10,000-path simulation and compare the 99% VaR to the normal-distribution version. Explain the difference in plain English.
Want to add a third asset:
Add a third asset — gold, with 0% expected return, 15% annual volatility, -0.3 correlation with equities, and +0.1 correlation with bonds. Update the covariance matrix to 3x3, re-run the simulation with a 50/30/20 equity/bond/gold allocation, and show how the VaR changes compared to the two-asset portfolio.
What This Gets You
The honest answer is: a genuinely useful educational tool and a fast prototyping environment that would have taken a full afternoon to set up five years ago. Claude Code removes the friction between “I want to understand portfolio risk” and “I have a working model in front of me.” That matters for financial educators, analysts exploring concepts before committing to a full build, and anyone who needs to show a stakeholder a risk distribution without firing up a Bloomberg terminal.
What it doesn’t get you is a validated, audit-ready production system. The gap between “working prototype” and “production financial model” is where risk management teams, quant validation groups, and regulatory frameworks live. Claude Code helps you get to the conversation — it doesn’t replace the people who need to happen after it. Use it accordingly, and the 15 minutes you spend here will save you hours of blank-screen frustration every time you need to model something new.