TheDeveloperBlog.com


C# Compound Interest

Compound interest. With compound interest, money makes money. Compound interest is determined with a formula. We input our principal amount, the interest rate, the number of times interest is compounded each year, and the number of years.


Example. Let's look at DePaul University's interest formula explanation. We compute the total amount of money after $1,500 is deposited. The bank pays an interest rate of 4.3%, compounded quarterly. It is left in the account for six years.

Compound Interest Formula

Quarterly: When interest is compounded quarterly, we pass 4 to the method. When interest is compounded monthly, we pass 12.

C# program that computes compound interest

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine(CompoundInterest(1500, 0.043, 4, 6));
    }

    /// <summary>
    /// CompoundInterest.
    /// </summary>
    static double CompoundInterest(double principal,
	double interestRate,
	int timesPerYear,
	double years)
    {
	// (1 + r/n)
	double body = 1 + (interestRate / timesPerYear);

	// nt
	double exponent = timesPerYear * years;

	// P(1 + r/n)^nt
	return principal * Math.Pow(body, exponent);
    }
}

Output

1938.83682213411

We find that the $1,500 amount has grown to $1938.84 after the six years. This result is the same as that from the example page at DePaul University, so we can guess it is correct.

Note: Financial formula are a good application of programming languages. Many formulae are possible, but compound interest is a fine start.


Frequency. Next, we look more carefully at how the frequency of compounding affects the total value of the investment. On Wikipedia we see that there is a significant difference between yearly, monthly and quarterly frequencies.

Compound interest: Wikipedia
Statements that change frequency: C#

Console.WriteLine(CompoundInterest(1000, 0.2, 1, 10));
Console.WriteLine(CompoundInterest(1000, 0.2, 4, 10));
Console.WriteLine(CompoundInterest(1000, 0.2, 12, 10));

Output

6191.7364224
7039.98871212466
7268.25499216019

The results of the method are the same as the graph on Wikipedia. At yearly interest, we end up with $6191.94. But at monthly interest we end up with $7268.25. These figures are at the same interest rate of 20%.


Simulation. This next program is more complex. It implements a stock-buying program. It simulates a trader who buys a dividend stock, or an interest-paying fund. Each month it collects dividend payments.

Then: The program tries to reinvest those dividend payments into the same stock or fund. It buys the maximum number of new shares.

Also: It stores cash in a separate variable. Cash accumulates and is used as part of further purchases.

It requires two input files. The first is dividends.txt, which should contain 4 or 12 of the recent dividend payments. And the second is prices.txt, which should contain 12 lines of the fund's price at the start of months.

Input file 1: dividends.txt

0.77013
0.61389
0.68826
0.77945

Input file 2: prices.txt

122.00
124.85
127.75
132.31
137.32
140.64
139.81
129.41
136.53
138.72
141.09
144.50

C# program that simulates trading

using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
	// ... Read in dividend payments.
	string[] dividendValues = File.ReadAllLines("C:\\dividends.txt");
	double[] dividends = dividendValues.Select(a => double.Parse(a)).ToArray();
	int dividendCount = dividends.Length;

	// ... Used to match a dividend payment to a monthly price.
	int dividendPriceMultiplier = dividendCount == 4 ?
	    3 : 1;

	// ... Read in prices for each month.
	string[] priceValues = File.ReadAllLines("C:\\prices.txt");
	double[] prices = priceValues.Select(a => double.Parse(a)).ToArray();

	double cash = 0;
	double shares = 1000;
	double moneyBefore = shares * prices[0];

	Console.WriteLine("Dividend to price multiplier: {0}", dividendPriceMultiplier);
	Console.WriteLine("Starting shares: {0}", shares);
	Console.WriteLine("Starting value: {0}", moneyBefore);
	Console.WriteLine();

	// ... Compute and reinvest dividends.
	for (int i = 0; i < dividendCount; i++)
	{
	    // ... Multiply dividend by share count.
	    double payout = dividends[i] * shares;

	    Console.WriteLine(i);
	    Console.WriteLine("    Dividend: {0}", payout);

	    // ... Add payout to cash.
	    cash += payout;

	    Console.WriteLine("    Cash before: {0}", cash);
	    Console.WriteLine("    Shares before: {0}", shares);

	    // ... Get current price.
	    double currentPrice = prices[i * dividendPriceMultiplier];

	    // ... Buy as many shares as possible.
	    double buyCount = Math.Floor(cash / currentPrice);

	    // ... Compute cost.
	    double cost = buyCount * currentPrice;

	    Console.WriteLine("    Current price: {0}", currentPrice);
	    Console.WriteLine("    Buy new shares: {0}", buyCount);
	    Console.WriteLine("    Reduce cash by: {0}", cost);

	    // ... Add to shares.
	    shares += buyCount;

	    // ... Subtract from cash.
	    cash -= cost;

	    Console.WriteLine("    Cash after: {0}", cash);
	}

	// ... Final value of account.
	double moneyAfter = (shares * prices[11]) + cash;

	// ... Convert to 1000 starting.
	double adjust = moneyAfter / moneyBefore;
	adjust *= 1000;

	Console.WriteLine();
	Console.WriteLine("Ending shares: {0}", shares);
	Console.WriteLine("Ending cash: {0}", cash);
	Console.WriteLine("Ending value: {0}", moneyAfter);
	Console.WriteLine("1000 grows to {0}", adjust);
    }
}

Output

Dividend to price multiplier: 3
Starting shares: 1000
Starting value: 122000

0
    Dividend: 770.13
    Cash before: 770.13
    Shares before: 1000
    Current price: 122
    Buy new shares: 6
    Reduce cash by: 732
    Cash after: 38.13
1
    Dividend: 617.57334
    Cash before: 655.70334
    Shares before: 1006
    Current price: 132.31
    Buy new shares: 4
    Reduce cash by: 529.24
    Cash after: 126.46334
2
    Dividend: 695.1426
    Cash before: 821.60594
    Shares before: 1010
    Current price: 139.81
    Buy new shares: 5
    Reduce cash by: 699.05
    Cash after: 122.55594
3
    Dividend: 791.14175
    Cash before: 913.69769
    Shares before: 1015
    Current price: 138.72
    Buy new shares: 6
    Reduce cash by: 832.32
    Cash after: 81.3776900000001

Ending shares: 1021
Ending cash: 81.3776900000001
Ending value: 147615.87769
1000 grows to 1209.96621057377

The program has some weaknesses. It does not subtract a brokerage fee or any other fees. It assumes when you buy the stock you are instantly paid a dividend. It pays dividends on the first of a month.

So: It is flawed but helps illustrate, conceptually, how dividends from shares are used to buy new shares.

And: It is a complete yet primitive implementation of a trading simulation. Further logic could even add decision-making.

File.ReadAllLinesSelectDoubleMath.Floor

Summary. We implemented a compound interest formula in the C# language. With this function we specify the interest rate, and the number of times interest is compounded per year. It returns the final amount of money.

Tip: Using the decimal type would be worthwhile in these methods. It retains more digits and can handle much larger numbers.

Decimal