Work the Shell - Calculating Mortgage Rates
I used to work at Hewlett-Packard years ago (pre-Fiorina), and back then, one of our mantras was the “next bench syndrome”. You've probably heard of it: build things that you'd want to use. It's logical, and although often we aren't in that position, it's certainly the basis of many great hobby projects.
It's also the basis for this month's script project. As I write this column, the house I'm in is “under contract” to sell, and I have an offer in on a new place that's four miles away and lots bigger—more room for those servers, natch! You can't talk about buying a house, townhouse, condo or even apartment without talking about getting a loan from a friendly bank—at least, I don't have a spare half-mil burning a hole in my bank account!
When looking at houses, the key question always becomes “how much can I afford?”, and the variables that go into that equation are the amount of your down payment, the duration of the loan, the interest rate the bank is going to charge you and, of course, the base cost of the house you're considering.
There are more factors, including mortgage insurance if your down payment is less than 20% of the house price, taxes, points, closing costs and so on, but we're going to skip those because, well, they're bafflingly complex and way beyond the scope of this column—or magazine!
The basic calculation we need is rather complicated:
M = P [ i((1 + i)**n) ] / [ ((1 + i)**n) - 1]
In this calculation, M is the required monthly payment; n is the total number of monthly payments (on a 30-year mortgage, it's 30 * 12); P is the principal/amount of the loan itself, and i is the annual interest rate divided by 12 for a monthly interest rate.
So, let's say the current mortgage rate at your bank is 5.00% APR. That means i would be 5/12 = 0.42.
How does this convert into a shell script? Surprisingly, it's not too difficult to duplicate the formula if we tap the power of bc and do some intermediate calculations to make it easy to work with and ensure we've no mathematical errors.
The real trick is to make sure we are getting sufficient precision from the calculations, so we don't see egregious rounding errors, which multiply dramatically with this sort of formula.
To accomplish that, each time I call bc, I'll specify scale=6, which gives six post-decimal digits of precision. That means the 5/12 calculation above would be calculated more correctly as 0.426667.
The script starts by having a default duration of 30 years and a default interest rate of 4.85% APR, which is, at the time of this writing, a typical rate. Here's how I encode those:
dfltduration=30 # 30 year loan dfltint=4.85 # 4.85% APR is the default pmts=$(( $dfltduration * 12 ))
The script will expect two variables to be specified, although only one is required, principal and actual interest rate:
princ=$1 ; int=$2
That's a lazy way to assign those variables because, as should be immediately obvious, if they're not specified, we now have empty variables. My general approach to writing scripts is always to start with the core functionality, then graft on all the error tests and friendly errors. I bet you're the same.
This gets a bit tricky because we need to normalize percentages; otherwise, users will assume they're entering 5.25%, and the formula will calculate payments based on 525% (for example, 5.25 not 0.0525). I wrap it all up in one:
if [ -z "$int" ] ; then int="$(echo "scale=6; $dfltint / (100*12)" | bc -q)" else int="$(echo "scale=6; $int / (100*12)" | bc -q)" fi
That's the setup. Now the calculations can be configured as a variable prior to pushing it at bc, for ease of debugging:
calculation="$princ * ( $int * ((1 + $int) ^ $pmts )) / ↪( ((1 + $int) ^ $pmts) - 1)"
Before I go further, let's look at an example. Say I want a loan for a $300,000 house at 4.85% APR for a typical 30-year mortgage. Here's what the above formula actually looks like:
300000 * ( .004041 * ((1 + .004041) ^ 360 )) / ( ((1 + .004041) ^ 360) - 1)
Hopefully, all of those numbers make sense given my explanation so far.
The last step is simply to run the calculation by feeding it to bc:
payment="$(echo "scale=6; $calculation" | bc -q)"
This still is not quite right because the resultant value ends up looking like 1582.859358 / month, which is a bit confusing when we're used to two digits after the decimal point!
I could tweak that within bc, but changing the scale has the bad side effect of reducing the accuracy of all calculations. Instead, here's a simple tweak that I've shown before and like:
payment="$(echo "$payment" | rev | cut -c5- | rev)"
I'll let you figure out what that does.
Finally, the output:
echo Payments: \$$payment/month for $pmts payments to pay off $princ
Let's run a few calculations given this functional script:
$ mortgage-calc.sh 300000 Payments: $1582.85/month for 360 payments to pay off 300000 $ mortgage-calc.sh 300000 7 Payments: $1995.78/month for 360 payments to pay off 300000 $ mortgage-calc.sh 500000 Payments: $2638.09/month for 360 payments to pay off 500000
You can see that even a few points of interest (7% instead of 4.85% makes a dramatic difference in those monthly payments).
Now, to find a really nice house to buy!
Dave Taylor has been hacking shell scripts for a really long time, 30 years. He's the author of the popular Wicked Cool Shell Scripts and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
- Synchronize Your Life with ownCloud
- Days Between Dates?
- A GUI for Your CLI?
- An Introduction to OpenGL Programming
- Tech Tip: Really Simple HTTP Server with Python
- Download "Linux Management with Red Hat Satellite: Measuring Business Impact and ROI"
- RSS Feeds
- The Only Mac I Use
- Ubuntu & SUSE & CentOS, Oh My!
- Returning Values from Bash Functions
Editorial Advisory Panel
Thank you to our 2014 Editorial Advisors!
- Jeff Parent
- Brad Baillio
- Nick Baronian
- Steve Case
- Chadalavada Kalyana
- Caleb Cullen
- Keir Davis
- Michael Eager
- Nick Faltys
- Dennis Frey
- Philip Jacob
- Jay Kruizenga
- Steve Marquez
- Dave McAllister
- Craig Oda
- Mike Roberts
- Chris Stark
- Patrick Swartz
- David Lynch
- Alicia Gibb
- Thomas Quinlan
- Carson McDonald
- Kristen Shoemaker
- Charnell Luchich
- James Walker
- Victor Gregorio
- Hari Boukis
- Brian Conner
- David Lane