Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# Re: st: RE: Calculating compound interest using loops?

 From Sara Kimberlin <[email protected]> To [email protected] Subject Re: st: RE: Calculating compound interest using loops? Date Tue, 10 Jul 2012 11:06:28 -0700

```This is exactly what I was looking for - thank you Lance!  And thank
you Steen, too, for your helpful earlier tip.

Sara

On Mon, Jul 9, 2012 at 2:42 PM, Lance Erickson <[email protected]> wrote:
> Hi Sara,
>
> Something like this (below) should give you a more efficient version of the code you had.
>
> Best,
> Lance
>
>
> // create test data
> clear
> input id principal rate payment
> 1 200000 .005 1199.1
> end
>
> // get amount of monthly interest
> local interest = 0
> forvalues i = 1/360 {
>         local j = `i' - 1
>         gen int`i' = (principal - (payment*`j') + `interest') * rate
>         local interest "`interest' + int`i'"
> }
>
> // get amount of yearly interest
> local l = 1
> foreach k of numlist 12(12)360 {
>         local m = `k' - 11
>         egen int_y`l' = rowtotal(int`m'-int`k')
>         local ++l
> }
>
> -----Original Message-----
> From: [email protected] [mailto:[email protected]] On Behalf Of Sara Kimberlin
> Sent: Monday, July 09, 2012 1:23 PM
> To: [email protected]
> Subject: st: Calculating compound interest using loops?
>
> Hello,
>
> I'm trying to calculate annual interest payments on a 30-year loan, with interest compounding monthly, and can't figure out how to write the code efficiently.
>
> Pre-defined variables include principal, rate, and monthly_payment.  I know I can manually calculate the amount of interest for each monthly period like this:
>
> gen interest_month1 = principal * rate
>
> gen interest_month2 = (principal - (monthly_payment * 1) +
> interest_month1) * rate
>
> gen interest_month3 = (principal - (monthly_payment * 2) +
> interest_month1 + interest_month2) * rate
>
> gen interest_month4  = (principal - (monthly_payment * 3) +
> interest_month1 + interest_month2 + interest_month3) * rate
>
> ... and so on through interest_month360.
>
> And then I can manually add up the monthly interest to calculate the annual interest for each year, e.g.:
>
> gen interest_year1 = interest_month1 + interest_month2... + interest_month12
>
> But I think there must be a way to write this much more efficiently using loops, and I haven't been able to figure it out.  I'd appreciate any help.
>
> Thank you,
> Sara
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```