Monday, October 10, 2011

Mortgage Logic

In the last post we dealt with storing the state of the GUI and loading the grid with data.

Amortizing

The most difficult thing about amortizing the mortgage is figuring out what data is most useful to the user.

In a previous post I listed the values I would like to track.
  • Principal
  • Interest
  • Extra Payments
  • Balance
  • Home Value
  • Tax
  • Insurance
  • Association Dues
  • Maintenance
  • Total Monthly Cost
  • Equity
  • Loan To Value
  • Rental Income
  • Cash Flow
  • Tax Appreciation
  • Insurance Appreciation
  • Association Dues Appreciation
  • Maintenance Appreciation
  • Rent Appreciation
  • Home Value Appreciation

The task was to create a structure to store all of this data, one month at a time. I created MonthIteration with all the variables I would show to the user.

private int _PaymentNum;
public String PaymentNum
{
    get
    {
        return _PaymentNum.ToString();
    }
}
...
private decimal _CashFlow;
public String CashFlow
{
    get
    {
        return _CashFlow.ToString("C2");
    }
}
MonthIteration has public string properties that represent the underlying data. This allows for formatting of the values and feeding the DataGridTextColumns strings instead of something it doesn't know how to process.

We also have a list of static variables. These are not displayed to the user on a month-by-month basis and do not change every month.

//the following varibles do not change ever iteration 
//and are never displayed to the user
private static decimal YearlyMaintenance;
private static decimal YearlyTax;
private static decimal YearlyInsurance;
private static decimal monthlyHoueValueIncrease;
private static decimal monthlyInterestRate;

//The Appreciation values never change and
//we wanted to forgo the double conversion at each iteration
private static decimal HouseValueApp;
private static decimal RentApp;
private static decimal MaintenanceApp;
private static decimal TaxesApp;
private static decimal InsuranceApp;
private static decimal AssociationDuesApp;

//if the check box is not selected we do not
//factor in the amounts into the totals.
private static bool HomeValueShowDef;
private static bool InsuranceShowDef;
private static bool MaintenanceShowDef;
private static bool PropertyTaxShowDef;
private static bool RentShowDef;
private static bool AssociationDuesShowDef;

//cumlative total of all interest payed
private static decimal TotalInterest;
private static decimal BeginingPrincipal;
We have one more static variable that holds all of the MonthIterations created.
private static List<MonthIteration> allIterations;
I wanted a simple class where I passed in as few variables as possible and returned a result without over complicating the class implementation. I created 2 constructors; a public one to load with the initial values and a private one for all consecutive iterations.
//this constructor is used for the first iteration
public MonthIteration(Mortgage inMortgage)
{
    allIterations = new List<MonthIteration>();
    allIterations.Add(this);

    LoadTheMortgageValues(inMortgage);

    //start from payment 1
    _PaymentNum = 1;
    _NumOfPayments = 1;

    //we want to keep track of all interest payed 
    //through the life of the loan
    TotalInterest = 0;

    monthlyHoueValueIncrease = 
        Math.Round(((_HouseValue * HouseValueApp) / 12), 2);

    //The first thing to do is calculate the payment
    _Payment = CalculateMonthlyPayment(inMortgage);
    _Payment = Math.Round(_Payment, 2);


    CalculateThisIteration();
}
        
//all subsequent iterations are called from the 
//previous iteration using this constructor
private MonthIteration(MonthIteration lastIteration)
{
    allIterations.Add(this);

    //load the values from the last iteration
    _PaymentNum = lastIteration._PaymentNum + 1;
    _NumOfPayments++;
    _Balance = lastIteration._Balance;
    _HouseValue = lastIteration._HouseValue;
    _RentCharged = lastIteration._RentCharged;
    _AssociationDues = lastIteration._AssociationDues;

    //_PaymentNum+1 is 1 based so we should update on the 13th payment
    if ((_PaymentNum-1) % 12 == 0)
    {   // = Math.Round(_Payment, 2);
        monthlyHoueValueIncrease = 
            Math.Round(((_HouseValue * HouseValueApp) / 12), 2);
        _RentCharged = Math.Round(_RentCharged * (1 + RentApp), 2);
        YearlyMaintenance = 
            Math.Round(YearlyMaintenance * (1 + MaintenanceApp), 2);
        YearlyTax = Math.Round(YearlyTax * (1 + TaxesApp), 2);
        YearlyInsurance = 
            Math.Round(YearlyInsurance * (1 + InsuranceApp), 2);
        _AssociationDues = 
            Math.Round(_AssociationDues * (1 + AssociationDuesApp), 2);
    }

    CalculateThisIteration();
}
In the Public constructor we pass in the Mortgage object which contains all the user inputted values and copy's them into the local variables in the LoadTheMortgageValues method. We then default some values, find out the monthly payment and calculate this month by calling CalculateThisIteration.

Calculating the monthly mortgage payment is straight forward.
//Loan equation
private decimal CalculateMonthlyPayment(Mortgage inMortgage)
{
    //c = monthly payment
    //r = interest rate
    //n = number or months
    //p = principal

    //c = (r/(1-(1+r)^(-n))) * p

    monthlyInterestRate = inMortgage.InterestRate / 12;
    double onePlusI = 1 + (double)monthlyInterestRate;
    double bottomToBeMinusedFrom = Math.Pow(onePlusI, (-1 * (inMortgage.Term)));
    decimal bottom = (decimal)(1 - bottomToBeMinusedFrom);
    decimal everyThingExceptPrincipal = monthlyInterestRate / bottom;
    decimal thePayment = _Balance * everyThingExceptPrincipal;
    return thePayment;
}
CalculateThisIteration is just book keeping.

//Update the displayed values
private void CalculateThisIteration()
{
    //The basic calculations
    _Interest = Math.Round(monthlyInterestRate * _Balance, 2);
    _Principal = _Payment - _Interest;
    _Balance = _Balance - (_Principal + _ExtraPayment);
    _HouseValue = _HouseValue + monthlyHoueValueIncrease;

    //add the interest payed
    TotalInterest += _Interest;

    //grab the monthly tax, insurance and maintenance
    _Tax = Math.Round(YearlyTax / 12, 2);
    _Insurance = Math.Round(YearlyInsurance / 12, 2);
    _Maintenance = Math.Round(YearlyMaintenance / 12, 2);

    //Investment data points
    _Equity = _HouseValue - _Principal;
    _TotalCost = _Payment + _ExtraPayment;
    if (PropertyTaxShowDef)
        _TotalCost += _Tax;
    if (MaintenanceShowDef)
        _TotalCost += _Maintenance;
    if (InsuranceShowDef)
        _TotalCost += _Insurance;
    if (AssociationDuesShowDef)
        _TotalCost += _AssociationDues;
    _CashFlow = _RentCharged - _TotalCost;

    //we don't want to show an Infinity value by dividing by 0
    if (_HouseValue == 0)
        _LoanToValue = 0;
    else
        _LoanToValue = _Balance / _HouseValue;

    //we have to have at least 1 penny to iterate another month
    if (_Balance <= ((decimal)0.009))
        return;

    MonthIteration mi = new MonthIteration(this);
}
At the end of CalculateThisIteration we now create the next iteration if the balance >= $0.01.

In the next post we are going to be dealing with Threading and Saving Data with LINQ to SQL.


Download the Code Here

No comments:

Post a Comment