You’re on the list. We’ll email you when your intake opens.
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
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:
#x27; in math mode at position 3: \\$̲10,000 \cdot (1…" style="color:#cc0000">\\$10,000 \cdot (1 + 0.10)^n\$
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:
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")
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
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):
Ending balance ≈ $4,200
Total payments made: #x27; in math mode at position 3: \\$̲100 \times 24 =…" style="color:#cc0000">\\$100 \times 24 = \\$2{,}400
Principal paid: #x27; in math mode at position 3: \\$̲5{,}000 - \\$4{…" style="color:#cc0000">\\$5{,}000 - \\$4{,}200 = \\$800
Interest paid: #x27; in math mode at position 3: \\$̲2{,}400 - \\$80…" style="color:#cc0000">\\$2{,}400 - \\$800 = \\$1{,}600
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.
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
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.
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:
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:
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.
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:
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 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:
For small interest rates, 72/r is a good approximation.
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:
Investor A: Invests
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.