Compound InterestCompute compound interest. Specify if it is compounded monthly, quarterly or yearly.
C#
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.
Some aspects of investing, like dividends, may not be part of the compound interest formula. We can compute dividends with another method.
Example. 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.
Info When interest is compounded quarterly, we pass 4 to the method. When interest is compounded monthly, we pass 12.
Result We find that the \$1,500 amount has grown to \$1938.84 after the six years. We have made some money.
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); } }
1938.83682213411
Frequency. The frequency of compounding affects the total value of the investment. There is a significant difference between yearly, monthly and quarterly frequencies.
Info At yearly interest, we end up with \$6191.94. But at monthly interest we end up with \$7268.25.
And These figures are at the same interest rate of 20%. The results of the method are the same as the graph on Wikipedia.
Console.WriteLine(CompoundInterest(1000, 0.2, 1, 10)); Console.WriteLine(CompoundInterest(1000, 0.2, 4, 10)); Console.WriteLine(CompoundInterest(1000, 0.2, 12, 10));
6191.7364224 7039.98871212466 7268.25499216019
Simulation. This program 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.
Detail It requires dividends.txt, which should contain 4 or 12 of the recent dividend payments.
Detail And the second is prices.txt, which should contain 12 lines of the fund's price at the start of months.
0.77013 0.61389 0.68826 0.77945
122.00 124.85 127.75 132.31 137.32 140.64 139.81 129.41 136.53 138.72 141.09 144.50