Compound Interest: The Power of Exponential Growth

30 minbeginner

2. Compound Interest: The Power of Exponential Growth

Compound interest is often called the eighth wonder of the world, and for good reason. It's the mechanism by which money grows exponentially over time, and it's the foundation of wealth accumulation. Understanding compound interest is crucial for understanding how investments grow, how debt accumulates, and how financial markets work.

Simple vs. Compound Interest

Simple Interest is calculated only on the principal amount. If you invest 100at5100 at 5% simple interest for 3 years, you earn \text{\$}5 per year (\text{\$}100 × 5% = \text{\$}5), for a total of \text{\$}15 in interest. After 3 years, you have \text{\$}115.110.25×1.05=110.25 × 1.05 =FV=$1,000×(1.07)30=$7,612.26FV = \text{\$}1{,}000 \times (1.07)^{30} = \text{\$}7{,}612.26

Your $1,000 grows to over $7,600, even though you only earned 7% per year. The power of compounding comes from earning returns on your returns.

Let's visualize the power of compound interest and compare it to simple interest:

Python exercise

#| label: compound-interest
#| fig-cap: "Compound Interest: Exponential Growth Over Time"
#| fig-width: 14
#| fig-height: 8
#| echo: false
#| warning: false

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib, pandas

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display

# Investment parameters
initial_investment = 1000
interest_rate = 0.07  # 7% annual
years = np.arange(0, 41, 1)

# Calculate compound interest
compound_fv = initial_investment * ((1 + interest_rate) ** years)

# Calculate simple interest (linear growth)
simple_fv = initial_investment * (1 + interest_rate * years)

# Create figure
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
fig.suptitle('Compound Interest vs Simple Interest: The Power of Exponential Growth', fontsize=16, fontweight='bold')

# Plot 1: Growth Comparison
ax1 = axes[0, 0]
ax1.plot(years, compound_fv, 'b-', linewidth=3, label='Compound Interest', alpha=0.8)
ax1.plot(years, simple_fv, 'r--', linewidth=2.5, label='Simple Interest', alpha=0.8)
ax1.set_xlabel('Years', fontsize=12, fontweight='bold')
ax1.set_ylabel('Future Value ($)', fontsize=12, fontweight='bold')
ax1.set_title('Compound vs Simple Interest: $1,000 at 7%', fontsize=13, fontweight='bold')
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.legend(loc='upper left', fontsize=10)
ax1.set_ylim(0, 16000)
# Mark 30-year point
ax1.axvline(x=30, color='gray', linestyle=':', linewidth=1.5, alpha=0.5)
ax1.plot(30, compound_fv[30], 'go', markersize=12, markeredgewidth=2, markeredgecolor='darkgreen', zorder=5)
ax1.annotate(f'30 years:\nCompound: ${compound_fv[30]:,.0f}\nSimple: ${simple_fv[30]:,.0f}',
             xy=(30, compound_fv[30]), xytext=(35, 12000),
             arrowprops=dict(arrowstyle='->', color='green', lw=2),
             fontsize=10, fontweight='bold', color='green',
             bbox=dict(boxstyle='round,pad=0.5', facecolor='lightgreen', edgecolor='green', linewidth=2))

# Plot 2: Difference Over Time
ax2 = axes[0, 1]
difference = compound_fv - simple_fv
ax2.fill_between(years, 0, difference, alpha=0.6, color='green', label='Advantage of Compound Interest')
ax2.plot(years, difference, 'g-', linewidth=2.5, alpha=0.8)
ax2.set_xlabel('Years', fontsize=12, fontweight='bold')
ax2.set_ylabel('Difference ($)', fontsize=12, fontweight='bold')
ax2.set_title('Compound Interest Advantage Over Time', fontsize=13, fontweight='bold')
ax2.grid(True, alpha=0.3, linestyle='--')
ax2.legend(loc='upper left', fontsize=10)
ax2.set_ylim(0, 9000)

# Plot 3: Growth Rate Comparison (semi-log scale)
ax3 = axes[1, 0]
ax3.semilogy(years, compound_fv, 'b-', linewidth=3, label='Compound Interest (Exponential)', alpha=0.8)
ax3.plot(years, simple_fv, 'r--', linewidth=2.5, label='Simple Interest (Linear)', alpha=0.8)
ax3.set_xlabel('Years', fontsize=12, fontweight='bold')
ax3.set_ylabel('Future Value ($, Log Scale)', fontsize=12, fontweight='bold')
ax3.set_title('Exponential vs Linear Growth (Log Scale)', fontsize=13, fontweight='bold')
ax3.grid(True, alpha=0.3, linestyle='--', which='both')
ax3.legend(loc='upper left', fontsize=10)

# Plot 4: Effect of Different Interest Rates
ax4 = axes[1, 1]
rates = [0.03, 0.05, 0.07, 0.10, 0.12]
colors_rate = ['blue', 'green', 'orange', 'red', 'purple']
for rate, color in zip(rates, colors_rate):
    fv = initial_investment * ((1 + rate) ** years)
    ax4.plot(years, fv, linewidth=2.5, label=f'{rate*100:.0f}%', color=color, alpha=0.8)
ax4.set_xlabel('Years', fontsize=12, fontweight='bold')
ax4.set_ylabel('Future Value ($)', fontsize=12, fontweight='bold')
ax4.set_title('Compound Interest: Effect of Different Rates', fontsize=13, fontweight='bold')
ax4.grid(True, alpha=0.3, linestyle='--')
ax4.legend(loc='upper left', fontsize=9)
ax4.set_yscale('log')  # Log scale to show exponential growth clearly

plt.tight_layout()
display(fig)
plt.close(fig)

print(f"\n📊 **Compound Interest Analysis**")
print(f"{'='*60}")
print(f"Initial Investment: ${initial_investment:,.2f}")
print(f"Interest Rate: {interest_rate*100:.1f}% per year")
print(f"{'='*60}")
print(f"After 30 Years:")
print(f"  Compound Interest: ${compound_fv[30]:,.2f}")
print(f"  Simple Interest:   ${simple_fv[30]:,.2f}")
print(f"  Difference:        ${difference[30]:,.2f} ({difference[30]/simple_fv[30]*100:.1f}% more)")
print(f"{'='*60}")
print(f"After 40 Years:")
print(f"  Compound Interest: ${compound_fv[40]:,.2f}")
print(f"  Simple Interest:   ${simple_fv[40]:,.2f}")
print(f"  Difference:        ${difference[40]:,.2f} ({difference[40]/simple_fv[40]*100:.1f}% more)")
print(f"{'='*60}")
print(f"✅ Key Insight: Compound interest grows exponentially")
print(f"✅ Small rate differences create huge differences over long periods")
print(f"✅ Time is the most powerful factor in compound interest")

Practice Problem 2.1: Long-Term Stock Investment

You invest

#x27; in math mode at position 3: \\$̲10,000 \cdot (1…" style="color:#cc0000">\\$10,000 \cdot (1 + 0.10)^n\$FV=PV×(1+r)nFV = PV \times (1 + r)^n∗∗After20years∗∗:−**After 20 years**: -FV=$10,000×(1.10)20FV = \text{\$}10{,}000 \times (1.10)^{20}−-FV=$10,000×6.7275=$67,275FV = \text{\$}10{,}000 \times 6.7275 = \text{\$}67{,}275∗∗After30years∗∗:−**After 30 years**: -FV=$10,000×(1.10)30FV = \text{\$}10{,}000 \times (1.10)^{30}−-FV=$10,000×17.4494=$174,494FV = \text{\$}10{,}000 \times 17.4494 = \text{\$}174{,}494∗∗After40years∗∗:−**After 40 years**: -FV=$10,000×(1.10)40FV = \text{\$}10{,}000 \times (1.10)^{40}−-FV=$10,000×45.2593=$452,593FV = \text{\$}10{,}000 \times 45.2593 = \text{\$}452{,}593

Analysis: Notice the exponential growth - the investment doesn't just grow linearly. The difference between 20 and 30 years is $107,219, but the difference between 30 and 40 years is $278,099. Each additional decade creates more growth than the previous one because you're earning returns on a larger base.

Compounding Frequency

The frequency of compounding matters. The formula for compound interest with different compounding frequencies is:

FV=PV×(1+rm)mnFV = PV \times (1 + \frac{r}{m})^{mn}

Where:

  • m = Number of compounding periods per year
  • n = Number of years
  • r = Annual interest rate

Let's visualize how different compounding frequencies affect future value:

Python exercise

#| label: compounding-frequency
#| fig-cap: "Compounding Frequency: FV = PV × (1 + r/m)^(mn) for Different Frequencies"
#| fig-width: 16
#| fig-height: 10
#| echo: false
#| warning: false

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib, pandas

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display

PV = 10000  # $10,000
annual_rate = 0.06  # 6% annual rate
years = np.arange(0, 21, 1)

# Different compounding frequencies
frequencies = {
    'Annual (m=1)': 1,
    'Semiannual (m=2)': 2,
    'Quarterly (m=4)': 4,
    'Monthly (m=12)': 12,
    'Daily (m=365)': 365,
    'Continuous': None  # Special case: e^(rt)
}

# Calculate FV for each frequency
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
fig.suptitle('Compounding Frequency: FV = PV × (1 + r/m)^(mn) - Effect of Compounding Frequency', 
            fontsize=16, fontweight='bold')

# Plot 1: FV Comparison Over Time
ax1 = axes[0, 0]
colors = ['blue', 'green', 'orange', 'red', 'purple', 'brown']
for idx, (label, m) in enumerate(frequencies.items()):
    if m is None:  # Continuous compounding
        fv = PV * np.exp(annual_rate * years)
    else:
        fv = PV * ((1 + annual_rate / m) ** (m * years))
    ax1.plot(years, fv, linewidth=2.5, marker='o', markersize=4, 
            label=label, color=colors[idx], alpha=0.8)

