Session 3: Risk and Return - Quantifying Uncertainty#
🤖 AI Copilot Reminder: Throughout this session, you’ll be working alongside your AI copilot to understand statistical concepts, analyze real market data, and prepare to teach others. Look for the 🤖 symbol for specific collaboration opportunities.
Section 1: The Investment Hook#
The Great Debate: Stocks vs. Bonds for the Long Run#
Sarah has implemented her three-fund portfolio (VTI, VXUS, BND) as planned from Session 2. She’s allocated 70% to stocks and 30% to bonds, but her conservative uncle Dave challenges her approach:
Uncle Dave’s Argument: “Sarah, you’re being reckless with stocks. Look at what happened in 2008 - people lost 40% of their money! Bonds are steady and safe. Here’s proof:”
Recent Performance |
1-Year Return |
3-Year Average |
---|---|---|
Bond Fund (BND) |
+2.8% |
+1.9% |
Stock Fund (VTI) |
-8.2% |
+8.4% |
Sarah’s Confusion: “But in Session 1, we learned that stocks outperform bonds over the long run. How do I know if that’s actually true? When Dave shows me these numbers, I can’t argue back with real data.”
The Core Challenge: Sarah realizes she needs to move beyond general statements about risk and return to actual statistical analysis. She faces the fundamental question: “Are stocks always better than bonds in the long run, and how can I prove this with data rather than just assumptions?”
Timeline Visualization: The Risk-Return Investigation#
Historical Analysis Current Decision Future Monitoring
(20+ years of data) → Statistical Measurement → Portfolio Optimization
↓ ↓ ↓
Calculate Risk Quantify Trade-offs Make Data-Driven
and Return Metrics with Real Numbers Adjustments
This session addresses the critical transition from intuitive understanding of risk to quantitative measurement that enables data-driven investment decisions.
Learning Connection#
Moving from qualitative concepts (“stocks are riskier but offer higher returns”) to quantitative analysis (“stocks have a standard deviation of 16% vs. 4% for bonds, but provide an average risk premium of 6% annually over the past 30 years”). This mathematical foundation enables the portfolio optimization we’ll explore in Session 4.
Section 2: Foundational Investment Concepts & Models#
Statistical Foundations for Investment Analysis#
🤖 AI Copilot Activity: Before diving into the mathematics, ask your AI copilot: “Help me understand why statistical analysis is crucial for investment decisions. What are the key statistical concepts I need to master to analyze risk and return? How do investment professionals use these tools in practice?”
Return Calculation Methods - Complete Framework#
Simple Returns (Single Period)
Definition: The percentage change in value over a single time period, including both capital appreciation and income
Formula: R = (Ending Value - Beginning Value + Income) / Beginning Value
Example: Stock bought at $100, sold at $110 with $2 dividend = (110 - 100 + 2) / 100 = 12%
Uses: Basic performance measurement, comparing single-period results
Limitations: Cannot be easily combined across multiple periods
Annualized Returns (Multi-Period)
Definition: The equivalent annual return that would produce the same cumulative result over multiple periods
Formula: Annualized Return = (Ending Value / Beginning Value)^(1/n) - 1, where n = years
Example: Investment grows from $1,000 to $1,500 over 3 years = (1,500/1,000)^(1/3) - 1 = 14.47% annually
Uses: Comparing investments with different time periods, standardizing performance
Critical for: Long-term investment analysis and benchmarking
Arithmetic vs. Geometric Mean Returns
Arithmetic Mean Return
Definition: Simple average of periodic returns
Formula: (R₁ + R₂ + … + Rₙ) / n
Example: Returns of 10%, -5%, 15% → Arithmetic mean = (10 - 5 + 15) / 3 = 6.67%
Uses: Expected return calculations, theoretical analysis
Characteristic: Always higher than geometric mean when returns vary
Geometric Mean Return
Definition: The average compound annual growth rate
Formula: [(1 + R₁) × (1 + R₂) × … × (1 + Rₙ)]^(1/n) - 1
Example: Same returns → [(1.10) × (0.95) × (1.15)]^(1/3) - 1 = 6.49%
Uses: Actual historical performance measurement, wealth accumulation analysis
Critical: More accurate for measuring actual investment experience
Risk Measurement - Comprehensive Statistical Framework#
🤖 AI Copilot Activity: Ask your AI copilot: “Explain the different ways to measure investment risk and why volatility (standard deviation) became the standard measure. What are the advantages and limitations of using standard deviation to quantify risk?”
Variance and Standard Deviation
Variance (σ²)
Definition: The average of squared deviations from the mean return
Formula: σ² = Σ(Rᵢ - R̄)² / (n-1), where R̄ is the mean return
Interpretation: Measures the spread of returns around the average
Units: Percentage points squared (difficult to interpret directly)
Standard Deviation (σ)
Definition: The square root of variance, bringing the risk measure back to percentage terms
Formula: σ = √(Variance)
Interpretation: In a normal distribution, ~68% of returns fall within 1 standard deviation of the mean
Example: If stocks average 10% return with 16% standard deviation, expect returns between -6% and +26% about 68% of the time
Industry Standard: Universal measure for comparing investment volatility
Risk Interpretation Guidelines
Low Risk: Standard deviation < 5% (money market funds, short-term bonds)
Moderate Risk: Standard deviation 5-15% (balanced funds, long-term bonds)
High Risk: Standard deviation 15-25% (domestic stock funds)
Very High Risk: Standard deviation > 25% (emerging markets, sector funds, individual stocks)
Alternative Risk Measures
Downside Deviation
Definition: Standard deviation calculated using only returns below the mean
Purpose: Focuses on “bad” volatility that investors actually care about
Advantage: More intuitive since upside volatility isn’t truly risky
Maximum Drawdown
Definition: The largest peak-to-trough decline during a specific period
Example: If an investment goes from $1,000 to $600 at its worst point, maximum drawdown = 40%
Importance: Shows worst-case scenario investors might experience
Value at Risk (VaR)
Definition: The maximum loss expected over a specific time period at a given confidence level
Example: 5% VaR of $10,000 means only 5% chance of losing more than $10,000
Professional Use: Risk management in institutional portfolios
Risk-Adjusted Return Measures#
🤖 AI Copilot Activity: Ask your AI copilot: “Help me understand why we need risk-adjusted return measures. How do these metrics help investors make better decisions? When would each measure be most useful?”
Sharpe Ratio - The Gold Standard
Definition: Excess return per unit of total risk
Formula: Sharpe Ratio = (Portfolio Return - Risk-free Rate) / Portfolio Standard Deviation
Interpretation: Higher values indicate better risk-adjusted performance
Example: Portfolio earning 12% with 16% volatility, risk-free rate 3% → Sharpe = (12-3)/16 = 0.56
Benchmark: Values above 1.0 considered good, above 2.0 considered excellent
Limitation: Assumes normal distribution of returns
Sortino Ratio - Downside-Focused Alternative
Definition: Excess return per unit of downside risk
Formula: Sortino Ratio = (Portfolio Return - Risk-free Rate) / Downside Deviation
Advantage: Penalizes only harmful volatility
Use Case: Better for evaluating investments with asymmetric return distributions
Information Ratio - Active Management Measure
Definition: Active return per unit of tracking error
Formula: Information Ratio = (Portfolio Return - Benchmark Return) / Tracking Error
Purpose: Evaluates skill of active managers in adding value relative to benchmark
Interpretation: Measures consistency of outperformance
Historical Performance Analysis Framework#
Asset Class Historical Returns (1928-2023)
Large Cap Stocks: 10.1% average annual return, 19.8% standard deviation
Small Cap Stocks: 11.9% average annual return, 31.6% standard deviation
Long-term Government Bonds: 5.5% average annual return, 9.4% standard deviation
Treasury Bills: 3.3% average annual return, 3.1% standard deviation
Inflation (CPI): 2.9% average annual rate
Key Insights from Historical Data
Risk Premium Exists: Stocks have consistently outperformed bonds over long periods
Volatility Matters: Higher returns come with substantially higher volatility
Time Horizon Impact: Stock risk decreases with longer holding periods
No Guarantees: Past performance doesn’t guarantee future results
Distribution of Investment Returns#
🤖 AI Copilot Activity: Ask your AI copilot: “Explain how investment returns are distributed and why this matters for portfolio planning. Are stock returns normally distributed, and what are the implications if they’re not?”
Normal Distribution Assumptions
Traditional Theory: Many financial models assume returns follow normal (bell curve) distribution
Practical Reality: Actual returns show “fat tails” (more extreme events than normal distribution predicts)
Implications: Standard deviation may underestimate true risk of extreme losses
Fat Tails and Black Swan Events
Definition: Extreme market events that occur more frequently than normal distribution suggests
Examples: 1987 crash (-22% in one day), 2008 financial crisis, COVID-19 market volatility
Investment Implication: Need to plan for events beyond 2-3 standard deviation moves
Skewness and Kurtosis
Skewness: Asymmetry in return distribution (negative skew = more frequent large losses)
Kurtosis: “Peakedness” of distribution (high kurtosis = more extreme events)
Portfolio Impact: Traditional diversification may fail during extreme events
Time Horizon and Risk Relationships#
Risk Reduction Over Time (Stocks)
1 Year: 68% probability of returns between -6% and +26% (assuming 10% mean, 16% std dev)
5 Years: Annualized volatility reduces due to averaging effect
20+ Years: Probability of loss approaches zero historically
Caveat: Time diversification debate among academics continues
Sequence of Returns Risk
Definition: Risk that poor returns early in retirement can permanently impair wealth
Example: Two investors with same average returns but different order experience vastly different outcomes
Importance: Timing of returns matters, especially near retirement
Section 3: The Investment Gym - Partner Practice & AI Copilot Learning#
Solo Practice Problems (10-15 minutes)#
Problem 1: Return Calculations Calculate for Apple stock data:
Year 1: $150 → $165, $2 dividend
Year 2: $165 → $140, $2.50 dividend
Year 3: $140 → $180, $3 dividend
Calculate:
Annual returns for each year
Arithmetic mean return
Geometric mean return
Total cumulative return
Problem 2: Risk Measurement Given monthly returns for a fund: 2%, -1%, 4%, -3%, 6%, 1%, -2%, 3%, 0%, 2%
Calculate:
Mean monthly return
Variance and standard deviation
Annualized standard deviation (multiply by √12)
Problem 3: Risk-Adjusted Returns Two portfolios over 5 years:
Portfolio A: 12% return, 18% standard deviation
Portfolio B: 9% return, 12% standard deviation
Risk-free rate: 3%
Calculate Sharpe ratios and determine which portfolio performed better on risk-adjusted basis.
AI Copilot Learning Phase (10-15 minutes)#
🤖 AI Copilot Learning Prompt: “Act as a quantitative analyst and help me understand risk and return measurement in investments. I need to explore: 1) Why is standard deviation the most common risk measure and what are its limitations? 2) How do professionals use historical data to make forward-looking investment decisions? 3) What does it mean when we say ‘stocks are less risky over longer time periods’? Prepare me to explain these concepts clearly to a peer, focusing on both the mathematical foundations and practical implications.”
Student Preparation Task: Work with AI to master these concepts, then prepare to teach:
The mathematical relationship between risk and return
How to interpret standard deviation in practical investment terms
Why time horizon affects risk perception and measurement
Reciprocal Teaching Component (15-20 minutes)#
Structured Roles:
Quantitative Analyst: Explain the statistical concepts and risk measurement methods
Portfolio Manager: Focus on practical applications and investment decision-making
Risk Manager: Challenge assumptions and explore limitations of risk measures
Teaching Requirements: Each student must explain:
Statistical Logic: How do we calculate and interpret standard deviation for investment purposes?
Practical Application: What does a 16% standard deviation mean for a real investor’s experience?
Investment Decision Framework: How should risk measurements influence portfolio allocation decisions?
Peer Teaching Scenario: “Your partner is Sarah trying to respond to Uncle Dave’s argument. Explain how to use historical risk and return data to make a compelling case for stock allocation, including both the statistical evidence and the limitations of this analysis.”
Collaborative Challenge Problem (15-20 minutes)#
The Asset Allocation Debate
Your team analyzes three asset allocation strategies for a 30-year-old investor:
Strategy Profiles:
Conservative: 30% stocks, 70% bonds (Expected: 6% return, 8% volatility)
Moderate: 60% stocks, 40% bonds (Expected: 8% return, 12% volatility)
Aggressive: 90% stocks, 10% bonds (Expected: 9.5% return, 16% volatility)
Challenge Questions:
Calculate expected wealth accumulation over 30 years for $500/month contributions
Estimate the range of outcomes using standard deviation (mean ± 1 std dev)
Discuss the probability of meeting different retirement goals
Consider sequence of returns risk for each strategy
Deliverable: Risk-return analysis with recommendations based on statistical evidence
Robinhood Integration (15 minutes)#
Market Data Analysis:
Historical Performance Research: Look up 5-year performance for:
VTI (Total Stock Market)
BND (Total Bond Market)
Compare volatility and returns
Real-Time Analysis:
Observe daily price movements and calculate simple returns
Note how bond prices react to interest rate changes
Compare volatility between individual stocks and broad market ETFs
Risk Assessment Practice:
Use Robinhood’s charts to estimate recent volatility visually
Compare small-cap vs. large-cap stock price movements
Analyze sector ETF performance differences
Research Task: Find current risk-free rate (3-month Treasury) and calculate approximate Sharpe ratios for major asset classes using recent performance data.
Debrief Discussion (10 minutes)#
Key Insights:
Statistical measurement transforms vague risk concepts into actionable data
Standard deviation provides common language for comparing investments
Time horizon fundamentally changes risk-return trade-offs
Historical data guides expectations but doesn’t guarantee future results
Critical Questions:
How do behavioral biases affect our interpretation of risk statistics?
When might quantitative risk measures mislead investors?
How should sequence of returns risk influence asset allocation decisions?
Section 4: The Investment Coaching - Your DRIVER Learning Guide#
Coaching Scenario: “Settling the Stocks vs. Bonds Debate with Data”#
Sarah needs to respond to Uncle Dave’s challenge using statistical analysis rather than general statements. She will use 20 years of historical data to analyze:
Decision Framework:
Question: Are stocks truly better than bonds for long-term investors?
Approach: Quantitative analysis using historical risk and return data
Data Sources: Historical performance of VTI (stocks) vs. BND (bonds)
Analysis: Calculate returns, risk measures, and risk-adjusted performance
Define & Discover#
🤖 DRIVER Stage 1: Structured Prompt Starters
Step 1 - Context Exploration Prompt: “Act as a quantitative investment analyst and help me explore the context of comparing stocks and bonds statistically. What factors make this comparison complex? What time periods and data sources provide the most reliable analysis? How do professionals approach this fundamental investment question?”
Step 2 - Problem Framing Prompt: “Help me frame Sarah’s stocks vs. bonds analysis systematically: 1) What specific metrics should I calculate to make a compelling case? 2) What time periods and market conditions should I include to ensure robust analysis? 3) What assumptions and limitations should I acknowledge? 4) How should I present this analysis to be both statistically sound and practically useful?”
Step 3 - Verification and Refinement Prompt: “Review my problem framing for the stocks vs. bonds analysis. Is this approach comprehensive and statistically valid? What important considerations might I be missing? How can I make this analysis more robust while keeping it accessible for a beginning investor?”
Problem Framing:
Objective: Provide statistical evidence for long-term asset allocation decisions
Constraints: 20 years of data, focus on broad market indices, acknowledge limitations
Variables: Returns, volatility, correlations, time horizons, market cycles
Success Criteria: Clear, data-driven conclusion with acknowledged uncertainties
Documentation Target: “Comprehensive risk-return analysis that can inform asset allocation decisions with statistical confidence measures and practical implications.”
Represent#
🤖 DRIVER Stage 2: Structured Prompt Starters
Step 1 - Visualization Planning Prompt: “Help me create a logical visual structure for comparing stocks and bonds statistically. I need to map the analysis flow from raw data through statistical calculations to investment conclusions. What visualizations would most effectively communicate risk-return relationships?”
Step 2 - Model Structure Prompt: “Help me design the logical framework for comprehensive risk-return analysis. What are the key steps in analyzing historical performance data? How should I structure the comparison to address both return potential and risk concerns?”
Step 3 - Logic Verification Prompt: “Review my logical structure for stocks vs. bonds statistical analysis. Does this framework capture the key quantitative relationships? What am I missing in terms of statistical rigor or practical application? How can I make this analysis more comprehensive?”
Visual Mapping:
Risk-Return Analysis Framework:
Historical Data Collection
↓
Return Calculations (Annual, Cumulative)
↓
Risk Measurements (Standard Deviation, Max Drawdown)
↓
Risk-Adjusted Performance (Sharpe Ratios)
↓
Time Horizon Analysis (Rolling Returns)
↓
Statistical Conclusions with Confidence Intervals
Logic Documentation:
Risk-Return Analysis Algorithm:
1. Gather historical price and dividend data for VTI and BND
2. Calculate annual returns for each year
3. Compute mean returns, standard deviations, and correlations
4. Calculate risk-adjusted returns (Sharpe ratios)
5. Analyze rolling period returns for different time horizons
6. Test statistical significance of performance differences
7. Identify periods of outperformance and underperformance
8. Draw conclusions with appropriate confidence levels
Implement#
🤖 DRIVER Stage 3: Structured Prompt Starters
Step 1 - Implementation Planning Prompt: “Help me plan the implementation of comprehensive risk-return analysis code. I need to create Python functions that can download historical data, calculate statistical measures, and produce meaningful visualizations. What libraries should I use? What data structure will work best for time series analysis?”
Step 2 - Code Development Prompt: “Help me implement the risk-return analysis code step by step. Start with data acquisition and cleaning, then build functions for return calculations, risk measurements, and performance comparisons. Make sure the code handles missing data and produces professional-quality charts for presentation.”
Step 3 - Code Review and Enhancement Prompt: “Review my risk-return analysis code for both statistical accuracy and practical usability. Are the financial calculations correct? How can I make the code more robust and educational? What additional analysis would strengthen the stocks vs. bonds comparison?”
⚠️ CODE LEARNING NOTE: The following code is intentionally simplified for educational purposes and may contain incomplete logic or potential errors. Your job is to work with your AI copilot to:
Understand each line of code and its statistical purpose
Verify the risk and return calculations against financial theory
Identify any limitations or potential improvements
Test the code with different time periods and data sources
Enhance the code to handle edge cases and provide deeper insights
Remember: Learning comes from analyzing and improving the statistical methodology, not just copying the calculations!
Python Code Example:
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
class RiskReturnAnalyzer:
def __init__(self, start_date='2004-01-01', end_date='2024-01-01'):
self.start_date = start_date
self.end_date = end_date
self.data = {}
self.returns = {}
self.stats = {}
def fetch_data(self, tickers):
"""Download historical price data for analysis"""
print("Fetching historical data...")
for ticker in tickers:
try:
stock = yf.Ticker(ticker)
hist = stock.history(start=self.start_date, end=self.end_date)
self.data[ticker] = hist['Close']
print(f"Successfully fetched {ticker}: {len(hist)} data points")
except Exception as e:
print(f"Error fetching {ticker}: {e}")
# Combine into single DataFrame
self.price_data = pd.DataFrame(self.data)
return self.price_data
def calculate_returns(self):
"""Calculate annual returns for each asset"""
# Resample to annual returns
annual_prices = self.price_data.resample('Y').last()
# Calculate annual returns
for ticker in self.price_data.columns:
annual_returns = annual_prices[ticker].pct_change().dropna()
self.returns[ticker] = annual_returns
self.returns_df = pd.DataFrame(self.returns)
return self.returns_df
def calculate_statistics(self):
"""Calculate comprehensive risk and return statistics"""
for ticker in self.returns.keys():
returns = self.returns[ticker]
# Basic statistics
mean_return = returns.mean()
std_dev = returns.std()
# Risk-adjusted measures (assuming 2% risk-free rate)
risk_free_rate = 0.02
sharpe_ratio = (mean_return - risk_free_rate) / std_dev
# Additional risk measures
max_drawdown = self._calculate_max_drawdown(ticker)
# Store results
self.stats[ticker] = {
'Mean Annual Return': mean_return,
'Standard Deviation': std_dev,
'Sharpe Ratio': sharpe_ratio,
'Max Drawdown': max_drawdown,
'Best Year': returns.max(),
'Worst Year': returns.min()
}
return self.stats
def _calculate_max_drawdown(self, ticker):
"""Calculate maximum drawdown for a given ticker"""
prices = self.data[ticker]
cumulative = (1 + self.price_data[ticker].pct_change()).cumprod()
rolling_max = cumulative.expanding().max()
drawdown = (cumulative - rolling_max) / rolling_max
return drawdown.min()
def compare_assets(self, asset1, asset2):
"""Statistical comparison between two assets"""
returns1 = self.returns[asset1]
returns2 = self.returns[asset2]
# Correlation
correlation = returns1.corr(returns2)
# Performance comparison
comparison = {
'Asset 1': asset1,
'Asset 2': asset2,
'Correlation': correlation,
'Return Difference': self.stats[asset1]['Mean Annual Return'] -
self.stats[asset2]['Mean Annual Return'],
'Risk Difference': self.stats[asset1]['Standard Deviation'] -
self.stats[asset2]['Standard Deviation'],
'Sharpe Difference': self.stats[asset1]['Sharpe Ratio'] -
self.stats[asset2]['Sharpe Ratio']
}
return comparison
def rolling_returns_analysis(self, window_years=5):
"""Analyze rolling period returns"""
rolling_results = {}
for ticker in self.returns.keys():
returns = self.returns[ticker]
rolling_returns = returns.rolling(window=window_years).mean()
rolling_results[ticker] = {
'Rolling Mean': rolling_returns,
'Positive Periods': (rolling_returns > 0).sum(),
'Total Periods': len(rolling_returns.dropna()),
'Success Rate': (rolling_returns > 0).sum() / len(rolling_returns.dropna())
}
return rolling_results
def create_visualizations(self):
"""Generate comprehensive charts for analysis"""
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
# 1. Annual Returns Comparison
axes[0,0].bar(range(len(self.returns['VTI'])), self.returns['VTI'],
alpha=0.7, label='Stocks (VTI)')
axes[0,0].bar(range(len(self.returns['BND'])), self.returns['BND'],
alpha=0.7, label='Bonds (BND)')
axes[0,0].set_title('Annual Returns Comparison')
axes[0,0].set_ylabel('Annual Return')
axes[0,0].legend()
axes[0,0].grid(True, alpha=0.3)
# 2. Risk-Return Scatter
for ticker in self.stats.keys():
axes[0,1].scatter(self.stats[ticker]['Standard Deviation'],
self.stats[ticker]['Mean Annual Return'],
s=100, label=ticker)
axes[0,1].set_xlabel('Risk (Standard Deviation)')
axes[0,1].set_ylabel('Return (Mean Annual)')
axes[0,1].set_title('Risk-Return Profile')
axes[0,1].legend()
axes[0,1].grid(True, alpha=0.3)
# 3. Cumulative Performance
cumulative_vti = (1 + self.returns['VTI']).cumprod()
cumulative_bnd = (1 + self.returns['BND']).cumprod()
axes[1,0].plot(cumulative_vti.index, cumulative_vti, label='Stocks (VTI)', linewidth=2)
axes[1,0].plot(cumulative_bnd.index, cumulative_bnd, label='Bonds (BND)', linewidth=2)
axes[1,0].set_title('Cumulative Performance (\$1 invested)')
axes[1,0].set_ylabel('Cumulative Value')
axes[1,0].legend()
axes[1,0].grid(True, alpha=0.3)
# 4. Return Distribution
axes[1,1].hist(self.returns['VTI'], bins=15, alpha=0.7, label='Stocks (VTI)')
axes[1,1].hist(self.returns['BND'], bins=15, alpha=0.7, label='Bonds (BND)')
axes[1,1].set_title('Return Distribution')
axes[1,1].set_xlabel('Annual Return')
axes[1,1].set_ylabel('Frequency')
axes[1,1].legend()
axes[1,1].grid(True, alpha=0.3)
plt.tight_layout()
return fig
# Example usage and analysis
def run_stocks_vs_bonds_analysis():
"""Complete analysis comparing stocks and bonds"""
# Initialize analyzer
analyzer = RiskReturnAnalyzer(start_date='2004-01-01', end_date='2024-01-01')
# Fetch data for VTI (stocks) and BND (bonds)
tickers = ['VTI', 'BND']
price_data = analyzer.fetch_data(tickers)
# Calculate returns and statistics
returns = analyzer.calculate_returns()
stats = analyzer.calculate_statistics()
# Compare assets
comparison = analyzer.compare_assets('VTI', 'BND')
# Rolling returns analysis
rolling_analysis = analyzer.rolling_returns_analysis(window_years=5)
# Generate visualizations
charts = analyzer.create_visualizations()
# Print comprehensive results
print("\n" + "="*50)
print("STOCKS vs. BONDS: 20-YEAR ANALYSIS RESULTS")
print("="*50)
for ticker in stats.keys():
print(f"\n{ticker} Statistics:")
for metric, value in stats[ticker].items():
if isinstance(value, float):
print(f" {metric}: {value:.3f}")
else:
print(f" {metric}: {value}")
print(f"\nComparison Results:")
for metric, value in comparison.items():
if isinstance(value, float):
print(f" {metric}: {value:.3f}")
else:
print(f" {metric}: {value}")
print(f"\n5-Year Rolling Returns Analysis:")
for ticker in rolling_analysis.keys():
success_rate = rolling_analysis[ticker]['Success Rate']
print(f" {ticker} - Positive 5-year periods: {success_rate:.1%}")
return analyzer, stats, comparison
# Run the analysis
if __name__ == "__main__":
analyzer, results, comparison = run_stocks_vs_bonds_analysis()
plt.show()
Financial Logic Explanation:
Data Collection: Uses actual market data from reliable sources (Yahoo Finance)
Return Calculations: Converts price changes to annual returns for standardized comparison
Risk Measurement: Calculates standard deviation to quantify volatility differences
Risk-Adjusted Performance: Sharpe ratios enable fair comparison accounting for risk differences
Time Analysis: Rolling returns show how performance varies across different market cycles
AI Collaboration: “Help me enhance this risk-return analysis to include: 1) Statistical significance testing for performance differences, 2) Monte Carlo simulation for future projections, 3) Correlation analysis during market stress periods. Focus on making the analysis more robust while maintaining educational clarity.”
Robinhood Integration: “Use Robinhood to verify current performance metrics for VTI and BND. Compare the real-time data with our historical analysis to see if recent performance aligns with long-term patterns.”
Validate#
🤖 DRIVER Stage 4: Structured Prompt Starters
Step 1 - Validation Planning Prompt: “Act as a risk management specialist and help me design comprehensive validation tests for this risk-return analysis. What statistical tests should I run to ensure the conclusions are robust? What are the most important assumptions to verify? How do professionals validate historical performance analysis?”
Step 2 - Testing Strategy Prompt: “Help me create specific validation tests for the stocks vs. bonds analysis. I need to test: 1) Statistical significance of performance differences, 2) Robustness across different time periods, 3) Sensitivity to outlier events, 4) Comparison with academic research. What specific metrics and tests should I use?”
Step 3 - Results Interpretation Prompt: “Help me interpret the validation results for my risk-return analysis. What do the test outcomes tell me about the reliability of my conclusions? What limitations should I acknowledge? How should I communicate the statistical confidence and uncertainty to Sarah?”
Verification Methods:
Statistical Significance Testing: T-tests for return differences, F-tests for variance differences
Robustness Testing: Sub-period analysis (bull markets, bear markets, different decades)
Stress Testing: Performance during major market events (2008, 2020, dot-com crash)
Academic Validation: Comparison with published research on equity risk premium
Out-of-Sample Testing: Test conclusions on different time periods or international markets
Benchmark Comparisons:
# Validation framework
validation_tests = {
'Academic Research': 'Equity risk premium studies (6-8% historically)',
'International Evidence': 'Compare US results with global markets',
'Different Time Periods': 'Test 1980s, 1990s, 2000s, 2010s separately',
'Economic Cycles': 'Performance during recessions vs. expansions',
'Inflation Environments': 'High inflation vs. low inflation periods'
}
Quality Assurance Standards:
All statistical tests reported with confidence intervals
Assumptions clearly stated and tested where possible
Alternative explanations considered and addressed
Limitations acknowledged prominently in conclusions
Evolve#
🤖 DRIVER Stage 5: Structured Prompt Starters
Step 1 - Pattern Recognition Prompt: “Help me identify the core analytical patterns from this risk-return analysis that apply to other investment decisions. What is the fundamental framework we used for statistical comparison? How does this quantitative approach extend to different types of investment evaluation problems?”
Step 2 - Application Extension Prompt: “Now that I understand this risk-return analysis framework, help me identify other investment contexts where this same statistical approach applies. Consider factor investing, international diversification, alternative assets, and market timing strategies. What are the similarities and differences in methodology?”
Step 3 - Integration and Advancement Prompt: “Help me connect this risk-return analysis to more advanced investment concepts. How does this statistical foundation prepare me for portfolio optimization, factor models, and institutional investment strategies? What should I learn next to build on this quantitative foundation?”
Pattern Recognition: This quantitative risk-return framework applies to:
Factor Analysis: Comparing growth vs. value, large vs. small cap performance
International Diversification: Analyzing benefits of global vs. domestic allocation
Alternative Assets: Evaluating REITs, commodities, or private equity risk-return profiles
Manager Selection: Comparing active fund performance vs. passive benchmarks
Market Timing: Testing strategic vs. tactical asset allocation approaches
ESG Investing: Analyzing performance impact of sustainable investment strategies
Forward Connections: “Understanding statistical risk-return analysis is crucial for Session 4’s portfolio optimization, where we’ll use correlation and covariance data to build efficient portfolios that maximize return for given risk levels.”
Reflect#
🤖 DRIVER Stage 6: Structured Prompt Starters
Step 1 - Learning Synthesis Prompt: “Act as a quantitative investment strategist and help me consolidate the key lessons from this risk-return analysis. What fundamental principles about statistical analysis and investment decision-making did we demonstrate? What was most important about moving from intuition to data-driven conclusions? How did this analysis change my understanding of the stocks vs. bonds debate?”
Step 2 - Application Planning Prompt: “Help me identify how I can apply this quantitative risk-return framework to my own investment decisions and future learning. What specific next steps should I take? What other DRIVER applications would strengthen my statistical analysis skills? How does this foundation prepare me for more sophisticated portfolio management?”
Step 3 - Meta-Learning Reflection Prompt: “Help me reflect on my learning process during this quantitative analysis. What aspects of the statistical framework were most valuable? Which concepts were most challenging? How can I improve my analytical thinking and AI collaboration for future investment research problems?”
Synthesis Guidance: Key insights from the stocks vs. bonds analysis:
Data Drives Decisions: Statistical analysis provides objective foundation for subjective investment choices
Risk-Return Trade-off: Higher returns consistently require accepting higher volatility
Time Horizon Matters: Statistical relationships change dramatically across different holding periods
Uncertainty Acknowledgment: Even strong statistical evidence doesn’t guarantee future results
Quantitative Literacy: Modern investing requires comfort with statistical concepts and tools
Next Applications: “Apply this same quantitative framework to analyze the performance of growth vs. value investing strategies, using historical data to determine which approach provides better risk-adjusted returns.”
Section 5: The Investment Game - Financial Detective Work#
Part A: Recognition Scenarios (15 minutes)#
Risk Measurement Challenge: For each scenario, identify the appropriate risk measure and explain your reasoning:
Scenario: Retiree worried about losing money in any given year Risk Measures: Standard deviation, Maximum drawdown, Downside deviation, Value at Risk Question: Which measure best captures this investor’s concern?
Scenario: Comparing two mutual funds with same average returns but different volatility patterns Fund A: Steady 8% annually with occasional 12% years Fund B: Alternates between -2% and +18% annually
Question: How do different risk measures help distinguish these funds?Scenario: Evaluating an emerging markets fund vs. S&P 500 fund Question: What statistical analysis would provide the most comprehensive comparison?
Part B: Full DRIVER Application (30 minutes)#
Case Study: The Factor Tilt Decision
Alex, 35, currently invests in broad market index funds but wonders about “factor tilting” toward small-cap value stocks. Research suggests these stocks historically provide higher returns, but Alex’s financial advisor warns about higher volatility.
Available Options:
Current Portfolio: 100% VTI (Total Stock Market) - 10% annual return, 16% volatility
Proposed Portfolio: 70% VTI + 30% VBR (Small-cap Value) - Estimated 11% return, 20% volatility
Time Horizon: 25 years until retirement
Your Challenge: Apply the complete DRIVER framework to analyze this decision using statistical evidence.
🤖 Assignment Reminder: Work closely with your AI copilot throughout this analysis, using the structured prompts provided for each DRIVER stage.
Required Analysis:
Define & Discover: Frame the factor tilt decision with clear objectives and constraints (use structured prompts)
Represent: Create statistical analysis plan and visualization framework
Implement: Build comprehensive risk-return analysis comparing both portfolios
Validate: Test assumptions and validate results against academic research on factor investing
Evolve: Identify how this analysis applies to other factor-based investment decisions
Reflect: Extract principles for evidence-based portfolio construction
Primary Deliverable: YouTube Video Presentation (8-12 minutes)
Your main assignment is a YouTube video presentation that demonstrates mastery of both financial logic and coding implementation.
Required Video Components:
Financial Analysis Section (4-6 minutes):
Clear explanation of your statistical comparison between the two portfolio approaches
Demonstration of risk-adjusted metrics calculation and interpretation
Time horizon analysis showing probability of different outcomes
Investment recommendation with clear justification based on quantitative evidence
Technical Implementation Section (4-6 minutes):
Step-by-step walkthrough of your Python code for risk-return analysis
Explanation of each major function and why you chose specific approaches
Demonstration of code execution with real data
Discussion of limitations and potential improvements to your implementation
Integration & Conclusion (1-2 minutes):
How the statistical results inform your investment recommendation
What this analysis teaches about factor investing decisions
Connection to broader portfolio construction principles
Video Production Requirements:
Screen recording showing your code execution and results
Clear audio explanation of both financial concepts and technical implementation
Professional presentation suitable for investment industry communication
Upload to YouTube (can be unlisted) and submit link
Written Supplement: AI Collaboration Reflection (200 words) Along with your video, submit a brief written reflection addressing:
Most Valuable Prompt: Which specific AI prompt from this session was most helpful for your learning? Copy the exact prompt and explain why it was effective.
Prompt Improvement: How would you modify or improve that prompt for future use?
Learning Process: How did working with your AI copilot change your understanding of statistical analysis compared to working alone?
Why Video Format? Video presentations provide an excellent opportunity to demonstrate your understanding of both financial concepts and technical implementation. This format allows you to showcase your analytical thinking, communication skills, and ability to integrate theory with practice - all valuable skills for investment professionals.
Section 6: Reflect & Connect - Investment Insights Discussion#
Individual Reflection (5 minutes)#
Reflection Prompts:
How has quantitative analysis changed your confidence in making investment decisions?
What was most challenging about moving from intuitive to statistical thinking about risk?
Which statistical concept will most influence your future investment approach?
Pair Discussion (10 minutes)#
Discussion Questions:
Compare your approaches to the stocks vs. bonds analysis - what statistical evidence was most compelling?
Discuss: “When might quantitative analysis mislead investors or fail to capture important risks?”
Share insights: What surprised you most about the historical risk-return relationships?
Class Synthesis (10 minutes)#
Key Insights to Surface:
Statistical analysis provides objective foundation for investment decisions
Standard deviation offers consistent language for comparing investment risks
Time horizon dramatically affects both risk perception and statistical relationships
Historical data informs expectations but doesn’t guarantee future performance
Modern investing requires quantitative literacy alongside financial knowledge
Forward-Looking Connections: Today’s statistical foundation prepares us for Session 4, where we’ll use correlation and covariance data to optimize portfolio construction and find the most efficient risk-return combinations.
Section 7: Looking Ahead - From Risk Measurement to Portfolio Optimization#
Skills Developed Today#
Applied statistical concepts to real investment data analysis
Calculated and interpreted risk-adjusted return measures
Used Python for comprehensive financial data analysis
Evaluated investment decisions using quantitative evidence
Bridge to Session 4#
Now that we can measure and compare risk-return characteristics of individual assets, Session 4 addresses the crucial question: How do we combine assets to create optimal portfolios?
The Portfolio Optimization Challenge: “I understand that stocks have higher returns but more volatility than bonds. I know my three-fund portfolio provides diversification. But how do I determine the optimal allocation percentages? How can I mathematically find the best balance between risk and return for my specific goals?”
Pattern Evolution Preview#
The statistical tools from today (standard deviation, correlation, Sharpe ratios) become inputs for portfolio optimization models in Session 4. We’ll discover how diversification can mathematically reduce risk without sacrificing returns.
Preparation for Next Session#
Review correlation concepts and how they relate to diversification
Think about this question: “If you could design the perfect portfolio, what would you optimize for?”
Section 8: Appendix - Investment Solutions & Implementation Guide#
Solutions to Practice Problems#
Problem 1: Return Calculations Apple stock analysis:
Year 1: (165-150+2)/150 = 11.33%
Year 2: (140-165+2.5)/165 = -13.64%
Year 3: (180-140+3)/140 = 30.71%
Arithmetic mean: (11.33-13.64+30.71)/3 = 9.47%
Geometric mean: [(1.1133)(0.8636)(1.3071)]^(1/3) - 1 = 7.91%
Total cumulative return: (180 + 2 + 2.5 + 3 - 150) / 150 = 25%
Problem 2: Risk Measurement Monthly returns: 2%, -1%, 4%, -3%, 6%, 1%, -2%, 3%, 0%, 2%
Mean monthly return: 1.2%
Variance: 7.51 percentage points squared
Standard deviation: 2.74% monthly
Annualized standard deviation: 2.74% × √12 = 9.49%
Problem 3: Risk-Adjusted Returns
Portfolio A Sharpe Ratio: (12-3)/18 = 0.50
Portfolio B Sharpe Ratio: (9-3)/12 = 0.50 Both portfolios have identical risk-adjusted performance despite different absolute returns.
Video Presentation Rubric for Session 3#
Financial Explanation (40%)
Excellent: Clear explanation of statistical concepts, risk-return relationships, proper interpretation of Sharpe ratios and standard deviation
Good: Solid understanding of key concepts with minor gaps in statistical interpretation
Needs Work: Basic understanding but unclear explanations or misinterpretation of statistical measures
Inadequate: Fundamental misunderstanding of risk measurement or statistical analysis
Technical Implementation (40%)
Excellent: Working statistical analysis code, proper data handling, accurate calculations, professional visualizations
Good: Mostly functional code with minor issues, clear technical approach to data analysis
Needs Work: Partially working implementation, some errors in statistical calculations
Inadequate: Non-functional code or major errors in statistical methodology
Integration & Communication (20%)
Excellent: Seamless connection between statistical analysis and investment decision-making
Good: Clear connections made between quantitative analysis and practical applications
Needs Work: Some integration but gaps in connecting statistics to investment strategy
Inadequate: No clear integration between statistical concepts and investment practice
Implementation Guide for Instructors#
Statistical Software Setup:
Ensure students have access to Python libraries: pandas, numpy, matplotlib, yfinance
Provide backup data files in case API access fails
Demonstrate proper data validation and error handling techniques
Common Statistical Misconceptions:
Confusion between arithmetic and geometric mean returns
Misinterpretation of standard deviation as absolute risk measure
Assumption that historical relationships will continue unchanged
Over-reliance on Sharpe ratios without considering other factors
AI Collaboration Best Practices:
Encourage students to verify statistical calculations independently
Require documentation of AI assistance in data analysis and interpretation
Emphasize critical evaluation of AI-generated statistical insights
Extension Resources#
Academic References:
Sharpe, W. “The Sharpe Ratio” - Journal of Portfolio Management (1994)
Bodie, Kane, Marcus: “Investments” - Chapters 5-6 (Risk and Return)
Dimson, Marsh, Staunton: “Triumph of the Optimists” (Historical returns analysis)
Statistical Tools and Data Sources:
Yahoo Finance API documentation and limitations
FRED Economic Data for risk-free rates and inflation
Portfolio Visualizer for backtesting and comparison tools
Academic factor data from French Data Library
Professional Applications:
Morningstar’s risk-adjusted return calculations
Institutional portfolio risk measurement standards
Regulatory requirements for investment risk disclosure
Preparation for Session 4#
Key Concepts to Review:
Correlation coefficients and their interpretation
Portfolio return and risk calculations
Mean-variance optimization basics
Data Requirements:
Historical correlation matrices for major asset classes
Efficient frontier calculation methodologies
Asset allocation research and best practices