Get startedGet started for free

Simulating periodic payments (II)

You have decided to extend your program from the previous exercise to store the principal and interest payments made at each period, and to plot the results instead of simply printing them.

For this example, the plotting code is already done, so you just need to finish the logic inside the for loop and the initialization of the variables which will be updated at each iteration.

This exercise is part of the course

Introduction to Financial Concepts in Python

View Course

Exercise instructions

  • Simply store the interest_paid and principal_paid for each time period.
  • Calculate the principal_remaining for each time period based on the principal payment and the remaining principal.
  • Run the provided code to plot the monthly Interest vs Principal payments.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Loop through each mortgage payment period
for i in range(0, mortgage_payment_periods):
    
    # Handle the case for the first iteration
    if i == 0:
        previous_principal_remaining = mortgage_loan
    else:
        previous_principal_remaining = principal_remaining[i-1]
        
    # Calculate the interest based on the previous principal
    interest_payment = round(previous_principal_remaining*mortgage_rate_periodic, 2)
    principal_payment = round(periodic_mortgage_payment - interest_payment, 2)
    
    # Catch the case where all principal is paid off in the final period
    if previous_principal_remaining - principal_payment < 0:
        principal_payment = previous_principal_remaining
        
    # Collect the historical values
    interest_paid[i] = ____
    principal_paid[i] = ____
    principal_remaining[i] = ____
    
# Plot the interest vs principal
plt.plot(interest_paid, color="red")
plt.plot(principal_paid, color="blue")
plt.legend(handles=[interest_plot, principal_plot], loc=2)
plt.show()
Edit and Run Code