ax1.set_xlabel('Years (n)', fontsize=12, fontweight='bold')
ax1.set_ylabel('Future Value ($)', fontsize=12, fontweight='bold')
ax1.set_title('Future Value at Different Compounding Frequencies (6% Annual Rate)', 
             fontsize=13, fontweight='bold')
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.legend(loc='best', fontsize=9)

# Plot 2: Difference from Annual Compounding
ax2 = axes[0, 1]
fv_annual = PV * ((1 + annual_rate) ** years)
for idx, (label, m) in enumerate(frequencies.items()):
    if m == 1:  # Skip annual (it's the baseline)
        continue
    if m is None:
        fv = PV * np.exp(annual_rate * years)
    else:
        fv = PV * ((1 + annual_rate / m) ** (m * years))
    difference = fv - fv_annual
    ax2.plot(years, difference, linewidth=2.5, marker='s', markersize=4, 
            label=label, color=colors[idx], alpha=0.8)

ax2.axhline(y=0, color='gray', linestyle='--', linewidth=1.5, alpha=0.5)
ax2.set_xlabel('Years (n)', fontsize=12, fontweight='bold')
ax2.set_ylabel('Additional Value vs Annual ($)', fontsize=12, fontweight='bold')
ax2.set_title('Advantage of More Frequent Compounding', fontsize=13, fontweight='bold')
ax2.grid(True, alpha=0.3, linestyle='--')
ax2.legend(loc='best', fontsize=9)

# Plot 3: Effective Annual Rate (EAR)
ax3 = axes[1, 0]
compounding_periods = [1, 2, 4, 12, 365]
effective_rates = []
labels_ear = []
for m in compounding_periods:
    ear = ((1 + annual_rate / m) ** m) - 1
    effective_rates.append(ear * 100)
    labels_ear.append(f'm={m}')

# Add continuous compounding
effective_rates.append((np.exp(annual_rate) - 1) * 100)
labels_ear.append('Continuous')

bars = ax3.bar(range(len(labels_ear)), effective_rates, 
               color=plt.cm.viridis(np.linspace(0, 1, len(labels_ear))), 
               alpha=0.7, edgecolor='black', linewidth=1.5)
ax3.axhline(y=annual_rate * 100, color='red', linestyle='--', linewidth=2, 
           alpha=0.7, label=f'Stated Rate: {annual_rate*100:.1f}%')
ax3.set_xlabel('Compounding Frequency', fontsize=12, fontweight='bold')
ax3.set_ylabel('Effective Annual Rate (%)', fontsize=12, fontweight='bold')
ax3.set_title('Effective Annual Rate (EAR) vs Stated Rate', fontsize=13, fontweight='bold')
ax3.set_xticks(range(len(labels_ear)))
ax3.set_xticklabels(labels_ear, rotation=45, ha='right')
ax3.grid(True, alpha=0.3, linestyle='--', axis='y')
ax3.legend(loc='best', fontsize=9)

# Add value labels
for bar, ear in zip(bars, effective_rates):
    height = bar.get_height()
    ax3.text(bar.get_x() + bar.get_width()/2., height + 0.01,
            f'{ear:.3f}%', ha='center', va='bottom',
            fontsize=9, fontweight='bold')

# Plot 4: FV at 20 Years by Frequency
ax4 = axes[1, 1]
fv_20_years = []
labels_20 = []
for label, m in frequencies.items():
    if m is None:
        fv = PV * np.exp(annual_rate * 20)
    else:
        fv = PV * ((1 + annual_rate / m) ** (m * 20))
    fv_20_years.append(fv)
    labels_20.append(label.split(' (')[0])  # Simplify labels

bars = ax4.bar(range(len(labels_20)), fv_20_years, 
               color=plt.cm.RdYlGn(np.linspace(0.3, 0.9, len(labels_20))), 
               alpha=0.7, edgecolor='black', linewidth=1.5)
ax4.axhline(y=fv_annual[20], color='blue', linestyle='--', linewidth=2, 
           alpha=0.7, label=f'Annual: ${fv_annual[20]:,.0f}')
ax4.set_xlabel('Compounding Frequency', fontsize=12, fontweight='bold')
ax4.set_ylabel('Future Value at 20 Years ($)', fontsize=12, fontweight='bold')
ax4.set_title('Future Value After 20 Years: Effect of Compounding Frequency', 
             fontsize=13, fontweight='bold')
ax4.set_xticks(range(len(labels_20)))
ax4.set_xticklabels(labels_20, rotation=45, ha='right')
ax4.grid(True, alpha=0.3, linestyle='--', axis='y')
ax4.legend(loc='best', fontsize=9)

# Add value labels
for bar, fv in zip(bars, fv_20_years):
    height = bar.get_height()
    ax4.text(bar.get_x() + bar.get_width()/2., height + 500,
            f'${fv:,.0f}', ha='center', va='bottom',
            fontsize=9, fontweight='bold')

plt.tight_layout()
display(fig)
plt.close(fig)

# Calculate and print comparison
print(f"\n📊 **Compounding Frequency Analysis**")
print(f"{'='*70}")
print(f"Formula: FV = PV × (1 + r/m)^(mn)")
print(f"  where m = compounding periods per year")
print(f"        n = number of years")
print(f"        r = annual interest rate")
print(f"{'='*70}")
print(f"Stated Rate: {annual_rate*100:.1f}% per year")
print(f"Initial Investment: ${PV:,}")
print(f"{'='*70}")
print(f"Effective Annual Rates (EAR):")
for m, label in zip([1, 2, 4, 12, 365], ['Annual', 'Semiannual', 'Quarterly', 'Monthly', 'Daily']):
    ear = ((1 + annual_rate / m) ** m) - 1
    print(f"  {label:12s} (m={m:3d}): EAR = {ear*100:.3f}%")
ear_continuous = np.exp(annual_rate) - 1
print(f"  {'Continuous':12s}: EAR = {ear_continuous*100:.3f}%")
print(f"{'='*70}")
print(f"Future Value After 20 Years:")
for label, m in frequencies.items():
    if m is None:
        fv = PV * np.exp(annual_rate * 20)
    else:
        fv = PV * ((1 + annual_rate / m) ** (m * 20))
    advantage = fv - fv_annual[20]
    print(f"  {label.split(' (')[0]:12s}: ${fv:,.2f} (${advantage:+,.2f} vs annual)")
print(f"{'='*70}")
print(f"✅ More frequent compounding → Higher effective rate → Higher FV")
print(f"✅ Continuous compounding: FV = PV × e^(rt) gives maximum growth")
print(f"✅ Difference grows over time and with higher rates")

Python exercise

#| label: practice-2-1
#| fig-cap: "Practice Problem 2.1: Long-Term Stock Investment Growth"
#| fig-width: 14
#| fig-height: 6
#| echo: false
#| warning: false

# Sandbox metadata (auto-generated from lesson.ts)
# libraries: numpy, matplotlib, pandas

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display

# Parameters
pv = 10000
rate = 0.10
years = np.arange(0, 41, 1)
fv_values = pv * ((1 + rate) ** years)

# Key milestone values
fv_20 = pv * ((1 + rate) ** 20)
fv_30 = pv * ((1 + rate) ** 30)
fv_40 = pv * ((1 + rate) ** 40)

fig, axes = plt.subplots(1, 2, figsize=(16, 6))
fig.suptitle('Practice Problem 2.1: Long-Term Stock Investment', fontsize=14, fontweight='bold')

# Plot 1: Growth Over Time
ax1 = axes[0]
ax1.plot(years, fv_values, 'b-', linewidth=3, alpha=0.8)
ax1.plot(20, fv_20, 'go', markersize=12, markeredgewidth=2, markeredgecolor='darkgreen', zorder=5, label=f'20 years: ${fv_20:,.0f}')
ax1.plot(30, fv_30, 'orange', marker='s', markersize=12, markeredgewidth=2, markeredgecolor='darkorange', zorder=5, label=f'30 years: ${fv_30:,.0f}')
ax1.plot(40, fv_40, 'ro', markersize=12, markeredgewidth=2, markeredgecolor='darkred', zorder=5, label=f'40 years: ${fv_40:,.0f}')
ax1.fill_between(years, 0, fv_values, alpha=0.3, color='blue')
ax1.set_xlabel('Years', fontsize=11, fontweight='bold')
ax1.set_ylabel('Investment Value ($)', fontsize=11, fontweight='bold')
ax1.set_title('Investment Growth at 10% Annual Return', fontsize=12, fontweight='bold')
ax1.grid(True, alpha=0.3, linestyle='--')
ax1.legend(loc='upper left', fontsize=9)
ax1.set_yscale('log')

# Plot 2: Milestone Comparison
ax2 = axes[1]
milestones = ['20 Years', '30 Years', '40 Years']
values = [fv_20, fv_30, fv_40]
colors = ['green', 'orange', 'red']
bars = ax2.bar(milestones, values, color=colors, alpha=0.7, edgecolor='black', linewidth=1.5)
ax2.set_ylabel('Future Value ($)', fontsize=11, fontweight='bold')
ax2.set_title('Investment Value at Different Milestones', fontsize=12, fontweight='bold')
ax2.grid(True, alpha=0.3, linestyle='--', axis='y')
for bar, val in zip(bars, values):
    height = bar.get_height()
    ax2.text(bar.get_x() + bar.get_width()/2., height + height*0.02,
             f'${val:,.0f}', ha='center', va='bottom', fontsize=10, fontweight='bold')
# Add growth annotations
ax2.text(0.5, 0.7, f'Growth:\n20→30: +${fv_30-fv_20:,.0f}\n30→40: +${fv_40-fv_30:,.0f}',
         transform=ax2.transAxes, ha='center', fontsize=10,
         bbox=dict(boxstyle='round,pad=0.5', facecolor='yellow', edgecolor='black', linewidth=1.5))

plt.tight_layout()
display(fig)
plt.close(fig)

