Portfolio Optimization in Python
Build an efficient frontier, compute the Sharpe-optimal portfolio, and visualize portfolio weights using Monte Carlo simulation.
What this AI workflow does
This AI Data Analyst workflow downloads two years of daily prices for AAPL, MSFT, GOOGL, AMZN, and JPM (or generates correlated synthetic returns if needed) and computes daily returns. It calculates and visualizes the return correlation matrix across the five assets. It runs a Monte Carlo simulation of 5,000 random portfolios to build an efficient frontier, then identifies the maximum Sharpe ratio portfolio and visualizes the resulting weights.
Who this example is for
This is for analysts and students who want a reproducible, code-generating example of mean-variance portfolio optimization in Python. It helps users compare risk, return, and diversification effects across multiple stocks and extract an interpretable set of portfolio weights.
Expected analysis outcomes
These are the results the AI workflow is expected to generate.
- Price DataFrame for the selected tickers over ~2 years
- Daily returns and a 5x5 correlation heatmap
- Efficient frontier scatter plot of risk vs return colored by Sharpe ratio
- Maximum Sharpe portfolio metrics (Sharpe, expected return, volatility) and printed optimal weights
- Portfolio weights visualization (pie chart)
Tools and libraries used
Main Python packages and tooling used to run this AI data analysis task.
- yfinance
- pandas
- numpy
- matplotlib
- seaborn
Prompt sequence
This is the exact list of prompts used in this workflow. The same prompt sequence is sent to each model so outputs and scores can be compared fairly.
- 1download 2 years of daily prices for AAPL, MSFT, GOOGL, AMZN, JPM with yfinance
- 2compute daily returns and show the correlation matrix
- 3run Monte Carlo simulation with 5000 random portfolios and plot the efficient frontier
- 4identify the max Sharpe ratio portfolio and print the optimal weights
Model Comparison
We compared several LLM models on the same analysis task. The table below shows their scores side by side. You can also open each model run to check the full conversation and notebook results.
| Model Source | Score | Task | Execution | Output | Reasoning | Reliability | Run |
|---|---|---|---|---|---|---|---|
| glm-5.1 | 10/10 | 2/2 | 2/2 | 3/3 | 2/2 | 1/1 | Open glm-5.1 conversation |
| gpt-5.4 | 10/10 | 2/2 | 2/2 | 3/3 | 2/2 | 1/1 | Open gpt-5.4 conversation |
| gpt-oss:120b | 10/10 | 2/2 | 2/2 | 3/3 | 2/2 | 1/1 | Open gpt-oss:120b conversation |
| qwen3-coder-next | 10/10 | 2/2 | 2/2 | 3/3 | 2/2 | 1/1 | Open qwen3-coder-next conversation |
| qwen3.5:397b | 10/10 | 2/2 | 2/2 | 3/3 | 2/2 | 1/1 | Open qwen3.5:397b conversation |
| gemma4:31b | 5/10 | 1/2 | 1/2 | 2/3 | 1/2 | 0/1 | Open gemma4:31b conversation |
How scoring works
Each run is graded on five dimensions:
- Task Completion (0-2): how fully the workflow answered the requested analysis task and completed required steps.
- Execution Correctness (0-2): whether generated code is correct, consistent, and likely runnable without major fixes.
- Output Quality (0-3): how well tables, charts, and results match the expected analytical outcomes.
- Reasoning Quality (0-2): clarity and correctness of interpretation, explanation, and conclusions.
- Reliability (0-1): robustness of the run, including low hallucination risk and stable behavior.
The final score is the sum of these dimensions, so total score = 0-10. Higher values indicate more complete, correct, and reliable notebook results for this workflow.
AI Analysis with gemma4:31b
This run uses AI with a step-by-step list of prompts to perform the analysis task Portfolio Optimization in Python. Below, you can review the full conversation generated with gemma4:31b. After the conversation, we show detailed score cards for this run.
Score cards for gemma4:31b for Portfolio Optimization in Python
Total score: 5/10
Task Completion: 1/2
Needs workThe notebook completed the download, correlation matrix, and Monte Carlo frontier, but the final optimal-weights step failed with a NameError before producing the requested pie chart and printed portfolio metrics.
Execution Correctness: 1/2
Needs workMost code is runnable, but the last cell errors because pandas was not imported as `pd`, so the workflow does not execute end-to-end.
Output Quality: 2/3
GoodIt produced the price table, a 5x5 correlation matrix, and an efficient frontier plot. However, the expected optimal weights pie chart and final Sharpe/return/volatility output are missing due to the error.
Reasoning Quality: 1/2
Needs workThe workflow reasoning is mostly sensible, but it incorrectly assumes the final portfolio summary can be built without importing pandas and does not recover from the failure.
Reliability: 0/1
Needs workThe workflow is fragile because a missing import breaks the final required step, preventing a complete and consistent result.
Try MLJAR Studio
Run the same type of AI-powered data analysis on your own datasets with conversational notebooks in MLJAR Studio.
Explore More AI Analysis Examples
Discover additional workflows across categories. Each example includes prompts, conversation outputs, and model-level scoring so you can compare approaches and results.