human
Give me a the Python code you requested given the following:
I am working on the file "House Investment Return-SF.ipynb".
The first task is:
Checks out.
Calculating the cost of buying is obviously more involved. Let's start with some basic mortgage definitions:
Can you write Python code for it?
assistant
#Here is the Python code you requested.

class Mortgage:
    def __init__(self, down, total, payments, rate):
        self.down, self.total, self.payments, self.rate = down, total, payments, rate
        
    def monthly_payment(self):
        r = self.rate
        P = self.total - self.down
        N = self.payments
        # From https://en.wikipedia.org/wiki/Mortgage_calculator#Monthly_payment_formula
        return (r * P)  / (1 - (1 + r) ** -N)
        
    def remaining(self, t):
        balance = self.total - self.down
        for _ in xrange(0, t):
            interest = balance * self.rate
            balance -= (self.monthly_payment() - interest)
        return max(0, balance)