Skip to content

Instantly share code, notes, and snippets.

@cjanis
Created May 16, 2018 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjanis/1a4f36e443e6d5d5909fbb86820ab3d2 to your computer and use it in GitHub Desktop.
Save cjanis/1a4f36e443e6d5d5909fbb86820ab3d2 to your computer and use it in GitHub Desktop.
A loan calculator that allows for extra principal payments
# given principal and interest rate
# + periods = minimum payment amount and total cost
# + extra payment = periods, total cost, and savings over minimum
import math
def calculate(principal,rate_yearly,periods,extra=0):
# variables
rate_monthly = rate_yearly / 12 / 100
# calculate minimum payment
if rate_monthly > 0:
payment = rate_monthly * principal / (1 - (1 + rate_monthly)**(-periods))
else:
payment = principal / periods
payment = round(payment,2)
# calculate costs at minimum payment
total = payment * periods
interest = total - principal
interest = round(interest,2)
# calculate payment with extra
if extra:
payment_extra = payment + extra
payment_extra = round(payment_extra,2)
# calculate period with extra
if extra:
periods_extra = -(math.log(-(rate_monthly * principal / payment_extra) + 1) / math.log(1 + rate_monthly)) # yes, this uses log, so thank your high school math teacher
periods_extra = round(periods_extra,1)
months_extra = periods - periods_extra
months_extra = round(months_extra,1)
# calculate costs with extra
if extra:
total_extra = payment_extra * periods_extra
interest_extra = total_extra - principal
interest_extra = round(interest_extra,2)
savings_extra = interest - interest_extra
savings_extra = round(savings_extra,2)
# output
print("\n"*3)
print(f"For a loan of ${principal} at a {rate_yearly}% interest rate, your minimum payment will be ${payment} per month for {periods} months, and you'll pay a total ${interest} in interest.")
if extra:
print(f"\nIf you pay ${extra} extra per month, your payments will be ${payment_extra} per month for {periods_extra} months, and you'll pay a total ${interest_extra} in interest. That's ${savings_extra} less and {months_extra} months faster than if you only pay the minimum!")
print("\n"*3)
# run the calculator
calculate(
principal = 100000 - 10000, # the amount of the loan, you can put the total cost minus down payment as well as shown here
rate_yearly = 5, # yearly interest rate out as a percent
periods = 30 * 12, # number of months for repayment, or as shown here, years for repayment times twelve
extra = 1000 # any extra you can pay each month above and beyond the minimum payment
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment