Array & Loop calculations - c#

I am doing a simple loan calculation of compound interest. When click "calculate", it will show in the list box the monthly payment every month and other information such as property tax. However, the information does not seem to appear at all.
private void btnCalculate_Click_1(object sender, EventArgs e)
{
decimal amount = 0.0m;
double principal;
double rate = 0.05;
int Years;
int timesPerYear = 12;
Years = int.Parse(tbLoanTerm.Text); ;
principal = int.Parse(tbAmount.Text);
int Months = 0;
decimal amountMonthly = 0.0m;
listBox1.Items.Add("Month \t\t\tMonthly Payment\t\t\tProperty Tax");
while(Months<=360)
{
Months = Years * 12;
double body = 1 + (rate / timesPerYear);
double exponent = timesPerYear * Years;
amount = Convert.ToInt32(principal * Math.Pow(body, exponent));
amountMonthly = amount / Months;
propertytaxdec = amount * Property_Tax;
listBox1.Items.Add(Months + "\t\t" + amountMonthly + "\t\t" + propertytaxdec);
Months++;
}
}

Related

Divide Into Monthly Installments

Hi I'm trying to make Monthly Installments of a "double value"
The Problem is that the decimal values get divided too, and i don't need that happen.
Example :
List<Installments> InstallmentList {get; set;}
for (int i = 0 ; int i <= Month ; i++)
{
double Value = 90.10 ;
int Month = 3;
InstallmentCost = Value / Month;
InstallmentList.Add (new Installment {InstallmentCost = example.InstallmentCost} )
}
Doing That i will get a list of Installments where the value will be :
Installment = 30.03333333333333;
Installment = 30.03333333333333;
Installment = 30.03333333333333;
But I need that the decimals do not divide and and only the last Installment gets it
Example Of The Results that i need :
Installment = 30.00;
Installment = 30.00;
Installment = 30.10;
Just truncate the installment which only takes the integral part (if not C# then convert to something like int and back to double would do the trick!).
I have used C#, here's the working solution:-
double Value = 90.10;
int Month = 3;
for (int i = 1; i <= Month ; i++)
{
var installmentCost = Math.Truncate(Value / Month);
InstallmentList.Add(new Installment {InstallmentCost = installmentCost});
}
// Extract pending balance to be adjusted, total - the sum of all installments
double pendingBalanceToAdjust = Value - InstallmentList.Sum((s) => s.InstallmentCost);
// Update to the last installment
if (pendingBalanceToAdjust > 0)
InstallmentList.Last().InstallmentCost += pendingBalanceToAdjust;
You can calculate the remainder at the start and then divide the rest into equal parts:
double value = 90.10;
int month = 3;
// calculate the remainder with precision 0.1
double remainder = value % (month * 0.1);
double installmentValue = (value - remainder) / month;
for (int i = 0; i < month - 1; i++)
InstallmentList.Add(new Installment {InstallmentCost = installmentCost});
InstallmentList.Add(new Installment {InstallmentCost = installmentCost + remainder});
the expression value % (month * 0.1) effectively works out what is left over if you keep giving each of the 3 months 0.1 from the value until you can no longer carry on.
Changing the precision to 0.01 will change the outcome to: 30.03, 30.03, 30.04
Linq approach
decimal value = 90.10m;
int month = 3;
List<Installment> installments = Enumerable.Range(0, month).Select(x => new Installment() { InstallmentCost = Math.Floor(value / month) }).ToList();
installments.Last().InstallmentCost += (value - installments.Sum(x => x.InstallmentCost));

Calculate EMA for MACD with 2 lines indicator in C#

I'm trying to write an indicator script that will plot the MACD with 2 lines in a practice trading tool.
At the moment, I'm following the formula which is using the EMA formula to calculate it.
I'm able to plot the chart. But somehow my indicator result does not have the exact same result as the one on meta trader 4 or on trading view. The indicator result on these apps is exactly the same.
I think I have missed something when I try to convert from the formula to actual code. Please help me fix it. Thank you.
Here is the part that will calculate the EMA.
/// ==================================================================
/// ======================== calculations ============================
/// ==================================================================
public void Calculate()
{
for (int i = 0; i < Bars.Length; i++){
if (i >= SlowEMA) {
MACD[i] = CalculateEMA(FastEMA, i) - CalculateEMA(SlowEMA, i);
Signal[i] = CalculateEMA_MACD(MACD, SignalEMA, i);
Histogram[i] = MACD[i] - Signal[i];
}
}
}
private double CalculateEMA(int Period, int index)
{
var currentValue = 0d;
var currentEMA = 0d;
var yesterdayEMA = 0d;
var smooth = 2d;
var multiplier = smooth / (1 + Period);
for (int i = 0; i < Period; i++){
currentValue = GetPrice(index + i - Period);
currentEMA = (currentValue * multiplier) + (yesterdayEMA * (1 - multiplier));
yesterdayEMA = currentEMA;
};
return yesterdayEMA;
}
private double CalculateEMA_MACD(double[] MACD, int Period, int index)
{
var currentValue = 0d;
var currentEMA = 0d;
var yesterdayEMA = 0d;
var smooth = 2d;
var multiplier = smooth / (1 + Period);
for (int i = 0; i < Period; i++){
currentValue = MACD[index + i - Period];
currentEMA = (currentValue * multiplier) + (yesterdayEMA * (1 - multiplier));
yesterdayEMA = currentEMA;
};
return yesterdayEMA;
}
private double GetPrice(int index)
{
Bar bar = Bars[index];
switch (Source)
{
case Sources.Close:
return bar.Close;
case Sources.Open:
return bar.Open;
case Sources.High:
return bar.High;
case Sources.Low:
return bar.Low;
case Sources.MedianPrice:
return (bar.High + bar.Low) / 2;
case Sources.TypicalPrice:
return (bar.High + bar.Low + bar.Close) / 3;
case Sources.WeightedClose:
return (bar.High + bar.Low + bar.Close + bar.Close) / 4;
}
throw new NotSupportedException("Unsupported price source type: " + Source);
}
It looks like your logic for EMA calculation is wrong. Based on your code, yesterdayEMA is always 0 and therefore right part of EMA equation is also 0.
private double CalculateEMA(int Period, int index)
{
...
var yesterdayEMA = 0D;
...
currentEMA = (currentValue * multiplier) + (yesterdayEMA * (1 - multiplier));
currentEMA = (currentValue * multiplier) + 0
...
}
You need to store yesterdayEMA outside of CalculateEMA and pass it as parameter for recursive calculation.
0 comes true in the first cycle, but yesterday EMA = current EMA; It starts to take values different from 0 in the next cycle due to its equality.

How do I get the values from a list box converted correctly as variables

Im very new to c# and coding in general. For my class I need to get the average, lowest, and highest number out of a list box. Im just trying to get all the numbers out and add them all together and divide them simply. I understand its not efficient but I need to understand it first.
private void button1_calculate_Click(object sender, EventArgs e)
{
double firstValue = (double)listBox_Values.Items[0];
double secondValue = (double)listBox_Values.Items[1];
double thirdValue = (double)listBox_Values.Items[2];
double fourthValue = (double)listBox_Values.Items[3];
double fifthValue = (double)listBox_Values.Items[4];
double sixthValue = (double)listBox_Values.Items[5];
double seventhValue = (double)listBox_Values.Items[6];
double average = 0;
average = firstValue + secondValue + thirdValue + fourthValue + fifthValue + sixthValue + seventhValue / 7;
textBox_Average.Text = average.ToString();
}
You can loop through your list of numbers and then divide by the number of list items:
int total = 0;
foreach (object item in listBox1.Items)
{
total += Convert.ToInt32(item);
}
int average = total / listBox1.Items.Count;

Tuition Increase

I am trying to get this to display Year 1 original tuition + interest rate then have all the interest rates compound afterwards. It gets stuck on Year 2 then just repeats.
private void button1_Click(object sender, EventArgs e)
{
double originalTuition = 6000.00;
double newTuition;
double interestRate = 0.02;
tuitionListBox.Items.Clear();
for (int year = 1; year <= 5; year++)
{
if (year == 1)
newTuition = originalTuition;
else
newTuition = originalTuition + (originalTuition * interestRate);
newTuition = newTuition + (newTuition * interestRate);
tuitionListBox.Items.Add(year + "\t" + newTuition.ToString("c"));
}
}
newTuition will always start with the same value after year 1 due to your ‘else’ block. My guess is you want to remove the first line of code after the ‘else’.
First initialize newTuition variable.
Then below code:
for (int year = 1; year <= 5; year++)
{
if (year == 1)
newTuition = originalTuition;
else
newTuition = newTuition + (newTuition * interestRate);
tuitionListBox.Items.Add(year + "\t" + newTuition.ToString("c"));
}
I would suggest creating a new method for clarity and reusability. Using brackets with if/else statements makes the code more easy to read, and thereby identifying the problem.
private List<double> GetAnnualTuitions(double originalTuition, double interestRate, int numOfYears)
{
double newTuition = 0;
List<double> tuitions = new List<double>();
for (int year = 1; year <= numOfYears; year++)
{
if (year == 1)
{
newTuition = originalTuition;
}
else
{
newTuition += (newTuition * interestRate);
}
tuitions.Add(newTuition);
}
return tuitions;
}

Comparing Math.Log and Math.Pow

I am working with annuities and have the following methods in my code:
public static double NumPMTsRemaining( double CurBalance, double ContractRate, double Pmt)
{
double rt = PeriodicRate(ContractRate);
return -1 * Math.Log(1 - (CurBalance * (rt) / Pmt)) / Math.Log(1 + (rt));
}
public static double MonthlyPMT(double OrigBalance, double ContractRate, int Term)
{
double rt = PeriodicRate(ContractRate);
if (ContractRate > 0)
return (OrigBalance * rt * Math.Pow(1 + rt, Term)) / (Math.Pow(1 + rt, Term) - 1);
else return OrigBalance / Term;
}
I use the former method to determine if the payment for a loan will insure the loans pays off in its life remaining. I use the latter method to determine if a payment is quoted for a payment period other than monthly and then replace it with a monthly payment if so. Upon reflection I can use the latter method for both tasks.
With that in mind, I was wondering if anyone knew off the top of their head if Math.Pow is faster/more efficient than/relative to Math.Log?
I assume that Math.Pow is the better choice, but would appreciate a bit of input.
I have built a benchmark as recommended by #Mangist. The code is posted below. I was surprised by the response by #CodesInChaos. I, of course, did some research and realized I could improve a large amount of my code. I will post a link to a interesting StackOverflow article I found in this regard. A number of people had worked out improvements on Math.Pow due to the aforementioned fact.
Thank you again for the suggestions and information.
int term = 72;
double contractRate = 2.74 / 1200;
double balance = 20203.66;
double pmt = 304.96;
double logarithm = 0;
double power = 0;
DateTime BeginLog = DateTime.UtcNow;
for (int i = 0; i < 100000000; i++)
{
logarithm=(-1*Math.Log(1-(balance*contractRate/pmt))/Math.Log(1+contractRate));
}
DateTime EndLog = DateTime.UtcNow;
Console.WriteLine("Elapsed time= " + (EndLog - BeginLog));
Console.ReadLine();
DateTime BeginPow = DateTime.UtcNow;
for (int i = 0; i < 100000000; i++)
{
power = (balance * contractRate * Math.Pow(1 + contractRate, term)) / (Math.Pow(1
+ contractRate, term) - 1);
}
DateTime EndPow = DateTime.UtcNow;
Console.WriteLine("Elapsed time= " + (EndPow - BeginPow));
Console.ReadLine();
The results of the benchmark were
Elapsed time for the logarithm 00:00:04.9274927
Elapsed time for the power 00:00:11.6981697
I also alluded to some additional StackOverflow discussions which shed light on the comment by #CodeInChaos.
How is Math.Pow() implemented in .NET Framework?
Let me add a head to head comparison between a suggestion on the above link and the Math.Pow function. I benchmarked Math.Pow(x,y) against Math.Exp(y*Math.Log(x)) with the following code:
DateTime PowBeginTime = DateTime.UtcNow;
for (int i = 0; i < 250000000; i++)
{
Math.Pow(1 + contractRate, term);
}
DateTime PowEndTime = DateTime.UtcNow;
Console.WriteLine("Elapsed time= " + (PowEndTime - PowBeginTime));
Console.ReadLine();
DateTime HighSchoolBeginTime = DateTime.UtcNow;
for (int i = 0; i < 250000000; i++)
{
Math.Exp(term * Math.Log(1 + contractRate));
}
DateTime HighSchoolEndTime = DateTime.UtcNow;
Console.WriteLine("Elapsed time= " + (HighSchoolEndTime - HighSchoolBeginTime));
Console.ReadLine();
The results were:
Math.Pow(x,y) 00:00:19.9469945
Math.Exp(y*Math.Log(x)) 00:00:18.3478346

Categories

Resources