Real-World Context: This demonstrates why long-term investing is so powerful. A $10,000 investment at age 25 could grow to over $450,000 by age 65, providing a substantial retirement nest egg. This is the principle behind 401(k) plans and other retirement savings vehicles.

Practice Problem 2.2: Credit Card Debt Accumulation

You have a credit card balance of $5,000 with an annual interest rate of 18% (compounded monthly). If you make only the minimum payment of $100 per month, how much will you owe after 2 years? How much interest will you have paid?

Solution:

First, calculate the monthly interest rate:

  • Annual rate = 18% = 0.18
  • Monthlyrate=0.18/12=0.015=1.5%Monthly rate = 0.18 / 12 = 0.015 = 1.5\%

Month-by-month calculation (showing first few months and pattern):

Month 1:

  • Beginning balance: $5,000
  • Interest:
#x27; in math mode at position 3: \\$̲5{,}000 \times …" style="color:#cc0000">\\$5{,}000 \times 0.015 = \\$75
  • New balance:
  • #x27; in math mode at position 3: \\$̲5{,}000 + \\$75…" style="color:#cc0000">\\$5{,}000 + \\$75 = \\$5{,}075
  • Payment: $100
  • Ending balance:
  • #x27; in math mode at position 3: \\$̲5{,}075 - \\$10…" style="color:#cc0000">\\$5{,}075 - \\$100 = \\$4{,}975

    Month 2:

    • Beginning balance: $4,975
    • Interest:
    #x27; in math mode at position 3: \\$̲4{,}975 \times …" style="color:#cc0000">\\$4{,}975 \times 0.015 = \\$74.63
  • New balance:
  • #x27; in math mode at position 3: \\$̲4{,}975 + \\$74…" style="color:#cc0000">\\$4{,}975 + \\$74.63 = \\$5{,}049.63
  • Payment: $100
  • Ending balance:
  • #x27; in math mode at position 3: \\$̲5{,}049.63 - \\…" style="color:#cc0000">\\$5{,}049.63 - \\$100 = \\$4{,}949.63

    After 24 months (using iterative calculation or financial calculator):

    Analysis: After paying $2,400 over 2 years, you've only reduced your debt by $800! The remaining $1,600 went to interest. At this rate, it would take many years to pay off the debt, and you'd pay thousands in interest.

    Python exercise

    #| label: practice-2-2
    #| fig-cap: "Practice Problem 2.2: Credit Card Debt Accumulation"
    #| fig-width: 14
    #| fig-height: 6
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib, pandas
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # Parameters
    initial_balance = 5000
    annual_rate = 0.18
    monthly_rate = annual_rate / 12
    monthly_payment = 100
    months = 24
    
    # Calculate balance over time
    balance = initial_balance
    balances = [balance]
    interest_paid = []
    principal_paid = []
    
    for month in range(months):
        interest = balance * monthly_rate
        principal = monthly_payment - interest
        balance = balance - principal
        balances.append(balance)
        interest_paid.append(interest)
        principal_paid.append(principal)
    
    total_interest = sum(interest_paid)
    total_principal = sum(principal_paid)
    
    fig, axes = plt.subplots(1, 2, figsize=(16, 6))
    fig.suptitle('Practice Problem 2.2: Credit Card Debt Accumulation', fontsize=14, fontweight='bold')
    
    # Plot 1: Balance Over Time
    ax1 = axes[0]
    month_numbers = np.arange(0, months + 1, 1)
    ax1.plot(month_numbers, balances, 'r-', linewidth=3, marker='o', markersize=4, alpha=0.8)
    ax1.axhline(y=initial_balance, color='blue', linestyle='--', linewidth=2, alpha=0.5, label=f'Initial: ${initial_balance:,.0f}')
    ax1.fill_between(month_numbers, 0, balances, alpha=0.3, color='red')
    ax1.set_xlabel('Month', fontsize=11, fontweight='bold')
    ax1.set_ylabel('Balance ($)', fontsize=11, fontweight='bold')
    ax1.set_title(f'Balance Over {months} Months (${monthly_payment}/month payment)', fontsize=12, fontweight='bold')
    ax1.grid(True, alpha=0.3, linestyle='--')
    ax1.legend(loc='upper right', fontsize=9)
    ax1.plot(0, initial_balance, 'bo', markersize=10, zorder=5)
    ax1.plot(months, balances[-1], 'ro', markersize=10, zorder=5)
    
    # Plot 2: Payment Breakdown
    ax2 = axes[1]
    month_indices = np.arange(1, months + 1, 1)
    width = 0.6
    ax2.bar(month_indices, principal_paid, width, label='Principal', color='green', alpha=0.7, edgecolor='black')
    ax2.bar(month_indices, interest_paid, width, bottom=principal_paid, label='Interest', color='red', alpha=0.7, edgecolor='black')
    ax2.axhline(y=monthly_payment, color='blue', linestyle='--', linewidth=2, alpha=0.5, label=f'Monthly Payment: ${monthly_payment}')
    ax2.set_xlabel('Month', fontsize=11, fontweight='bold')
    ax2.set_ylabel('Payment Amount ($)', fontsize=11, fontweight='bold')
    ax2.set_title('Payment Breakdown: Principal vs Interest', fontsize=12, fontweight='bold')
    ax2.grid(True, alpha=0.3, linestyle='--', axis='y')
    ax2.legend(loc='upper right', fontsize=9)
    ax2.set_xticks(range(0, months + 1, 6))
    # Add summary text
    ax2.text(0.5, 0.95, f'Total Paid: ${monthly_payment * months:,.0f}\nPrincipal: ${total_principal:,.0f} | Interest: ${total_interest:,.0f}',
             transform=ax2.transAxes, ha='center', va='top', fontsize=10, fontweight='bold',
             bbox=dict(boxstyle='round,pad=0.5', facecolor='yellow', edgecolor='black', linewidth=1.5))
    
    plt.tight_layout()
    display(fig)
    plt.close(fig)

    Real-World Context: This demonstrates why credit card debt is so dangerous. High interest rates combined with compound interest can trap borrowers in debt. This is why financial advisors recommend paying off high-interest debt before investing - the guaranteed return from avoiding interest often exceeds investment returns.

    Practice Problem 2.3: Certificate of Deposit Comparison

    You have 25,000toinvestandarecomparingtwoCDs:−BankA:5.0−BankB:4.9WhichCDwillgiveyoumoremoneyafter5years?Calculatethedifference.∗∗Solution∗∗:∗∗BankA−AnnualCompounding∗∗:−25,000 to invest and are comparing two CDs: - Bank A: 5.0% annual interest, compounded annually - Bank B: 4.9% annual interest, compounded monthly Which CD will give you more money after 5 years? Calculate the difference. **Solution**: **Bank A - Annual Compounding**: -PV=$25,000PV = \text{\$}25{,}000−-r=5.0%=0.05r = 5.0\% = 0.05−-n=5n = 5years−years -FV=$25,000×(1.05)5FV = \text{\$}25{,}000 \times (1.05)^{5}−-FV=$25,000×1.2763=$31,907.50FV = \text{\$}25{,}000 \times 1.2763 = \text{\$}31{,}907.50∗∗BankB−MonthlyCompounding∗∗:−**Bank B - Monthly Compounding**: -PV=$25,000PV = \text{\$}25{,}000−-r=4.9%=0.049r = 4.9\% = 0.049annual−Monthlyrateannual - Monthly rate=0.049/12=0.004083= 0.049 / 12 = 0.004083−-n=5n = 5years$×12=60years \text{\$}\times 12 = 60months−months -FV=$25,000×(1.004083)60FV = \text{\$}25{,}000 \times (1.004083)^{60}−-FV=$25,000×1.2772=$31,930.00FV = \text{\$}25{,}000 \times 1.2772 = \text{\$}31{,}930.00

    Analysis: Bank B gives slightly more ($31,930 vs $31,907.50), even though it has a lower stated annual rate (4.9% vs 5.0%). This is because monthly compounding allows interest to earn interest more frequently. The difference is $22.50, which demonstrates that compounding frequency can matter, especially for larger amounts and longer periods.

    Python exercise

    #| label: practice-2-3
    #| fig-cap: "Practice Problem 2.3: Certificate of Deposit Comparison"
    #| fig-width: 14
    #| fig-height: 6
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib, pandas
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # Parameters
    pv = 25000
    rate_a = 0.05  # Annual compounding
    rate_b = 0.049  # Monthly compounding
    years = 5
    fv_a = pv * ((1 + rate_a) ** years)
    fv_b = pv * ((1 + rate_b / 12) ** (years * 12))
    
    # Growth over time
    time_points = np.arange(0, years + 0.1, 0.1)
    growth_a = pv * ((1 + rate_a) ** time_points)
    growth_b = pv * ((1 + rate_b / 12) ** (time_points * 12))
    
    fig, axes = plt.subplots(1, 2, figsize=(16, 6))
    fig.suptitle('Practice Problem 2.3: Certificate of Deposit Comparison', fontsize=14, fontweight='bold')
    
    # Plot 1: Growth Comparison
    ax1 = axes[0]
    ax1.plot(time_points, growth_a, 'b-', linewidth=3, label=f'Bank A: {rate_a*100:.1f}% annual', alpha=0.8)
    ax1.plot(time_points, growth_b, 'r--', linewidth=3, label=f'Bank B: {rate_b*100:.1f}% monthly', alpha=0.8)
    ax1.plot(years, fv_a, 'bo', markersize=12, markeredgewidth=2, markeredgecolor='white', zorder=5)
    ax1.plot(years, fv_b, 'ro', markersize=12, markeredgewidth=2, markeredgecolor='white', zorder=5)
    ax1.set_xlabel('Years', fontsize=11, fontweight='bold')
    ax1.set_ylabel('Future Value ($)', fontsize=11, fontweight='bold')
    ax1.set_title('CD Growth Comparison Over 5 Years', fontsize=12, fontweight='bold')
    ax1.grid(True, alpha=0.3, linestyle='--')
    ax1.legend(loc='upper left', fontsize=9)
    ax1.annotate(f'Bank A: ${fv_a:,.2f}', xy=(years, fv_a), xytext=(years+0.3, fv_a + 500),
                 arrowprops=dict(arrowstyle='->', color='blue', lw=1.5), fontsize=9, fontweight='bold')
    ax1.annotate(f'Bank B: ${fv_b:,.2f}', xy=(years, fv_b), xytext=(years+0.3, fv_b - 500),
                 arrowprops=dict(arrowstyle='->', color='red', lw=1.5), fontsize=9, fontweight='bold')
    
    # Plot 2: Final Value Comparison
    ax2 = axes[1]
    banks = ['Bank A\n(5.0% annual)', 'Bank B\n(4.9% monthly)']
    values = [fv_a, fv_b]
    colors = ['blue', 'red']
    bars = ax2.bar(banks, values, color=colors, alpha=0.7, edgecolor='black', linewidth=1.5)
    ax2.axhline(y=fv_a, color='blue', linestyle='--', linewidth=2, alpha=0.5)
    ax2.set_ylabel('Future Value ($)', fontsize=11, fontweight='bold')
    ax2.set_title('Final Value After 5 Years', fontsize=12, fontweight='bold')
    ax2.grid(True, alpha=0.3, linestyle='--', axis='y')
    for bar, val in zip(bars, values):
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height + 200,
                 f'${val:,.2f}', ha='center', va='bottom', fontsize=10, fontweight='bold')
    # Add difference annotation
    diff = fv_b - fv_a
    ax2.text(0.5, 0.7, f'Difference: ${diff:.2f}\nBank B is better by\n${diff:.2f}',
             transform=ax2.transAxes, ha='center', fontsize=10, fontweight='bold',
             bbox=dict(boxstyle='round,pad=0.5', facecolor='yellow', edgecolor='black', linewidth=1.5))
    
    plt.tight_layout()
    display(fig)
    plt.close(fig)

    Real-World Context: This is why it's important to compare effective annual rates (EAR) rather than just stated rates. Banks often advertise higher rates but with less frequent compounding, or lower rates with more frequent compounding. The EAR calculation helps you compare apples to apples.

    Compounding Frequency

    Interest can compound at different frequencies: annually, semiannually, quarterly, monthly, daily, or continuously. The more frequently interest compounds, the faster money grows.

    Annual Compounding: Interest is calculated and added once per year.

    Semiannual Compounding: Interest is calculated and added twice per year. The annual rate is divided by 2, and the number of periods is doubled.

    Monthly Compounding: Interest is calculated and added 12 times per year. The annual rate is divided by 12, and the number of periods is multiplied by 12.

    Continuous Compounding: Interest is calculated and added continuously. The formula becomes:

    FV=PV×ertFV = PV \times e^{rt}

    Where e is the mathematical constant (approximately 2.71828), r is the annual rate, and t is time in years.

    Effective Annual Rate (EAR) is the actual annual rate when compounding occurs more than once per year. The formula is:

    EAR=(1+rm)m−1EAR = (1 + \frac{r}{m})^m - 1

    Where r is the stated annual rate and m is the number of compounding periods per year.

    Example: If a bank offers 6% annual interest compounded monthly:

    The effective rate is higher than the stated rate because of more frequent compounding.

    Python exercise

    #| label: compounding-frequency-visualization
    #| fig-cap: "Compounding Frequency: How Often Interest Compounds Matters"
    #| fig-width: 14
    #| fig-height: 8
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib, pandas
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    import math
    
    # Parameters
    pv = 1000
    annual_rate = 0.06
    years = 10
    
    # Different compounding frequencies
    frequencies = {
        'Annual': 1,
        'Semiannual': 2,
        'Quarterly': 4,
        'Monthly': 12,
        'Daily': 365,
        'Continuous': None  # Special case
    }
    
    # Calculate FV for each frequency
    fv_values = {}
    ear_values = {}
    for name, periods in frequencies.items():
        if periods is None:  # Continuous compounding
            fv = pv * math.exp(annual_rate * years)
            ear = math.exp(annual_rate) - 1
        else:
            fv = pv * (1 + annual_rate / periods) ** (periods * years)
            ear = (1 + annual_rate / periods) ** periods - 1
        fv_values[name] = fv
        ear_values[name] = ear
    
    # Time series for first 10 years
    time_points = np.linspace(0, years, 1000)
    fv_annual = pv * (1 + annual_rate) ** time_points
    fv_monthly = pv * (1 + annual_rate / 12) ** (12 * time_points)
    fv_daily = pv * (1 + annual_rate / 365) ** (365 * time_points)
    fv_continuous = pv * np.exp(annual_rate * time_points)
    
    # Compounding frequency sensitivity
    freq_range = np.array([1, 2, 4, 12, 52, 365, 1000, 10000])
    fv_freq = pv * (1 + annual_rate / freq_range) ** (freq_range * years)
    fv_continuous_val = pv * math.exp(annual_rate * years)
    
    fig, axes = plt.subplots(2, 2, figsize=(16, 12))
    fig.suptitle('Compounding Frequency: How Often Interest Compounds Matters', fontsize=16, fontweight='bold')
    
    # Plot 1: FV Comparison by Frequency
    ax1 = axes[0, 0]
    names_list = list(fv_values.keys())
    fv_list = list(fv_values.values())
    fv_annual_value = fv_values['Annual']  # Get the scalar annual FV value
    colors = ['blue', 'green', 'orange', 'red', 'purple', 'brown']
    bars = ax1.bar(names_list, fv_list, color=colors, alpha=0.7, edgecolor='black', linewidth=1.5)
    ax1.axhline(y=fv_annual_value, color='blue', linestyle='--', linewidth=2, alpha=0.5, label='Annual Baseline')
    ax1.set_ylabel('Future Value ($)', fontsize=12, fontweight='bold')
    ax1.set_title('Future Value: Different Compounding Frequencies', fontsize=13, fontweight='bold')
    ax1.grid(True, alpha=0.3, linestyle='--', axis='y')
    ax1.legend(loc='upper left', fontsize=9)
    for bar, fv in zip(bars, fv_list):
        height = bar.get_height()
        diff = fv - fv_annual_value
        ax1.text(bar.get_x() + bar.get_width()/2., height + 10,
                 f'${fv:,.0f}\n(+${diff:.0f})', ha='center', va='bottom', fontsize=9, fontweight='bold')
    
    # Plot 2: Growth Over Time
    ax2 = axes[0, 1]
    ax2.plot(time_points, fv_annual, 'b-', linewidth=2, label='Annual (1x)', alpha=0.8)
    ax2.plot(time_points, fv_monthly, 'r--', linewidth=2, label='Monthly (12x)', alpha=0.8)
    ax2.plot(time_points, fv_daily, 'g:', linewidth=2, label='Daily (365x)', alpha=0.8)
    ax2.plot(time_points, fv_continuous, 'm-', linewidth=2, label='Continuous', alpha=0.8)
    ax2.set_xlabel('Years', fontsize=12, fontweight='bold')
    ax2.set_ylabel('Future Value ($)', fontsize=12, fontweight='bold')
    ax2.set_title('Growth Over Time: Frequency Impact', fontsize=13, fontweight='bold')
    ax2.grid(True, alpha=0.3, linestyle='--')
    ax2.legend(loc='upper left', fontsize=10)
    ax2.text(0.05, 0.95, f'Initial: ${pv:,.0f}\nRate: {annual_rate*100:.0f}% annually\nPeriod: {years} years',
             transform=ax2.transAxes, ha='left', va='top', fontsize=10, fontweight='bold',
             bbox=dict(boxstyle='round,pad=0.5', facecolor='yellow', edgecolor='black', linewidth=1.5))
    
    # Plot 3: Effective Annual Rate (EAR)
    ax3 = axes[1, 0]
    ear_list = [ear_values[name] * 100 for name in names_list]
    bars2 = ax3.bar(names_list, ear_list, color=colors, alpha=0.7, edgecolor='black', linewidth=1.5)
    ax3.axhline(y=annual_rate * 100, color='blue', linestyle='--', linewidth=2, alpha=0.5, 
                label=f'Stated Rate: {annual_rate*100:.0f}%')
    ax3.set_ylabel('Effective Annual Rate (%)', fontsize=12, fontweight='bold')
    ax3.set_title('Effective Annual Rate: Actual Return', fontsize=13, fontweight='bold')
    ax3.grid(True, alpha=0.3, linestyle='--', axis='y')
    ax3.legend(loc='upper left', fontsize=9)
    for bar, ear in zip(bars2, ear_list):
        height = bar.get_height()
        diff = ear - annual_rate * 100
        ax3.text(bar.get_x() + bar.get_width()/2., height + 0.01,
                 f'{ear:.2f}%\n(+{diff:.2f}%)', ha='center', va='bottom', fontsize=9, fontweight='bold')
    
    # Plot 4: Frequency Sensitivity (Convergence to Continuous)
    ax4 = axes[1, 1]
    freq_labels = ['1\n(Annual)', '2\n(Semi)', '4\n(Quarter)', '12\n(Monthly)', '52\n(Weekly)', 
                   '365\n(Daily)', '1000', '10000']
    ax4.plot(range(len(freq_range)), fv_freq, 'bo-', linewidth=2, markersize=8, alpha=0.8, label='Discrete Compounding')
    ax4.axhline(y=fv_continuous_val, color='red', linestyle='--', linewidth=2, alpha=0.8, 
               label=f'Continuous: ${fv_continuous_val:,.2f}')
    ax4.set_xlabel('Compounding Frequency (times per year)', fontsize=12, fontweight='bold')
    ax4.set_ylabel('Future Value ($)', fontsize=12, fontweight='bold')
    ax4.set_title('Convergence to Continuous Compounding', fontsize=13, fontweight='bold')
    ax4.set_xticks(range(len(freq_range)))
    ax4.set_xticklabels(freq_labels)
    ax4.grid(True, alpha=0.3, linestyle='--')
    ax4.legend(loc='lower right', fontsize=10)
    ax4.text(0.5, 0.95, 'More frequent compounding → Higher FV\nConverges to continuous compounding',
             transform=ax4.transAxes, ha='center', va='top', fontsize=10, fontweight='bold',
             bbox=dict(boxstyle='round,pad=0.5', facecolor='lightblue', edgecolor='blue', linewidth=1.5))
    
    plt.tight_layout()
    display(fig)
    plt.close(fig)

    The Rule of 72

    The Rule of 72 is a quick mental calculation to estimate how long it takes for money to double at a given interest rate:

    Doubling Time: Doubling Time=72r\text{Doubling Time} = \frac{72}{r}

    Where $r$ is the interest rate as a percentage.

    Let's visualize the Rule of 72 and its accuracy:

    Python exercise

    #| label: rule-of-72-enhanced
    #| fig-cap: "Rule of 72: Approximation Accuracy Across Different Rates"
    #| fig-width: 16
    #| fig-height: 10
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib, pandas
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # Interest rates to test (as percentages)
    rates_percent = np.array([2, 3, 4, 5, 6, 7, 8, 10, 12, 15, 20])
    rates_decimal = rates_percent / 100
    
    # Rule of 72 approximation
    doubling_time_approx = 72 / rates_percent
    
    # Exact doubling time: solve (1 + r)^n = 2, so n = log(2) / log(1 + r)
    doubling_time_exact = np.log(2) / np.log(1 + rates_decimal)
    
    # Error in approximation
    error_percent = ((doubling_time_approx - doubling_time_exact) / doubling_time_exact) * 100
    
    # Create figure
    fig, axes = plt.subplots(2, 2, figsize=(16, 12))
    fig.suptitle('Rule of 72: Approximation Accuracy for Doubling Time', 
                fontsize=16, fontweight='bold')
    
    # Plot 1: Doubling Time Comparison
    ax1 = axes[0, 0]
    ax1.plot(rates_percent, doubling_time_exact, 'b-o', linewidth=3, markersize=8, 
            label='Exact: n = log(2) / log(1+r)', alpha=0.8)
    ax1.plot(rates_percent, doubling_time_approx, 'r--s', linewidth=2.5, markersize=8, 
            label='Rule of 72: n = 72 / r', alpha=0.8)
    ax1.set_xlabel('Interest Rate (%)', fontsize=12, fontweight='bold')
    ax1.set_ylabel('Years to Double', fontsize=12, fontweight='bold')
    ax1.set_title('Doubling Time: Rule of 72 vs Exact Calculation', fontsize=13, fontweight='bold')
    ax1.grid(True, alpha=0.3, linestyle='--')
    ax1.legend(loc='best', fontsize=9)
    
    # Add annotations for specific rates
    for i, rate in enumerate([4, 6, 8, 10]):
        idx = np.where(rates_percent == rate)[0][0]
        ax1.annotate(f'{rate}%: {doubling_time_approx[idx]:.1f} yrs\n(actual: {doubling_time_exact[idx]:.2f} yrs)',
                    xy=(rate, doubling_time_exact[idx]), xytext=(rate + 1, doubling_time_exact[idx] + 2),
                    fontsize=9, fontweight='bold',
                    bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.8),
                    arrowprops=dict(arrowstyle='->', color='blue', lw=1.5))
    
    # Plot 2: Approximation Error
    ax2 = axes[0, 1]
    bars = ax2.bar(range(len(rates_percent)), error_percent, 
                   color=plt.cm.RdYlGn_r(np.abs(error_percent) / np.abs(error_percent).max()), 
                   alpha=0.7, edgecolor='black', linewidth=1.5)
    ax2.axhline(y=0, color='black', linestyle='-', linewidth=1.5)
    ax2.set_xlabel('Interest Rate (%)', fontsize=12, fontweight='bold')
    ax2.set_ylabel('Approximation Error (%)', fontsize=12, fontweight='bold')
    ax2.set_title('Rule of 72 Approximation Error', fontsize=13, fontweight='bold')
    ax2.set_xticks(range(len(rates_percent)))
    ax2.set_xticklabels([f'{r:.0f}%' for r in rates_percent], rotation=45, ha='right')
    ax2.grid(True, alpha=0.3, linestyle='--', axis='y')
    
    # Add value labels
    for i, (bar, err) in enumerate(zip(bars, error_percent)):
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height + (0.2 if height > 0 else -0.5),
                f'{err:+.1f}%', ha='center', va='bottom' if height > 0 else 'top',
                fontsize=8, fontweight='bold')
    
    # Plot 3: Growth Visualization - Doubling Examples
    ax3 = axes[1, 0]
    example_rates = [4, 6, 8, 12]
    years_max = 40
    years = np.arange(0, years_max + 1, 1)
    colors_ex = ['blue', 'green', 'orange', 'red']
    
    for rate, color in zip(example_rates, colors_ex):
        doubling_approx = 72 / rate
        growth = 2 ** (years / doubling_approx)  # Simplified: grows by 2x every doubling_approx years
        exact_growth = (1 + rate/100) ** years
        ax3.plot(years, exact_growth, linewidth=2.5, color=color, alpha=0.7, 
                label=f'{rate}% (doubles in ~{doubling_approx:.0f} yrs)')
        # Mark doubling points
        for n in [int(doubling_approx), int(doubling_approx * 2)]:
            if n <= years_max:
                ax3.plot(n, exact_growth[n], 'o', markersize=8, color=color, 
                        markeredgecolor='white', markeredgewidth=1.5, zorder=5)
    
    ax3.axhline(y=2, color='gray', linestyle='--', linewidth=1.5, alpha=0.5, label='2x (doubled)')
    ax3.axhline(y=4, color='gray', linestyle=':', linewidth=1.5, alpha=0.5, label='4x (doubled twice)')
    ax3.set_xlabel('Years', fontsize=12, fontweight='bold')
    ax3.set_ylabel('Growth Factor (Multiplier)', fontsize=12, fontweight='bold')
    ax3.set_title('Growth Visualization: Doubling at Different Rates', fontsize=13, fontweight='bold')
    ax3.grid(True, alpha=0.3, linestyle='--')
    ax3.legend(loc='upper left', fontsize=9)
    ax3.set_yscale('log')
    
    # Plot 4: Rule Variations (72, 69.3, 70)
    ax4 = axes[1, 1]
    rules = {
        'Rule of 72': 72,
        'Rule of 69.3\n(continuous)': 69.3,
        'Rule of 70': 70
    }
    
    rate_range = np.linspace(2, 20, 100)
    exact = np.log(2) / np.log(1 + rate_range/100)
    
    for rule_name, constant in rules.items():
        approx = constant / rate_range
        error = ((approx - exact) / exact) * 100
        ax4.plot(rate_range, np.abs(error), linewidth=2.5, label=rule_name, alpha=0.8)
    
    ax4.set_xlabel('Interest Rate (%)', fontsize=12, fontweight='bold')
    ax4.set_ylabel('Absolute Error (%)', fontsize=12, fontweight='bold')
    ax4.set_title('Comparison of Rule Approximations', fontsize=13, fontweight='bold')
    ax4.grid(True, alpha=0.3, linestyle='--')
    ax4.legend(loc='best', fontsize=9)
    
    plt.tight_layout()
    display(fig)
    plt.close(fig)
    
    print(f"\n📊 **Rule of 72 Analysis**")
    print(f"{'='*70}")
    print(f"Formula: Doubling Time ≈ 72 / r")
    print(f"  where r = interest rate as a percentage")
    print(f"  Exact: n = log(2) / log(1 + r)")
    print(f"{'='*70}")
    print(f"Doubling Time Comparison:")
    print(f"{'Rate':<8} {'Rule of 72':<12} {'Exact':<12} {'Error':<10}")
    print(f"{'-'*70}")
    for i, rate in enumerate(rates_percent):
        print(f"{rate:>5.0f}%   {doubling_time_approx[i]:>8.2f} yrs   {doubling_time_exact[i]:>8.2f} yrs   {error_percent[i]:>+6.2f}%")
    print(f"{'='*70}")
    print(f"Key Insights:")
    print(f"  • Rule of 72 is most accurate for rates around 6-8%")
    print(f"  • Error increases for very low or very high rates")
    print(f"  • Rule of 69.3 (ln(2) × 100) is more accurate for continuous compounding")
    print(f"{'='*70}")
    print(f"✅ Rule of 72 provides quick mental estimates")
    print(f"✅ Most useful for rates between 3% and 15%")
    print(f"✅ Example: At 6%, money doubles in ~12 years (72/6 = 12)")

    Example: At 8% interest, money doubles in approximately 728=9\frac{72}{8} = 9 years.

    This rule is approximate but useful for quick calculations. It works because it's based on the logarithmic relationship in compound interest. The actual formula is:

    n=ln⁡(2)ln⁡(1+r)≈0.693r≈72100rn = \frac{\ln(2)}{\ln(1 + r)} \approx \frac{0.693}{r} \approx \frac{72}{100r}

    For small interest rates, 72/r is a good approximation.

    Python exercise

    #| label: rule-of-72-visualization
    #| fig-cap: "The Rule of 72: Quick Mental Calculation for Doubling Time"
    #| fig-width: 14
    #| fig-height: 8
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib, pandas
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    import math
    
    # Interest rates to test
    rates = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20])
    rates_decimal = rates / 100
    
    # Rule of 72 approximation
    doubling_time_72 = 72 / rates
    
    # Exact calculation
    doubling_time_exact = np.log(2) / np.log(1 + rates_decimal)
    
    # Error percentage
    error_pct = ((doubling_time_72 - doubling_time_exact) / doubling_time_exact) * 100
    
    # Example: $1000 at 8% over time
    pv_example = 1000
    rate_example = 0.08
    years_example = np.linspace(0, 20, 1000)
    fv_example = pv_example * (1 + rate_example) ** years_example
    doubling_time_example = np.log(2) / np.log(1 + rate_example)
    doubling_time_72_example = 72 / (rate_example * 100)
    
    # Multiple rates comparison
    rates_comparison = np.array([3, 6, 9, 12])
    years_comparison = np.linspace(0, 25, 1000)
    pv_comparison = 1000
    
    fig, axes = plt.subplots(2, 2, figsize=(16, 12))
    fig.suptitle('The Rule of 72: Quick Mental Calculation for Doubling Time', fontsize=16, fontweight='bold')
    
    # Plot 1: Rule of 72 vs Exact Calculation
    ax1 = axes[0, 0]
    ax1.plot(rates, doubling_time_72, 'b-', linewidth=3, marker='o', markersize=8, label='Rule of 72 (72/r)', alpha=0.8)
    ax1.plot(rates, doubling_time_exact, 'r--', linewidth=3, marker='s', markersize=8, label='Exact (ln(2)/ln(1+r))', alpha=0.8)
    ax1.set_xlabel('Interest Rate (%)', fontsize=12, fontweight='bold')
    ax1.set_ylabel('Doubling Time (Years)', fontsize=12, fontweight='bold')
    ax1.set_title('Rule of 72: Approximation vs Exact', fontsize=13, fontweight='bold')
    ax1.grid(True, alpha=0.3, linestyle='--')
    ax1.legend(loc='upper right', fontsize=10)
    ax1.text(0.05, 0.95, 'Rule of 72 is a good approximation\nfor typical interest rates',
             transform=ax1.transAxes, ha='left', va='top', fontsize=10, fontweight='bold',
             bbox=dict(boxstyle='round,pad=0.5', facecolor='lightgreen', edgecolor='green', linewidth=1.5))
    
    # Plot 2: Error Analysis
    ax2 = axes[0, 1]
    colors_error = ['green' if abs(err) < 5 else 'orange' if abs(err) < 10 else 'red' for err in error_pct]
    bars = ax2.bar(range(len(rates)), error_pct, color=colors_error, alpha=0.7, edgecolor='black', linewidth=1.5)
    ax2.axhline(y=0, color='black', linestyle='-', linewidth=1)
    ax2.axhline(y=5, color='green', linestyle='--', linewidth=2, alpha=0.5, label='±5% error')
    ax2.axhline(y=-5, color='green', linestyle='--', linewidth=2, alpha=0.5)
    ax2.set_xlabel('Interest Rate (%)', fontsize=12, fontweight='bold')
    ax2.set_ylabel('Approximation Error (%)', fontsize=12, fontweight='bold')
    ax2.set_title('Rule of 72: Accuracy at Different Rates', fontsize=13, fontweight='bold')
    ax2.set_xticks(range(len(rates)))
    ax2.set_xticklabels([f'{r}%' for r in rates])
    ax2.grid(True, alpha=0.3, linestyle='--', axis='y')
    ax2.legend(loc='upper right', fontsize=9)
    for bar, err, rate in zip(bars, error_pct, rates):
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height + (0.5 if height > 0 else -1),
                 f'{err:+.1f}%', ha='center', va='bottom' if height > 0 else 'top', fontsize=8, fontweight='bold')
    
    # Plot 3: Example: Doubling at 8%
    ax3 = axes[1, 0]
    ax3.plot(years_example, fv_example, 'b-', linewidth=3, alpha=0.8, label=f'Investment at {rate_example*100:.0f}%')
    ax3.axhline(y=pv_example * 2, color='red', linestyle='--', linewidth=2, alpha=0.7, label='Double: $2,000')
    ax3.axvline(x=doubling_time_example, color='red', linestyle='--', linewidth=2, alpha=0.7, 
               label=f'Exact: {doubling_time_example:.2f} years')
    ax3.axvline(x=doubling_time_72_example, color='green', linestyle=':', linewidth=2, alpha=0.7, 
               label=f'Rule of 72: {doubling_time_72_example:.1f} years')
    ax3.plot(doubling_time_example, pv_example * 2, 'ro', markersize=12, markeredgewidth=2, markeredgecolor='white', zorder=5)
    ax3.plot(doubling_time_72_example, pv_example * (1 + rate_example) ** doubling_time_72_example, 
             'go', markersize=12, markeredgewidth=2, markeredgecolor='white', zorder=5)
    ax3.set_xlabel('Years', fontsize=12, fontweight='bold')
    ax3.set_ylabel('Future Value ($)', fontsize=12, fontweight='bold')
    ax3.set_title(f'Example: $1,000 at {rate_example*100:.0f}% - When Does It Double?', fontsize=13, fontweight='bold')
    ax3.grid(True, alpha=0.3, linestyle='--')
    ax3.legend(loc='upper left', fontsize=10)
    ax3.text(0.05, 0.95, f'Rule of 72: {doubling_time_72_example:.1f} years\nExact: {doubling_time_example:.2f} years\nError: {abs(doubling_time_72_example - doubling_time_example):.2f} years',
             transform=ax3.transAxes, ha='left', va='top', fontsize=10, fontweight='bold',
             bbox=dict(boxstyle='round,pad=0.5', facecolor='yellow', edgecolor='black', linewidth=1.5))
    
    # Plot 4: Multiple Rates Comparison
    ax4 = axes[1, 1]
    for rate in rates_comparison:
        fv_comp = pv_comparison * (1 + rate/100) ** years_comparison
        doubling_time = 72 / rate
        ax4.plot(years_comparison, fv_comp, linewidth=2, alpha=0.8, 
                label=f'{rate}% (doubles in ~{doubling_time:.0f}yr)')
        ax4.axvline(x=doubling_time, color=ax4.lines[-1].get_color(), linestyle=':', linewidth=1.5, alpha=0.5)
    ax4.axhline(y=pv_comparison * 2, color='red', linestyle='--', linewidth=2, alpha=0.7, label='Double ($2,000)')
    ax4.set_xlabel('Years', fontsize=12, fontweight='bold')
    ax4.set_ylabel('Future Value ($)', fontsize=12, fontweight='bold')
    ax4.set_title('Doubling Time: Different Interest Rates', fontsize=13, fontweight='bold')
    ax4.grid(True, alpha=0.3, linestyle='--')
    ax4.legend(loc='upper left', fontsize=9)
    ax4.text(0.5, 0.95, 'Higher rate → Faster doubling\nRule of 72: Quick mental math',
             transform=ax4.transAxes, ha='center', va='top', fontsize=10, fontweight='bold',
             bbox=dict(boxstyle='round,pad=0.5', facecolor='lightblue', edgecolor='blue', linewidth=1.5))
    
    plt.tight_layout()
    display(fig)
    plt.close(fig)

    Applications of Compound Interest

    Compound interest applies to many financial situations:

    Savings and Investments: When you save money in a bank account or invest in stocks or bonds, your money compounds over time. Understanding compound interest helps you appreciate the value of starting to save early and the cost of waiting.

    Debt: When you borrow money, interest compounds, increasing the amount you owe. Credit card debt, mortgages, and student loans all involve compound interest. Understanding this helps you appreciate the cost of debt and the importance of paying it off.

    Retirement Planning: Retirement planning relies heavily on compound interest. The money you save today compounds over decades, growing to much larger amounts. Understanding compound interest helps you calculate how much you need to save.

    Investment Returns: Investment returns compound over time. A stock that grows 10% per year doesn't just add 10% each year - it compounds. Understanding this helps you appreciate long-term investing.

    Inflation: Inflation compounds over time. If prices rise 3% per year, they don't just add 3% each year - they compound. Understanding this helps you appreciate the long-term effects of inflation.

    Economic Growth: Economic growth compounds. If an economy grows 3% per year, it doesn't just add 3% each year - it compounds. Understanding this helps explain how some countries become wealthy over time.

    The Power of Time

    The most important variable in compound interest is time. The longer the time period, the more powerful compounding becomes. Small differences in returns or time periods create enormous differences in final values over long periods.

    Example: Compare two investors:

    The 10-year head start more than doubles the final value, even though both invested the same amount at the same rate.

    Let's visualize why starting early is so powerful with an enhanced visualization:

    Python exercise

    #| label: early-vs-late-investing-enhanced
    #| fig-cap: "Early vs Late Investing: Enhanced Chart Showing Power of Starting Early with Multiple Scenarios"
    #| fig-width: 16
    #| fig-height: 10
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib, pandas
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # Investment scenarios
    annual_contribution = 5000  # $5,000 per year
    interest_rate = 0.07  # 7% annual return
    
    # Scenario 1: Start at age 25, invest until 65 (40 years)
    age_start_early = 25
    age_end = 65
    years_early = age_end - age_start_early
    years_early_array = np.arange(0, years_early + 1, 1)
    fv_early = np.zeros_like(years_early_array, dtype=float)
    
    for i in range(len(years_early_array)):
        if i == 0:
            fv_early[i] = annual_contribution
        else:
            fv_early[i] = fv_early[i-1] * (1 + interest_rate) + annual_contribution
    
    # Scenario 2: Start at age 35, invest until 65 (30 years)
    age_start_late = 35
    years_late = age_end - age_start_late
    years_late_array = np.arange(0, years_late + 1, 1)
    fv_late = np.zeros_like(years_late_array, dtype=float)
    
    for i in range(len(years_late_array)):
        if i == 0:
            fv_late[i] = annual_contribution
        else:
            fv_late[i] = fv_late[i-1] * (1 + interest_rate) + annual_contribution
    
    # Create figure
    fig, axes = plt.subplots(2, 2, figsize=(16, 12))
    fig.suptitle('Early vs Late Investing: The Power of Starting Early', 
                fontsize=16, fontweight='bold')
    
    # Plot 1: Growth Comparison
    ax1 = axes[0, 0]
    # Align for comparison (show from age 25 to 65)
    age_axis = np.arange(age_start_early, age_end + 1, 1)
    fv_early_aligned = fv_early
    fv_late_aligned = np.concatenate([np.zeros(10), fv_late])  # 10 years of zeros
    
    ax1.plot(age_axis, fv_early_aligned, 'b-', linewidth=3, marker='o', markersize=6, 
            label=f'Start at 25 (40 years)', alpha=0.8)
    ax1.plot(age_axis, fv_late_aligned, 'r--', linewidth=3, marker='s', markersize=6, 
            label=f'Start at 35 (30 years)', alpha=0.8)
    ax1.axvline(x=age_start_late, color='orange', linestyle=':', linewidth=2, alpha=0.7, 
               label='Late Starter Begins')
    ax1.fill_between(age_axis, fv_early_aligned, fv_late_aligned, 
                    where=(fv_early_aligned > fv_late_aligned),
                    alpha=0.3, color='green', label='Advantage of Starting Early')
    ax1.set_xlabel('Age', fontsize=12, fontweight='bold')
    ax1.set_ylabel('Accumulated Value ($)', fontsize=12, fontweight='bold')
    ax1.set_title('Investment Growth: Starting Early vs Late', fontsize=13, fontweight='bold')
    ax1.grid(True, alpha=0.3, linestyle='--')
    ax1.legend(loc='best', fontsize=9)
    
    # Mark final values
    ax1.plot(age_end, fv_early[-1], 'go', markersize=12, markeredgewidth=2, 
            markeredgecolor='darkgreen', zorder=5)
    ax1.plot(age_end, fv_late[-1], 'ro', markersize=12, markeredgewidth=2, 
            markeredgecolor='darkred', zorder=5)
    ax1.annotate(f'Age 65:\nEarly: ${fv_early[-1]:,.0f}\nLate: ${fv_late[-1]:,.0f}\nDifference: ${fv_early[-1]-fv_late[-1]:,.0f}',
                xy=(age_end, fv_early[-1]), xytext=(age_end - 8, fv_early[-1] * 0.7),
                arrowprops=dict(arrowstyle='->', color='green', lw=2),
                fontsize=10, fontweight='bold',
                bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.9))
    
    # Plot 2: Contribution Comparison
    ax2 = axes[0, 1]
    total_contrib_early = annual_contribution * years_early
    total_contrib_late = annual_contribution * years_late
    
    categories = ['Early Starter\n(Age 25-65)', 'Late Starter\n(Age 35-65)']
    contributions = [total_contrib_early, total_contrib_late]
    final_values = [fv_early[-1], fv_late[-1]]
    gains = [fv_early[-1] - total_contrib_early, fv_late[-1] - total_contrib_late]
    
    x = np.arange(len(categories))
    width = 0.35
    
    bars1 = ax2.bar(x - width/2, contributions, width, label='Total Contributions', 
                   color='blue', alpha=0.7, edgecolor='black', linewidth=1.5)
    bars2 = ax2.bar(x + width/2, final_values, width, label='Final Value', 
                   color='green', alpha=0.7, edgecolor='black', linewidth=1.5)
    
    ax2.set_xlabel('Investment Strategy', fontsize=12, fontweight='bold')
    ax2.set_ylabel('Amount ($)', fontsize=12, fontweight='bold')
    ax2.set_title('Contributions vs Final Value: Starting Early vs Late', fontsize=13, fontweight='bold')
    ax2.set_xticks(x)
    ax2.set_xticklabels(categories)
    ax2.legend(loc='best', fontsize=9)
    ax2.grid(True, alpha=0.3, linestyle='--', axis='y')
    
    # Add value labels
    for bars in [bars1, bars2]:
        for bar in bars:
            height = bar.get_height()
            ax2.text(bar.get_x() + bar.get_width()/2., height + height*0.01,
                    f'${height:,.0f}', ha='center', va='bottom',
                    fontsize=9, fontweight='bold')
    
    # Plot 3: Multiple Starting Ages
    ax3 = axes[1, 0]
    starting_ages = [25, 30, 35, 40]
    colors_age = ['blue', 'green', 'orange', 'red']
    for start_age, color in zip(starting_ages, colors_age):
        years_invest = age_end - start_age
        years_array = np.arange(0, years_invest + 1, 1)
        fv = np.zeros_like(years_array, dtype=float)
        
        for i in range(len(years_array)):
            if i == 0:
                fv[i] = annual_contribution
            else:
                fv[i] = fv[i-1] * (1 + interest_rate) + annual_contribution
        
        age_axis_scenario = np.arange(start_age, age_end + 1, 1)
        fv_aligned = np.concatenate([np.zeros(start_age - age_start_early), fv])
        
        ax3.plot(age_axis, fv_aligned, linewidth=2.5, marker='o', markersize=4, 
                label=f'Start at {start_age} (${fv[-1]:,.0f} at 65)', color=color, alpha=0.8)
    
    ax3.set_xlabel('Age', fontsize=12, fontweight='bold')
    ax3.set_ylabel('Accumulated Value ($)', fontsize=12, fontweight='bold')
    ax3.set_title('Multiple Starting Ages: Impact on Final Value', fontsize=13, fontweight='bold')
    ax3.grid(True, alpha=0.3, linestyle='--')
    ax3.legend(loc='best', fontsize=9)
    
    # Plot 4: Return Multiple Comparison
    ax4 = axes[1, 1]
    return_multiple_early = fv_early[-1] / total_contrib_early
    return_multiple_late = fv_late[-1] / total_contrib_late
    
    metrics = ['Total\nContributions', 'Final\nValue', 'Return\nMultiple']
    early_values = [total_contrib_early/1000, fv_early[-1]/1000, return_multiple_early]
    late_values = [total_contrib_late/1000, fv_late[-1]/1000, return_multiple_late]
    
    x = np.arange(len(metrics))
    width = 0.35
    
    bars1 = ax4.bar(x - width/2, early_values, width, label='Early Starter (25)', 
                   color='blue', alpha=0.7, edgecolor='black', linewidth=1.5)
    bars2 = ax4.bar(x + width/2, late_values, width, label='Late Starter (35)', 
                   color='red', alpha=0.7, edgecolor='black', linewidth=1.5)
    
    ax4.set_xlabel('Metric', fontsize=12, fontweight='bold')
    ax4.set_ylabel('Value ($ Thousands or Multiple)', fontsize=12, fontweight='bold')
    ax4.set_title('Comparison: Early vs Late Starter', fontsize=13, fontweight='bold')
    ax4.set_xticks(x)
    ax4.set_xticklabels(metrics)
    ax4.legend(loc='best', fontsize=9)
    ax4.grid(True, alpha=0.3, linestyle='--', axis='y')
    
    # Add value labels
    for i, (bar1, bar2) in enumerate(zip(bars1, bars2)):
        height1 = bar1.get_height()
        height2 = bar2.get_height()
        if i < 2:  # Contributions and Final Value
            ax4.text(bar1.get_x() + bar1.get_width()/2., height1 + height1*0.02,
                    f'${height1:.0f}K', ha='center', va='bottom', fontsize=9, fontweight='bold')
            ax4.text(bar2.get_x() + bar2.get_width()/2., height2 + height2*0.02,
                    f'${height2:.0f}K', ha='center', va='bottom', fontsize=9, fontweight='bold')
        else:  # Return Multiple
            ax4.text(bar1.get_x() + bar1.get_width()/2., height1 + 0.1,
                    f'{height1:.2f}x', ha='center', va='bottom', fontsize=9, fontweight='bold')
            ax4.text(bar2.get_x() + bar2.get_width()/2., height2 + 0.1,
                    f'{height2:.2f}x', ha='center', va='bottom', fontsize=9, fontweight='bold')
    
    plt.tight_layout()
    display(fig)
    plt.close(fig)
    
    print(f"\n📊 **Early vs Late Investing Analysis**")
    print(f"{'='*70}")
    print(f"Scenario: Invest ${annual_contribution:,} per year at {interest_rate*100:.0f}% return")
    print(f"{'='*70}")
    print(f"Early Starter (Age 25-65, 40 years):")
    print(f"  Total Contributions: ${total_contrib_early:,}")
    print(f"  Final Value:         ${fv_early[-1]:,.2f}")
    print(f"  Total Gain:          ${gains[0]:,.2f}")
    print(f"  Return Multiple:     {return_multiple_early:.2f}x")
    print(f"{'='*70}")
    print(f"Late Starter (Age 35-65, 30 years):")
    print(f"  Total Contributions: ${total_contrib_late:,}")
    print(f"  Final Value:         ${fv_late[-1]:,.2f}")
    print(f"  Total Gain:          ${gains[1]:,.2f}")
    print(f"  Return Multiple:     {return_multiple_late:.2f}x")
    print(f"{'='*70}")
    print(f"Advantage of Starting Early:")
    print(f"  Extra Value:         ${fv_early[-1] - fv_late[-1]:,.2f}")
    print(f"  Percentage More:     {((fv_early[-1]/fv_late[-1] - 1)*100):.1f}%")
    print(f"  Extra 10 years of compounding makes huge difference!")
    print(f"{'='*70}")
    print(f"✅ Starting 10 years early more than doubles the final value")
    print(f"✅ Time is the most powerful factor - invest as early as possible")
    print(f"✅ Even with same total contributions, early starter wins significantly")

    Python exercise

    #| label: early-vs-late-investing
    #| fig-cap: "Early vs Late Investing: The Power of Starting Early"
    #| fig-width: 14
    #| fig-height: 8
    #| echo: false
    #| warning: false
    
    # Sandbox metadata (auto-generated from lesson.ts)
    # libraries: numpy, matplotlib, pandas
    
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython.display import display
    
    # Scenario: Investor A starts at 25, Investor B starts at 35
    age_a_start = 25
    age_b_start = 35
    retirement_age = 65
    annual_investment = 5000
    rate = 0.07  # 7% annual return
    
    # Investor A: invests from age 25 to 65 (40 years)
    years_a = np.arange(0, retirement_age - age_a_start + 1, 1)
    fv_a = annual_investment * (((1 + rate) ** years_a - 1) / rate)  # Future value of annuity
    
    # Investor B: invests from age 35 to 65 (30 years)
    years_b = np.arange(0, retirement_age - age_b_start + 1, 1)
    fv_b = annual_investment * (((1 + rate) ** years_b - 1) / rate)
    
    # Also show single $10,000 investment comparison
    single_invest_a = 10000 * ((1 + rate) ** (retirement_age - age_a_start))
    single_invest_b = 10000 * ((1 + rate) ** (retirement_age - age_b_start))
    
    # Create figure
    fig, axes = plt.subplots(2, 2, figsize=(16, 12))
    fig.suptitle('Early vs Late Investing: The Power of Time in Compound Interest', fontsize=16, fontweight='bold')
    
    # Plot 1: Cumulative Growth - Annual Contributions
    ax1 = axes[0, 0]
    age_a = age_a_start + years_a
    age_b = age_b_start + years_b
    ax1.plot(age_a, fv_a, 'b-', linewidth=3, marker='o', markersize=4, label='Investor A (starts at 25)', alpha=0.8)
    ax1.plot(age_b, fv_b, 'r--', linewidth=3, marker='s', markersize=4, label='Investor B (starts at 35)', alpha=0.8)
    ax1.axvline(x=retirement_age, color='green', linestyle=':', linewidth=2, alpha=0.5, label='Retirement (65)')
    ax1.set_xlabel('Age', fontsize=12, fontweight='bold')
    ax1.set_ylabel('Accumulated Value ($)', fontsize=12, fontweight='bold')
    ax1.set_title('Annual $5,000 Contributions: Growth Over Time', fontsize=13, fontweight='bold')
    ax1.grid(True, alpha=0.3, linestyle='--')
    ax1.legend(loc='upper left', fontsize=10)
    # Mark final values
    ax1.plot(retirement_age, fv_a[-1], 'go', markersize=12, markeredgewidth=2, markeredgecolor='darkgreen', zorder=5)
    ax1.plot(retirement_age, fv_b[-1], 'ro', markersize=12, markeredgewidth=2, markeredgecolor='darkred', zorder=5)
    ax1.annotate(f'Investor A: ${fv_a[-1]:,.0f}',
                 xy=(retirement_age, fv_a[-1]), xytext=(retirement_age + 2, fv_a[-1] + 100000),
                 arrowprops=dict(arrowstyle='->', color='blue', lw=2),
                 fontsize=10, fontweight='bold', color='blue',
                 bbox=dict(boxstyle='round,pad=0.5', facecolor='lightblue', edgecolor='blue', linewidth=2))
    ax1.annotate(f'Investor B: ${fv_b[-1]:,.0f}',
                 xy=(retirement_age, fv_b[-1]), xytext=(retirement_age + 2, fv_b[-1] - 200000),
                 arrowprops=dict(arrowstyle='->', color='red', lw=2),
                 fontsize=10, fontweight='bold', color='red',
                 bbox=dict(boxstyle='round,pad=0.5', facecolor='lightcoral', edgecolor='red', linewidth=2))
    
    # Plot 2: Single Investment Comparison
    ax2 = axes[0, 1]
    years_single = np.arange(0, 41, 1)
    fv_single_a = 10000 * ((1 + rate) ** years_single)
    fv_single_b = np.zeros_like(years_single)
    fv_single_b[years_single >= 10] = 10000 * ((1 + rate) ** (years_single[years_single >= 10] - 10))
    
    ax2.plot(age_a_start + years_single, fv_single_a, 'b-', linewidth=3, label='Investor A: $10K at 25', alpha=0.8)
    ax2.plot(age_a_start + years_single, fv_single_b, 'r--', linewidth=3, label='Investor B: $10K at 35', alpha=0.8)
    ax2.axvline(x=age_a_start, color='blue', linestyle=':', linewidth=1.5, alpha=0.5)
    ax2.axvline(x=age_b_start, color='red', linestyle=':', linewidth=1.5, alpha=0.5)
    ax2.set_xlabel('Age', fontsize=12, fontweight='bold')
    ax2.set_ylabel('Future Value ($)', fontsize=12, fontweight='bold')
    ax2.set_title('Single $10,000 Investment: 10-Year Head Start', fontsize=13, fontweight='bold')
    ax2.grid(True, alpha=0.3, linestyle='--')
    ax2.legend(loc='upper left', fontsize=10)
    # Mark final values
    ax2.plot(retirement_age, single_invest_a, 'go', markersize=12, markeredgewidth=2, markeredgecolor='darkgreen', zorder=5)
    ax2.plot(retirement_age, single_invest_b, 'ro', markersize=12, markeredgewidth=2, markeredgecolor='darkred', zorder=5)
    
    # Plot 3: Total Contributions Comparison
    ax3 = axes[1, 0]
    total_contrib_a = annual_investment * len(years_a)
    total_contrib_b = annual_investment * len(years_b)
    categories = ['Total\nContributions', 'Final Value']
    investor_a_values = [total_contrib_a, fv_a[-1]]
    investor_b_values = [total_contrib_b, fv_b[-1]]
    
    x = np.arange(len(categories))
    width = 0.35
    bars1 = ax3.bar(x - width/2, investor_a_values, width, label='Investor A (starts at 25)', 
                    color='blue', alpha=0.7, edgecolor='black', linewidth=1.5)
    bars2 = ax3.bar(x + width/2, investor_b_values, width, label='Investor B (starts at 35)', 
                    color='red', alpha=0.7, edgecolor='black', linewidth=1.5)
    
    ax3.set_xlabel('Metric', fontsize=12, fontweight='bold')
    ax3.set_ylabel('Amount ($)', fontsize=12, fontweight='bold')
    ax3.set_title('Comparison: Contributions vs Final Value', fontsize=13, fontweight='bold')
    ax3.set_xticks(x)
    ax3.set_xticklabels(categories)
    ax3.legend(loc='upper left', fontsize=10)
    ax3.grid(True, alpha=0.3, linestyle='--', axis='y')
    
    # Add value labels
    for bars in [bars1, bars2]:
        for bar in bars:
            height = bar.get_height()
            ax3.text(bar.get_x() + bar.get_width()/2., height + height*0.02,
                     f'${height:,.0f}',
                     ha='center', va='bottom', fontsize=9, fontweight='bold')
    
    # Plot 4: Advantage Over Time
    ax4 = axes[1, 1]
    # Calculate advantage at each age
    common_ages = np.arange(age_b_start, retirement_age + 1, 1)
    advantage = []
    for age in common_ages:
        years_a_at_age = age - age_a_start
        years_b_at_age = age - age_b_start
        if years_b_at_age > 0:
            fv_a_at_age = annual_investment * (((1 + rate) ** years_a_at_age - 1) / rate)
            fv_b_at_age = annual_investment * (((1 + rate) ** years_b_at_age - 1) / rate)
            advantage.append(fv_a_at_age - fv_b_at_age)
        else:
            advantage.append(0)
    
    ax4.fill_between(common_ages, 0, advantage, alpha=0.6, color='green', label='Advantage of Starting Early')
    ax4.plot(common_ages, advantage, 'g-', linewidth=3, alpha=0.8)
    ax4.set_xlabel('Age', fontsize=12, fontweight='bold')
    ax4.set_ylabel('Advantage ($)', fontsize=12, fontweight='bold')
    ax4.set_title('Advantage of Starting Early: Cumulative Benefit', fontsize=13, fontweight='bold')
    ax4.grid(True, alpha=0.3, linestyle='--')
    ax4.legend(loc='upper left', fontsize=10)
    
    plt.tight_layout()
    display(fig)
    plt.close(fig)
    
    print(f"\n📊 **Early vs Late Investing Analysis**")
    print(f"{'='*60}")
    print(f"Scenario: Annual $5,000 investment at 7% return")
    print(f"{'='*60}")
    print(f"Investor A (starts at 25, invests for 40 years):")
    print(f"  Total Contributions: ${total_contrib_a:,.0f}")
    print(f"  Final Value:         ${fv_a[-1]:,.0f}")
    print(f"  Return Multiple:     {fv_a[-1]/total_contrib_a:.2f}x")
    print(f"{'='*60}")
    print(f"Investor B (starts at 35, invests for 30 years):")
    print(f"  Total Contributions: ${total_contrib_b:,.0f}")
    print(f"  Final Value:         ${fv_b[-1]:,.0f}")
    print(f"  Return Multiple:     {fv_b[-1]/total_contrib_b:.2f}x")
    print(f"{'='*60}")
    print(f"Advantage of Starting Early:")
    print(f"  Extra 10 years of compounding: ${fv_a[-1] - fv_b[-1]:,.0f}")
    print(f"  Percentage advantage:         {(fv_a[-1]/fv_b[-1] - 1)*100:.1f}%")
    print(f"{'='*60}")
    print(f"✅ Key Insight: Starting 10 years early more than doubles the final value")
    print(f"✅ Time is the most powerful factor in wealth accumulation")
    print(f"✅ Starting early allows you to invest less and still accumulate more")

    This example illustrates why starting to save early is so important. Time is the most powerful factor in compound interest.


    In Module 4: Mathematics for Finance

    1. Introduction
    2. Time Value of Money: The Foundation of Finance
    3. Compound Interest: The Power of Exponential Growth
    4. Present Value and Future Value: Valuing Money Across Time
    5. Annuities and Perpetuities
    6. Basic Statistics and Probability: Understanding Uncertainty
    7. Financial Ratios and Percentages: Tools for Analysis
    8. Advanced Financial Mathematics
    9. Mathematical Modeling in Finance
    10. End-of-Module Assessment