Demystify Mortgage Loan By Building a Python Simulator | by Bee Guan Teo | Towards Data Science

A mortgage loan is more than just a monthly repayment based on an agreed amount within a stipulated payment tenure. A mortgage loan can easily jeopardize our finance if without a good understanding of its repayment mechanism and its potential risks.
Here we are going to walk through a step by step practical guide to develop a Python simulator that can simulate mortgage loan repayment in a long term. The simulator will also enable us to visualize the loan amortization and the future growth of our home equity. You might be surprised to see a seemingly slightly higher loan interest rate can affect home equity heavily.
Before starting the development process, we will need to ensure the following libraries are available in our machine:
Streamlit — https://www.streamlit.io/Plotly — https://plotly.com/python/Numpy — https://numpy.org/
Streamlit — https://www.streamlit.io/
Plotly — https://plotly.com/python/
Numpy — https://numpy.org/
If you wish to use my codes to follow the article, you can get the full source codes at my Github Repo.
You may also run my code obtained from my GitHub repo (MortgageSimulator.py) to preview the app. Ensure that you have set up the Streamlit properly in your machine. You may refer to Streamlit website for further information.
Firstly, we import all the required libraries in our program.
Here we are going to start using Streamlit to build our simulator. Streamlit is an open-source Python framework to develop a data app.
Firstly, let us set our page title for our browser tab and the main page.
Line 1: Use page_title inside the Streamlit set_page_config to define a title for our browser tab.
Line 2: Create the main title of our simulator.
At this point, we can try to run the Streamlit app to visualize the output. To do so, we type the following command in our terminal/command prompt.
streamlit run YourPythonFileName.py
(Note: Ensure that you have navigated to your directory where you keep your script file before running the app.)
We should see the output as follows:
In order to simulate mortgage payment, we need four pieces of information and they are home value, down payment percentage, loan interest rate and payment period.
In this section, we will build four numerical input fields using Streamlit to get user input on the four pieces of information stated above.
Line 1: Create a header.
Line 2: Define two columns to place our input fields.
Line 4–9: In the first column, create relevant subheaders and use Streamlit number_input method to create the numerical input fields for home value and interest rate. We set the minimum value to zero and the input format to decimal number.
Line 11–16: In the second column, repeat the similar process above to create relevant subheaders and numerical input fields for the down payment percentage and payment period in years.
With the four pieces of information ready, we can now proceed to calculate the monthly instalments. This will give us a crude idea of our monthly commitment to mortgage repayment.
Line 1–4: Calculate loan amount by deducting the down payment from home value. Multiply payment years by twelves to get the total number of payment months. Convert interest rate to a decimal.
Line 5–6: Based on the input interest rate, we calculate the periodic interest rate using the formula
Periodic interest rate is the annual interest rate expressed over a shorter period (e.g. 1 month). Since the mortgage repayment is on monthly basis, here our aim is to obtain monthly periodic interest and therefore the N=12. At last, use Numpy pmt method to compute the monthly instalment amount based on the periodic interest rate, the total number of payment months, and the loan amount. Numpy pmt method will encapsulate the calculation logic and automatically result in a monthly instalment amount.
Line 8–10: Display down payment, loan amount and the monthly instalment to our simulator.
Let us try to input a sample set of values on those numerical input fields of the mortgage details:
Home Value — 500000
Down Payment Percent — 10
Loan Interest Rate — 4.5
Target Payment Period in years— 30
The simulator processes our sample input and results in a monthly instalment of $2256.02.
At this stage, our simulator is able to estimate a monthly instalment amount based on the input values of the mortgage details given by us. However, the monthly instalment amount alone doesn’t give us an idea about how much of our payment contributed to the loan principal and loan interest, respectively. Although the monthly instalment is the same amount in total for each month, the amount fraction that covers the loan principal and loan interest will differ over time.
In this section, we will generate an amortization schedule for the mortgage loan. The amortization schedule is a table that shows the amount of loan principal and loan interest that comprise each monthly instalment until the loan is totally paid off. Besides, we will also plot a chart to project a visualization of the monthly changes of loan principal and loan interest that comprise our monthly instalments.
Line 4–6: Create three Numpy series to hold the values of the remaining principal, the principal paid and the interest paid every month. Initialize each of the Numpy series with zeros.
Line 8–23: Create a loop to iteratively calculate the principal and interest payments that comprise the current month instalment. The current interest payment is computed based on the multiplication of the periodic interest rate with the previous remaining principal (Line 15). Subtract the resulting interest payment from the monthly instalment will result in the principal payment for that particular month (Line 16). Store the current interest payment, principal payment and the remaining principal to the three Numpy series created earlier (Line 21–23).
Line 31–37: Use the Python Plotly make_subplots method to create a composite figure that entails a table and a chart.
Line 39–49: Use Plotly go.Table object to create a table that shows the monthly principal payment, the interest payment and the remaining principal. Plug in the Numpy series created earlier into the values of the cells (Line 44–46). Use add_trace method to add the table into the composite figure object.
Line 51–58: Use Plotly go.Scatter object to create a line plot for the principal payment over months. Set the Numpy series of principal payment as the y-axis value. Use the add_trace method again to add the plot to the composite figure object.
Line 60–67: In a similar way, use Plotly go.Scatter object to create a line plot for the interest payment over months. For this time, we use append_trace method to add the line plot so that it will be overlaid with the line plot for the principal payment in the same chart.
Line 69–81: Configure the layout for the composite figure by setting the relevant title, dimension and legends.
Line 83: Use Streamlit plotly_chart method to render the composite figure.
From the amortization table and the line plots above, we can observe the majority of our monthly instalment is used to cover the loan interest at the early stage of our payment schedule. Only a small fraction of our instalment contribute to the principal payment in the first few years.
However, this trend is changed over time. Since the interest payment is calculated based on the periodic interest rate of the previous remaining principal, a consistent repayment will result in a steady decrease of the interest payment from one month to another month. At the later stage of the amortization schedule, we will find the majority of the monthly instalment is used to cover our loan principal.
A consistent repayment of the mortgage loan does not only reduce our interest payment from time to time but also keep increasing our home equity. Basically, home equity is the portion of a home’s current value that we actually possess at any given time.
Let’s say we purchase a property at a $500,000 market price and our down payment is 10%. This means our initial home equity is equivalent to our down payment which is $50,000. When we start our mortgage repayment, our home equity will be accumulated whenever an instalment is made. For example, if we have made three months instalment which covers a total of $2700 cumulative principal payment, our latest home equity is $50,000 + $2700 = $52700.
By presuming the market value of the house remains constant throughout our repayment period, our home equity will be equivalent to the $500,000 market price at the end of our mortgage tenure.
Let us add a plot to our simulator to show a clearer picture.
Line 4–5: Use Numpy cumsum method to obtain the cumulative sum of the principal payment and the interest payment series. The cumulative sum of the principal payment is equivalent to cumulative home equity (presuming that the market value of the property remains unchanged).
Line 7: Create a Plotly Fig object to show the line plots.
Line 8–14: Use Plotly go.Scatter object to create a line plot to show cumulative home equity over months. Use add_trace method to add the line plot to the fig object.
Line 16–22: In a similar way, use Plotly go.Scatter object to create another line plot to show the cumulative interest paid over months and add it to the fig object.
Line 24–36: Configure the layout by setting the title name, x-axis & y-axis title, dimension and legends of the chart figure.
From the line chart above, we can see our cumulative home equity keep increasing from month to month until it reaches its peak at the end of the repayment period. Besides, we can also observe that our cumulative home equity will only overtake cumulative interest payment roughly after Month-314 (approaching the end of the repayment period).
Let’s say if we adjust our loan annual interest rate in our simulator and lower it from 4.5 to 4. Once a value is changed, our plot will be updated automatically as below.
With a 0.5% lower annual interest rate, we can observe that the final cumulative interest paid is reduced significantly. Our cumulative home equity will overtake the cumulative interest roughly after Month-278. This is the reason we always look for a financial institution that can offer us the best interest rate for our mortgage.
Now, what if we adjust our payment period from 30 years to 25 years? Let see how will it affect our cumulative home equity over time.
With a shorter loan repayment tenure, the cumulative interest paid is reduced drastically. Our cumulative home equity will be higher than the cumulative interest paid roughly right after the midterm of our mortgage tenure. This shows that while we can pay for a lower monthly instalment with a longer tenure, we bear a hefty cost of interest in the long run. There should be a balance in controlling our current financial commitment and the profit in the longer term.
At last, let us add a growth forecast feature to our mortgage simulator. In the previous section, the evolvement of our home equity is solely based on our principal payment through the entire loan tenure without considering the growth of the home market value.
What will happen to our home equity if the market value of our home has been changed from year to year (which always happen). This is important to note that the growth is not necessarily positive. There can be negative growth as well.
Here we add another input field to get user input on the forecast growth rate in our simulator and also create a line chart to show the forecast home value and forecast home equity over time.
Line 4–5: Create a relevant subheader and a new numerical input field for the home market value growth rate per year.
Line 7–8: Convert the annual forecast growth rate into monthly growth. Create a growth array and populate it with the monthly growth rate using Numpy full method.
Line 9–10: Use Numpy cumprod method to compute the cumulative product of the growth rate over the months. Multiply the resulting cumulative growth with the original home value. This will result in a forecast home value series.
Line 11–12: Compute the cumulative percentage of home ownership over the months. Multiply this cumulative percentage with the forecast home value series and this will result in a forecast home equity series.
Line 14–51: Repeat the similar step presented in the earlier section to create the line plots to show the forecast home value over the months, forecast home equity over the months and the principal remaining over the months. The three line plots are added to the same chart figure using the Plotly add_trace method. Configure the chart figure layout by setting a relevant title, x-axis & y-axis title, dimension and legends.
Line 53: Render the chart figure.
By setting a 3% growth rate per year, we will see our home market value will be doubled after 300 months (25 years). While we are still serving our mortgage with the same monthly instalment, our home equity has exceeded the original home value ($500,000) after 202 months. At the end of our repayment period, our home equity is equivalent to the forecast home value which is 200% of the original home value. Such increment of home equity can provide us with a chance to apply for a home equity loan that can convert our equity into cash.
Now, let try to tweak the growth rate again with a negative value, -5 and see how it affects our home equity over the times.
From the line plots above, we can observe that the home value is heavily depreciated to around 30% of the original market value after 300 months (25 years). This also means our home equity will also be depreciated as well at the end of our mortgage tenure. We suffer a great loss from a depreciated property.
Besides, there is quite a long period of time (around Month-57 to Month-169), our home value falls under the remaining principal amount. Such a situation is known as an underwater mortgage. During this period, we will not have any equity available for credit and may even prevent us from selling the home unless we have sufficient cash to pay the loss. Underwater mortgages were a common problem during the Financial Crisis of 2008.
Home investment can be very rewarding but it is a long term process which is full of risk. It requires careful market analysis and good self-control in our own financial planning. Hopefully, the Python simulator presented here will give you some vivid ideas about mortgage loan. Any investment would never be a random guess activity but will require some solid projection of future scenario which will help us to make a more decent decision.
I wish you enjoy reading this article.