Session 6: Modern Portfolio Theory - Building Optimal Portfolios Scientifically#
Learning Objectives#
By the end of this session, you will be able to:
Apply Modern Portfolio Theory principles to build mathematically optimal portfolios
Calculate the efficient frontier showing the best risk-return combinations
Find optimal portfolio weights that maximize returns for a given risk level
Understand diversification benefits through correlation and covariance analysis
Compare different portfolio strategies using optimization techniques
Present portfolio optimization results professionally through video communication
Section 1: The Financial Hook#
The Nobel Prize That Changed Investing Forever#
In 1990, Harry Markowitz won the Nobel Prize in Economics for an idea so simple yet revolutionary: you can use math to build better portfolios.
Before Markowitz (1950s):
Investors picked stocks they liked
Diversification meant “don’t put all eggs in one basket”
No scientific way to balance risk and return
After Markowitz:
Mathematical proof that diversification reduces risk
Precise calculation of optimal portfolio weights
Every major fund now uses these principles
The $100 Trillion Impact: Today, over $100 trillion in global assets are managed using Modern Portfolio Theory principles.
The Magic of Diversification#
Consider this real example from 2022:
Tech Stock Portfolio: Lost 35% (high risk, high correlation)
Energy Stock Portfolio: Gained 45% (but volatile)
Optimized Mixed Portfolio: Gained 8% with 60% less volatility
The optimized portfolio didn’t pick winners—it found the mathematical sweet spot.
Why Portfolio Optimization Matters#
The Diversification Paradox:
Combining two risky assets can create a safer portfolio
The whole becomes less risky than its parts
Math proves what seems impossible
Real-World Impact:
Pension Funds: Use optimization to protect retiree savings
University Endowments: Yale’s David Swensen used MPT to grow endowment from $1B to $42B
Your 401(k): Target-date funds use optimization principles
Your Mission Today#
Master the science of portfolio construction:
Build the efficient frontier
Find optimal portfolio weights
Compare optimization strategies
Validate your results professionally
Section 2: Foundational Financial Concepts & Models#
Core Concept: Modern Portfolio Theory (MPT)#
What is Modern Portfolio Theory? MPT is a mathematical framework for building portfolios that maximize expected return for a given level of risk. It’s like finding the best recipe where ingredients (stocks) combine to create something better than individual parts.
The Efficient Frontier#
What is the Efficient Frontier? The efficient frontier is a curve showing all portfolios that offer the highest expected return for each level of risk. Think of it as the “speed limit” of investing—you can’t go faster (get more return) without taking more risk.
Mathematical Definition: For a given level of risk (σ), the efficient frontier shows the maximum possible expected return (μ).
Portfolio Expected Return#
The expected return of a portfolio is the weighted average of individual asset returns:
Where:
\(E(R_p)\) = expected portfolio return
\(w_i\) = weight of asset \(i\)
\(E(R_i)\) = expected return of asset \(i\)
Example:
60% in stocks expecting 10% return
40% in bonds expecting 5% return
Portfolio expected return = (0.60 × 10%) + (0.40 × 5%) = 8%
Portfolio Risk (Variance)#
What Makes Portfolio Risk Special? Portfolio risk is NOT just the average of individual risks. Correlation between assets reduces overall risk.
Where:
\(\sigma_p^2\) = portfolio variance
\(\sigma_i\) = standard deviation of asset \(i\)
\(\rho_{ij}\) = correlation between assets \(i\) and \(j\)
The Diversification Benefit: When correlation < 1, portfolio risk < weighted average of individual risks
The Optimization Problem#
Mean-Variance Optimization: Find portfolio weights that minimize risk for a target return:
Minimize: Portfolio Variance Subject to:
Portfolio Return = Target Return
All weights sum to 100%
No negative weights (no short selling)
🎯 AI Learning Support - Understanding MPT#
Learning Goal: Grasp why mathematical optimization beats intuitive portfolio construction.
Starting Prompt: “Why is diversification called a ‘free lunch’ in investing?”
🚀 Hints to Improve Your Prompt:
Ask for specific examples with numbers
Include your risk tolerance level
Request visual explanations
Ask about correlation effects
💡 Better Version Hints:
Ask why correlation matters more than individual risks
Request the math behind risk reduction
Inquire about real portfolio examples
Ask when diversification fails
🎯 Your Challenge: Create a prompt that helps you understand why two risky stocks can create a safer portfolio than either stock alone.
Section 3: The Financial Gym - Partner Practice & AI Copilot Learning#
Solo Warm-Up (15 minutes)#
Exercise 1: Manual Portfolio Optimization
You have three stocks:
Stock A: Expected return 12%, Risk 20%
Stock B: Expected return 8%, Risk 15%
Stock C: Expected return 10%, Risk 18%
Correlation: All pairs have correlation = 0.3
Try different weight combinations:
Equal weights (33.3% each)
High return focus (60% A, 20% B, 20% C)
Low risk focus (20% A, 60% B, 20% C)
Calculate expected return and estimate which has lowest risk.
AI Copilot Learning Phase (20 minutes)#
Step 1: Understanding Correlation Impact
# CORRELATION AND DIVERSIFICATION
# See how correlation affects portfolio risk
import numpy as np
# Two stocks with same risk
stock1_return = 10 # 10% expected return
stock2_return = 10 # 10% expected return
stock1_risk = 20 # 20% volatility
stock2_risk = 20 # 20% volatility
# Equal weights
weight1 = 0.5
weight2 = 0.5
# Portfolio return (always the same)
portfolio_return = weight1 * stock1_return + weight2 * stock2_return
print(f"Portfolio Return: {portfolio_return}%")
# Portfolio risk with different correlations
correlations = [1.0, 0.5, 0.0, -0.5, -1.0]
print("\nCorrelation Impact on Risk:")
for corr in correlations:
# Calculate portfolio variance
variance = (weight1**2 * stock1_risk**2 +
weight2**2 * stock2_risk**2 +
2 * weight1 * weight2 * stock1_risk * stock2_risk * corr)
portfolio_risk = np.sqrt(variance)
print(f"Correlation {corr:+.1f}: Risk = {portfolio_risk:.1f}%")
💡 AI Learning Support - Correlation Analysis#
Learning Goal: Understand how correlation drives diversification benefits.
Starting Prompt: “Why does correlation between stocks matter for my portfolio?”
🚀 Improvement Hints:
Ask for visual examples
Include specific stock pairs
Request historical correlation data
Ask about correlation stability
💡 Advanced Hints:
Ask when correlations increase (crises)
Request sector correlation patterns
Inquire about international diversification
Ask about alternative assets
🎯 Your Challenge: Develop a prompt that helps you identify which asset combinations provide the best diversification.
Reciprocal Teaching Component (25 minutes)#
Partner A Tasks (10 min):
Explain the efficient frontier concept
Show why portfolio risk < average of individual risks
Demonstrate a simple 2-asset optimization
Partner B Tasks (10 min):
Explain mean-variance optimization
Show impact of changing correlations
Demonstrate risk-return tradeoff
Together (5 min):
Build a 3-asset portfolio
Find the minimum risk combination
Discuss real-world constraints
Collaborative Challenge (20 minutes)#
The Optimization Challenge
You’re building a portfolio with:
US Stocks: E(R) = 10%, σ = 16%
International Stocks: E(R) = 9%, σ = 18%
Bonds: E(R) = 4%, σ = 5%
Correlation: Stocks 0.7, Stock-Bond 0.2, Int-Bond 0.1
Find:
Minimum risk portfolio weights
Maximum Sharpe ratio weights (assume Rf = 2%)
Best portfolio for a conservative investor
Best portfolio for an aggressive investor
Section 4: The Financial Coaching - Your DRIVER Learning Guide#
Complete DRIVER Case Study: University Endowment Optimization#
Scenario: You’re hired as a junior analyst for a $500 million university endowment. The investment committee wants to optimize the portfolio using Modern Portfolio Theory. They need “something more sophisticated than our current 60/40 stocks/bonds allocation.”
D - Define & Discover#
Understanding Optimization Requirements
Portfolio optimization requires:
Historical data for return/risk estimation
Clear investment constraints
Defined risk tolerance
Computational tools
🎯 AI Learning Support - Problem Discovery
Learning Goal: Understand what makes portfolio optimization practical vs. theoretical.
Starting Prompt: “What do I need to build a portfolio optimizer?”
🚀 Enhancement Hints:
Specify the investor type (endowment)
Include time horizon
Ask about data requirements
Mention regulatory constraints
💡 Professional Hints:
Ask about parameter estimation challenges
Request rebalancing considerations
Inquire about transaction costs
Ask about model limitations
🎯 Your Challenge: Create a prompt that uncovers the gap between textbook optimization and real-world implementation.
Design Specifications:
Optimize across 5-8 asset classes
Build efficient frontier
Find minimum variance portfolio
Find maximum Sharpe ratio portfolio
R - Represent#
Optimization Framework
1. Data Preparation
├── Collect returns data
├── Calculate expected returns
└── Calculate covariance matrix
2. Optimization Setup
├── Define objective function
├── Set constraints
└── Choose optimization method
3. Efficient Frontier
├── Minimize risk for return targets
├── Plot risk-return combinations
└── Identify key portfolios
4. Portfolio Selection
├── Minimum variance
├── Maximum Sharpe ratio
└── Custom risk targets
5. Validation
├── Check weight constraints
├── Verify risk-return calculations
└── Compare to benchmarks
🚀 AI Learning Support - System Design
Learning Goal: Design a complete optimization system.
Starting Prompt: “How do I structure portfolio optimization code?”
🚀 Better Planning Hints:
List required calculations
Specify output requirements
Ask about modularity
Request error handling tips
💡 Professional Elements:
Ask about scalability
Request performance considerations
Inquire about maintenance
Ask about documentation needs
🎯 Your Challenge: Create a prompt that helps you design an optimizer that could handle 1000 assets, not just 5.
I - Implement#
Simple Portfolio Optimization
# MODERN PORTFOLIO THEORY IMPLEMENTATION
# Building optimal portfolios step by step
# Step 1: Setup with sample data
import numpy as np
import pandas as pd
import yfinance as yf
# Define asset universe
assets = ['SPY', 'EFA', 'EEM', 'AGG', 'GLD']
asset_names = ['US Stocks', 'Intl Stocks', 'EM Stocks', 'Bonds', 'Gold']
# Download 5 years of data
end_date = pd.Timestamp.now()
start_date = end_date - pd.DateOffset(years=5)
print("PORTFOLIO OPTIMIZATION SYSTEM")
print("=" * 40)
# Get prices
prices = pd.DataFrame()
for asset in assets:
data = yf.download(asset, start=start_date, end=end_date, progress=False)
prices[asset] = data['Adj Close']
# Calculate returns
returns = prices.pct_change().dropna()
# Step 2: Calculate optimization inputs
# Expected returns (annualized)
expected_returns = returns.mean() * 252
print("\nExpected Returns:")
for i, asset in enumerate(asset_names):
print(f"{asset}: {expected_returns[assets[i]]:.2%}")
# Covariance matrix (annualized)
cov_matrix = returns.cov() * 252
# Correlation matrix
corr_matrix = returns.corr()
print("\nAverage Correlation: {:.2f}".format(
corr_matrix.values[np.triu_indices_from(corr_matrix.values, k=1)].mean()
))
Minimum Variance Portfolio
# MINIMUM VARIANCE PORTFOLIO
# Find the lowest risk portfolio
# Step 1: Equal weight starting point
n_assets = len(assets)
equal_weights = np.array([1/n_assets] * n_assets)
# Calculate equal weight metrics
eq_return = np.dot(equal_weights, expected_returns)
eq_variance = np.dot(equal_weights, np.dot(cov_matrix, equal_weights))
eq_volatility = np.sqrt(eq_variance)
print(f"\nEQUAL WEIGHT PORTFOLIO")
print(f"Return: {eq_return:.2%}")
print(f"Risk: {eq_volatility:.2%}")
# Step 2: Simple minimum variance approximation
# Use inverse volatility weighting as approximation
individual_vols = np.sqrt(np.diag(cov_matrix))
inv_vol_weights = 1 / individual_vols
inv_vol_weights = inv_vol_weights / inv_vol_weights.sum()
# Calculate metrics
inv_return = np.dot(inv_vol_weights, expected_returns)
inv_variance = np.dot(inv_vol_weights, np.dot(cov_matrix, inv_vol_weights))
inv_volatility = np.sqrt(inv_variance)
print(f"\nLOW RISK PORTFOLIO (Inverse Vol)")
print(f"Return: {inv_return:.2%}")
print(f"Risk: {inv_volatility:.2%}")
# Display weights
print("\nPortfolio Weights:")
for i, asset in enumerate(asset_names):
print(f"{asset}: {inv_vol_weights[i]:.1%}")
💻 AI Learning Support - Code Understanding
Learning Goal: Understand optimization calculations.
Starting Prompt: “What is a covariance matrix in portfolio optimization?”
🚀 Context Improvements:
Include your specific assets
Ask about interpretation
Request visual representation
Ask about estimation issues
💡 Deeper Understanding:
Ask about matrix properties
Request stability analysis
Inquire about sample size needs
Ask about robust estimation
🎯 Your Challenge: Create a prompt that helps you understand why covariance matrices sometimes lead to extreme portfolio weights.
V - Validate#
Optimization Validation
# VALIDATION CHECKS
# Ensure optimization results make sense
print("\nVALIDATION RESULTS")
print("-" * 40)
# Check 1: Weights sum to 100%
weight_sum = inv_vol_weights.sum()
print(f"Weights sum: {weight_sum:.1%}")
if abs(weight_sum - 1.0) < 0.001:
print("✓ Weights valid")
# Check 2: Risk reduction achieved
risk_reduction = (eq_volatility - inv_volatility) / eq_volatility
print(f"\nRisk Reduction: {risk_reduction:.1%}")
if risk_reduction > 0:
print("✓ Optimization reduced risk")
# Check 3: Diversification
max_weight = inv_vol_weights.max()
print(f"\nMax Weight: {max_weight:.1%}")
if max_weight < 0.6:
print("✓ Well diversified")
else:
print("⚠ Concentrated position")
# Check 4: Compare to naive diversification
if inv_volatility < eq_volatility:
print("\n✓ Optimized portfolio beats equal weights")
🔍 AI Learning Support - Validation
Learning Goal: Ensure optimization produces implementable portfolios.
Starting Prompt: “How do I know if my optimization worked correctly?”
🚀 Specific Improvements:
Include your results
Ask about reasonableness checks
Request industry standards
Ask about common errors
💡 Professional Validation:
Ask about backtest requirements
Request stability testing
Inquire about sensitivity analysis
Ask about implementation costs
🎯 Your Challenge: Develop a prompt that helps you validate portfolios like an investment committee would.
E - Evolve#
Enhancement Opportunities
Your optimizer can evolve to include:
Multiple risk measures (CVaR, downside deviation)
Transaction cost optimization
Tax-aware optimization
ESG constraints
Black-Litterman views
🎯 AI Learning Support - Evolution
Learning Goal: Identify valuable enhancements for real-world use.
Starting Prompt: “What features should I add to my portfolio optimizer?”
🚀 Priority Hints:
Describe current capabilities
Specify investor needs
Ask about complexity tradeoffs
Request implementation effort
💡 Strategic Thinking:
Ask about market trends
Request regulatory requirements
Inquire about client demands
Ask about competitive advantages
🎯 Your Challenge: Create a prompt that helps you prioritize enhancements like a fintech product manager.
R - Reflect#
Key Insights from Portfolio Optimization
Math Beats Intuition: Systematic optimization finds combinations humans miss
Correlation Is Key: Risk reduction comes from how assets move together
Constraints Matter: Real-world limits affect optimal portfolios
Simple Can Win: Basic optimization often beats complex strategies
Professional Applications:
Strategic asset allocation
Risk budgeting
Portfolio rebalancing
Performance attribution
📋 AI Learning Support - Synthesis
Learning Goal: Connect optimization theory to investment practice.
Starting Prompt: “How do real fund managers use portfolio optimization?”
🚀 Real-World Context:
Ask about specific fund types
Include market conditions
Request failure examples
Inquire about evolution
💡 Career Insights:
Ask about required skills
Request job market trends
Inquire about certifications
Ask about career paths
🎯 Your Challenge: Develop a prompt that bridges academic optimization with the messy reality of managing billions.
Section 5: Assignment#
Scenario#
You’re a quantitative analyst at a wealth management firm. A high-net-worth client wants to optimize their three-stock portfolio using Modern Portfolio Theory. They’re skeptical about “mathematical optimization” and need to see clear evidence of how it improves their risk-return profile.
Requirements#
Create a video (approximately 10-15 minutes) demonstrating:
Selection and justification of 3 stocks from different sectors
Implementation of portfolio optimization to find minimum variance and maximum Sharpe portfolios
Comparison of optimized portfolios against equal-weight benchmark
Critical analysis of optimization results and practical limitations
Execution Format#
Use your completed Jupyter notebook or Python script
Run your code cell-by-cell while explaining what each part does
Show outputs including efficient frontier visualization
Discuss whether the optimized weights are practical for real implementation
Deliverables#
Video demonstration showing code execution and analysis
Python code file (.py or .ipynb)
Section 6: Reflect & Connect - Financial Insights Discussion#
Individual Reflection (10 minutes)#
Write your thoughts on:
What surprised you about portfolio optimization results?
Why do correlations matter more than individual returns?
When might optimization give bad advice?
How would you explain MPT to a skeptical investor?
Small Group Discussion (15 minutes)#
In groups of 3-4, discuss:
Compare optimization results
What were your minimum variance weights?
How much risk reduction did you achieve?
Which assets dominated portfolios?
Explore practical challenges
How would you handle changing correlations?
When should you reoptimize?
What about assets not in your universe?
Real-world applications
Would you trust optimization with real money?
How to handle client constraints?
When to override optimization?
Class Synthesis (15 minutes)#
Key Topics for Discussion:
The Optimization Paradox
Why don’t all portfolios converge to one optimal solution?
How do different objectives lead to different portfolios?
Why do professionals still disagree?
Implementation Reality
Transaction costs and taxes
Parameter estimation errors
Changing market conditions
Future of Optimization
Machine learning approaches
Alternative risk measures
Behavioral considerations
Connecting to Practice#
Industry Insight: “We use optimization, but it’s just the starting point. The art is knowing when to trust the model and when to override it based on experience. No model captures everything.”
Patricia Chen, CIO, University Endowment
Key Takeaways Board#
Create class list of:
Most surprising optimization results
Practical implementation challenges
Key insights about diversification
Questions for further research
Section 7: Looking Ahead#
What You’ve Mastered#
✅ Technical Skills:
Efficient frontier construction
Portfolio optimization calculations
Covariance matrix analysis
Constraint implementation
✅ Professional Capabilities:
Risk-return optimization
Diversification quantification
Investment policy implementation
Client portfolio customization
Building Bridges to Session 7#
Next session’s Asset Allocation & Rebalancing builds on optimization:
From Theory to Practice: Today’s optimal weights become tomorrow’s allocations
From Static to Dynamic: One-time optimization becomes ongoing rebalancing
From Unconstrained to Real-World: Add taxes, costs, and constraints
From Single-Period to Multi-Period: Consider long-term strategies
The Portfolio Construction Journey#
Session 6: Find Optimal → Session 7: Implement Strategy → Session 8: Manage Risk
↓ ↓ ↓
Mathematical weights Practical allocation Risk monitoring
Efficient frontier Rebalancing rules Stress testing
Theoretical optimum Real-world execution Ongoing management
Preview Challenge#
Before next session, think about:
How often should you rebalance an optimal portfolio?
What triggers rebalancing decisions?
How do taxes affect optimization?
When do transaction costs overwhelm benefits?
Professional Development Path#
Your optimization skills enable:
Entry Level: Investment analyst roles
3-5 Years: Portfolio management associate
5-10 Years: Senior portfolio manager
10+ Years: Chief Investment Officer
Preparation for Session 7#
Technical Prep:
Review portfolio weights
Understand rebalancing math
Consider transaction costs
Conceptual Prep:
Research rebalancing strategies
Explore tax implications
Study behavioral biases
Professional Prep:
Review robo-advisor approaches
Understand institutional constraints
Research regulatory requirements
Section 8: Appendix - Solutions & Implementation Guide#
Complete Solution Code#
# COMPLETE PORTFOLIO OPTIMIZATION SOLUTION
# Professional MPT implementation made simple
# ===== SETUP =====
import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime
# ===== DATA COLLECTION =====
# Diversified asset classes
assets = ['SPY', 'EFA', 'EEM', 'AGG', 'GLD', 'VNQ']
names = ['US Stocks', 'Intl Dev', 'Emerg Mkts', 'Bonds', 'Gold', 'Real Estate']
# Get 5 years of data
end = datetime.now()
start = datetime(end.year - 5, end.month, end.day)
# Download prices
print("Downloading data...")
prices = pd.DataFrame()
for asset in assets:
temp = yf.download(asset, start=start, end=end, progress=False)
prices[asset] = temp['Adj Close']
# ===== CALCULATE PARAMETERS =====
# Daily returns
returns = prices.pct_change().dropna()
# Annualized expected returns
expected_returns = returns.mean() * 252
# Annualized covariance
cov_matrix = returns.cov() * 252
# Individual volatilities
vols = np.sqrt(np.diag(cov_matrix))
print("\n=== ASSET CHARACTERISTICS ===")
for i, name in enumerate(names):
print(f"{name}: Return={expected_returns[assets[i]]:.1%}, Risk={vols[i]:.1%}")
# ===== SIMPLE PORTFOLIOS =====
n = len(assets)
# 1. Equal Weight
eq_weights = np.ones(n) / n
eq_ret = np.dot(eq_weights, expected_returns)
eq_var = np.dot(eq_weights, np.dot(cov_matrix, eq_weights))
eq_vol = np.sqrt(eq_var)
# 2. Minimum Variance (approximation)
inv_vols = 1 / vols
min_var_weights = inv_vols / inv_vols.sum()
mv_ret = np.dot(min_var_weights, expected_returns)
mv_var = np.dot(min_var_weights, np.dot(cov_matrix, min_var_weights))
mv_vol = np.sqrt(mv_var)
# 3. Risk Parity (simplified)
rp_weights = inv_vols / inv_vols.sum()
rp_ret = np.dot(rp_weights, expected_returns)
rp_var = np.dot(rp_weights, np.dot(cov_matrix, rp_weights))
rp_vol = np.sqrt(rp_var)
# ===== EFFICIENT FRONTIER =====
# Generate random portfolios
np.random.seed(42)
n_portfolios = 10000
results = []
for _ in range(n_portfolios):
# Random weights
w = np.random.random(n)
w = w / w.sum()
# Calculate metrics
ret = np.dot(w, expected_returns)
var = np.dot(w, np.dot(cov_matrix, w))
vol = np.sqrt(var)
sharpe = (ret - 0.02) / vol
results.append([ret, vol, sharpe] + list(w))
# Convert to DataFrame
columns = ['Return', 'Risk', 'Sharpe'] + assets
results_df = pd.DataFrame(results, columns=columns)
# Find efficient frontier (simple approach)
# Group by risk buckets and take highest return
results_df['Risk_Bucket'] = pd.qcut(results_df['Risk'], 20)
efficient = results_df.groupby('Risk_Bucket').apply(
lambda x: x.nlargest(1, 'Return')
).reset_index(drop=True)
# ===== VISUALIZATION =====
plt.figure(figsize=(12, 8))
# Plot all portfolios
plt.scatter(results_df['Risk']*100, results_df['Return']*100,
c=results_df['Sharpe'], cmap='viridis', alpha=0.5, s=10)
# Plot efficient frontier
plt.plot(efficient['Risk']*100, efficient['Return']*100,
'r-', linewidth=2, label='Efficient Frontier')
# Plot special portfolios
plt.scatter(eq_vol*100, eq_ret*100, marker='o', s=200,
c='blue', edgecolor='black', linewidth=2, label='Equal Weight')
plt.scatter(mv_vol*100, mv_ret*100, marker='s', s=200,
c='green', edgecolor='black', linewidth=2, label='Min Variance')
# Plot individual assets
for i, name in enumerate(names):
plt.scatter(vols[i]*100, expected_returns[assets[i]]*100,
marker='^', s=150, edgecolor='black', linewidth=1)
plt.annotate(name, (vols[i]*100, expected_returns[assets[i]]*100),
xytext=(5,5), textcoords='offset points')
plt.xlabel('Risk (Annual Volatility %)')
plt.ylabel('Expected Return (Annual %)')
plt.title('Efficient Frontier and Portfolio Optimization')
plt.legend()
plt.grid(True, alpha=0.3)
plt.colorbar(label='Sharpe Ratio')
plt.tight_layout()
plt.show()
# ===== RESULTS SUMMARY =====
print("\n=== OPTIMIZATION RESULTS ===")
print(f"{'Portfolio':<15} {'Return':>8} {'Risk':>8} {'Sharpe':>8}")
print("-" * 45)
print(f"{'Equal Weight':<15} {eq_ret:>8.1%} {eq_vol:>8.1%} {(eq_ret-0.02)/eq_vol:>8.2f}")
print(f"{'Min Variance':<15} {mv_ret:>8.1%} {mv_vol:>8.1%} {(mv_ret-0.02)/mv_vol:>8.2f}")
print(f"{'Risk Parity':<15} {rp_ret:>8.1%} {rp_vol:>8.1%} {(rp_ret-0.02)/rp_vol:>8.2f}")
# Find max Sharpe from random portfolios
max_sharpe_idx = results_df['Sharpe'].idxmax()
max_sharpe = results_df.loc[max_sharpe_idx]
print(f"{'Max Sharpe':<15} {max_sharpe['Return']:>8.1%} {max_sharpe['Risk']:>8.1%} {max_sharpe['Sharpe']:>8.2f}")
print("\n=== PORTFOLIO WEIGHTS ===")
print(f"{'Asset':<15} {'Equal':>8} {'MinVar':>8} {'MaxSharpe':>8}")
print("-" * 45)
for i, name in enumerate(names):
print(f"{name:<15} {eq_weights[i]:>8.1%} {min_var_weights[i]:>8.1%} {max_sharpe[assets[i]]:>8.1%}")
# Risk reduction
risk_reduction = (eq_vol - mv_vol) / eq_vol
print(f"\nRisk Reduction (Min Var vs Equal): {risk_reduction:.1%}")
Common Student Mistakes#
Forgetting annualization
Wrong: Using daily returns/covariance directly
Right: Multiply by 252 (or √252 for volatility)
Matrix multiplication errors
Wrong: Simple multiplication
Right: Use np.dot for matrix operations
Ignoring constraints
Wrong: Allowing negative weights
Right: Enforce sum=1, all weights ≥ 0
Over-optimization
Wrong: Using in-sample optimal weights
Right: Consider out-of-sample performance
Quick Reference#
Key Concepts:
Efficient Frontier: Maximum return for each risk level
Minimum Variance: Lowest risk portfolio possible
Maximum Sharpe: Best risk-adjusted returns
Diversification: Risk < weighted average when ρ < 1
Python Tips:
np.dot(w, returns)
: Portfolio returnnp.dot(w, np.dot(cov, w))
: Portfolio variancenp.sqrt(variance)
: Portfolio volatilityAlways check weights sum to 1
Implementation Notes for Instructors#
Pre-Session Setup#
Install required packages
Test data downloads
Prepare correlation examples
Have backup data ready
Common Teaching Points#
Start with 2-asset examples
Build intuition before math
Show correlation impact visually
Emphasize practical constraints
Assessment Guidelines#
Understanding > perfect optimization
Test constraint handling
Reward clear explanations
Check validation logic
Professional Resources#
Markowitz (1952): “Portfolio Selection” original paper
CFA Curriculum: Portfolio Management sections
CAIA Materials: Alternative portfolio optimization
Python: cvxpy for advanced optimization
End of Session 6: Modern Portfolio Theory
Next: Session 7 - Asset Allocation & Rebalancing: From Theory to Practice