user17530453
user17530453

Reputation:

fixed rate mortgage in Python

I'm relatively new to coding. I have a task where I have to program an fixed rate mortgage calculator in python. I started by coding this:

import pandas as pd
import numpy_financial as npf
from datetime import date

interest = 0.025
years = 10
payments_year = 12
mortgage = 1500000
start_date = (date(2021, 1, 1))

rng = pd.date_range(start_date, periods=years * payments_year, freq='MS')
rng.name = "Payment Date"
df = pd.DataFrame(index=rng, columns=['Payment', 'Principal Paid', 'Interest Paid', 'Ending Balance'], dtype='float')
df.reset_index(inplace=True)
df.index += 1
df.index.name = "Period"

df["Payment"] = -1 * npf.pmt(interest/12, years*payments_year,mortgage)
df["Interest Paid"] = -1 * npf.ipmt(interest/payments_year, df.index, years*payments_year,mortgage)
df["Principal Paid"] = -1 * npf.ppmt(interest/payments_year, df.index, years*payments_year,mortgage)
df["Ending Balance"] = 0
df.loc[1, "Ending Balance"] = mortgage - df.loc[1, "Principal Paid"]
df = df.round(2)

for period in range(2, len(df)+1):
    previous_balance = df.loc[period-1, "Ending Balance"]
    principal_paid = df.loc[period, "Principal Paid"]
    
    if previous_balance == 0:
        df.loc[period, ['Payment', 'Principal Paid', 'Interest Paid', 'Ending Balance']] == 0
        continue
    elif principal_paid <= previous_balance:
        df.loc[period, "Ending Balance"] = previous_balance - principal_paid
        
print(df)

I have created variables with specific numbers, and as a result got table. I want the calculator itself to come out as a table.

But I also want to use input, so the user can enter the loan amount, interest rate, start date for loan, etc. instead of having a specific variable. Just some simple input like this here:

loan = input("Write the amount you want to loan \n")
loan = float(loan)

start_date = input("What is the starte date, put it in YYYY-MM-DD format")
year, month, day = map(int, start_date.split("-"))
date = datetime.date(year, month, day)

How can I combine the input numbers and still get a table? Appreciate help and tips! :)

Upvotes: 0

Views: 599

Answers (1)

Kamil G&#243;rzyński
Kamil G&#243;rzyński

Reputation: 61

You are doing great, the task is almost done! The code of your calculator can now be placed inside of a function so that the variables can actually take different values.

As you move with your code from draft to a working script, the constants defined on top can now be commented out/removed. They will not conflict with your input data.

import pandas as pd
import numpy_financial as npf
from datetime import date

def fixed_rate_mortgage(interest: float, years: int, payments_year: int, mortgage: int, start_date: str):
  periods = years * payments_year
  df = pd.DataFrame(index=range(1, periods+1))
  df["Date"] = pd.date_range(start_date, periods=periods, freq='MS', name='Payment Date').date
  df["Payment"] = -1 * npf.pmt(interest/12, periods,mortgage)
  df["Interest Paid"] = -1 * npf.ipmt(interest/payments_year, df.index, periods,mortgage)
  df["Principal Paid"] = -1 * npf.ppmt(interest/payments_year, df.index, periods,mortgage)
  df['Ending Balance'] = mortgage - df['Principal Paid'].cumsum()
  df[df['Ending Balance'] < 0] = 0
  total_loan = loan + df['Interest Paid'].sum()
  with pd.option_context(
      'display.max_columns', None,
      'display.float_format', '${:,.2f}'.format):
    print(df)
  print(f"\nTotal of the loan is: ${total_loan:,.2f}.\n")

Now as the logic of the calculator is coded, you can load the variables with an input form. As your project grows, it is important to keep its hierarchy. You call the function, assume that it works and just forget about its implementation.

interest = 0.025
years = 10
payments_year = 12

loan = input("Write the amount you want to loan \n")
loan = float(loan)

start_date = input("What is the starte date, put it in YYYY-MM-DD format")
year, month, day = map(int, start_date.split("-"))
start_date = date(year, month, day)

fixed_rate_mortgage(interest, years, payments_year, loan, start_date)

EDIT: Reformatted the code, added the total loan calculation (asked in the comment).

Upvotes: 1

Related Questions