Here is a breakdown of the code by functional blocks:
1. Data Preparation & Returns
In financial analysis, we rarely look at the raw price of a stock (like $500). Instead,
we look at the Percentage Change (Returns).
df.pct_change(): Calculates the percentage increase or decrease between rows.
Annualization: Since the data is weekly, we multiply the average returns by 52 and
the covariance by 52. This scales our "7-day" view up to a "1-year" view.
2. Portfolio Performance Function
This is the heart of the mathematical engine. It uses linear algebra to calculate how a
"basket" of stocks would perform.
Return: A simple weighted average of all stock returns.
Risk (Volatility): Calculated using the Covariance Matrix. This measures
how stocks move in relation to each other. Diversification works because
when one stock goes down, another might stay flat or go up.
3. The "Optimizer" (SLSQP)
This is the most "Intermediate-to-Advanced" part of your code. We use
[Link].
The Goal: We want the highest Sharpe Ratio (Return minus Risk-Free Rate,
divided by Risk).
The Constraints:
All weights must add up to 1.0 (100% of your money).
Weights must be between 0 and 1 (No "short-selling" or borrowing
money).
The Logic: Since the computer can only "minimize" things, we tell it to
minimize the Negative Sharpe Ratio. Minimizing a negative is the same as
maximizing a positive.
4. Monte Carlo Simulation
Instead of using math to find the perfect answer, we "brute force" it.
We create 25,000 random portfolios with random weights.
We plot every single one. This creates that "cloud" of dots you see in the final
graph. It helps visualize all the possible combinations of these 10 stocks.
5. The Efficient Frontier & CML
These are the "Thesis Level" boundaries of the graph:
Efficient Frontier: This is the line that connects the very "top-left" dots of the
cloud. It represents the absolute minimum risk you can take for a specific
target return.
Capital Market Line (CML): This is a tangent line that starts at the Risk-
Free Rate (e.g., a government bond) and touches the Efficient Frontier at
exactly one point: the Tangency Portfolio.
6. Visualization (Matplotlib)
The code uses [Link] for the "cloud" and [Link] for the lines.
The Gold Star is your "Optimized" result—the best mathematical balance of
risk and reward.
The Color Bar (Viridis) shows the Sharpe Ratio; brighter colors usually
indicate "better" portfolios (more return per unit of risk).
Tips for a New Learner:
NumPy Broadcasting: Notice how we do weights * annual_returns. We aren't
using a for loop; NumPy multiplies the entire list at once. This is "vectorization" and
is crucial for data analysis.
Lambda Functions: In the constraints, lambda x: [Link](x) - 1 is a
"throwaway" function. It’s a quick way to tell the optimizer: "Hey, make sure the sum
of x equals 1."
The .dot() method: This is matrix multiplication. It is the standard way to calculate
portfolio variance in finance.