Python
Python Compound Interest Calculator
Build a compound interest calculator with Python. Visualise how your money grows with different rates, contributions, and time periods.
Getting Started
def compound_interest(principal, rate, years, monthly_contribution=0):
"""Calculate compound interest with optional monthly contributions."""
balance = principal
history = [balance]
for year in range(1, years + 1):
# Add monthly contributions
balance += monthly_contribution * 12
# Apply annual interest
balance *= (1 + rate / 100)
history.append(round(balance, 2))
return balance, history
# Example: £10,000 initial + £500/month at 7% for 30 years
final, history = compound_interest(10000, 7, 30, 500)
print(f"Final balance: £{final:,.2f}")
total_contributed = 10000 + (500 * 12 * 30)
print(f"Total contributed: £{total_contributed:,.2f}")
print(f"Interest earned: £{final - total_contributed:,.2f}")Core Implementation
import matplotlib.pyplot as plt
# Compare different scenarios
scenarios = [
("7% no contributions", compound_interest(10000, 7, 30)[1]),
("7% + £200/month", compound_interest(10000, 7, 30, 200)[1]),
("7% + £500/month", compound_interest(10000, 7, 30, 500)[1]),
("10% + £500/month", compound_interest(10000, 10, 30, 500)[1]),
]
plt.figure(figsize=(12, 6))
for label, data in scenarios:
plt.plot(range(len(data)), [d/1000 for d in data], label=label, linewidth=2)
plt.xlabel("Years")
plt.ylabel("Balance (£k)")
plt.title("Compound Interest: The Power of Time and Contributions")
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig("compound_interest.png", dpi=150)
plt.show()Extended Example
# Interactive version with different compounding frequencies
def compound_with_frequency(principal, annual_rate, years,
monthly_contribution=0, frequency=12):
"""
frequency: 1=annually, 4=quarterly, 12=monthly, 365=daily
"""
balance = principal
periods = years * frequency
period_rate = annual_rate / 100 / frequency
for period in range(periods):
if period % (frequency // 12) == 0 and monthly_contribution > 0:
balance += monthly_contribution
balance *= (1 + period_rate)
return round(balance, 2)
# Compare compounding frequencies
for freq, name in [(1, "Annually"), (4, "Quarterly"), (12, "Monthly"), (365, "Daily")]:
result = compound_with_frequency(10000, 7, 30, 500, freq)
print(f"{name}: £{result:,.2f}")