I'm trying to calculate a list of closing price for SMA. My program was supposed to be calculating like this. And the value of first day of 5-day SMA will be stored in array with index (time_frame-1).
Daily Closing Prices:
1.4660, 1.4627, 1.4600, 1.4607, 1.4609, 1.4691, 1.4687
First day of 5-day SMA:
(1.4660 + 1.4627 + 1.4600 + 1.4607 + 1.4609) / 5 = 1.4621
Second day of 5-day SMA:
(1.4627 + 1.4600 + 1.4607 + 1.4609 + 1.4691) / 5 = 1.4627
Third day of 5-day SMA:
(1.4600 + 1.4607 + 1.4609 + 1.4691 + 1.4687) / 5 = 1.4639
This is my typedef struct
typedef struct
{
char date[11];
double price;
double SMA;
double EMA;
}DATA;
This is the main function.
int main(void)
{
DATA forex[100];
int time_frame, count;
get_data(&time_frame, &count, forex);
calculate_SMA(time_frame, count, forex);
return 0;
}
This function is to read from my text file "forexPrice.txt" and get user input for time_frame
void get_data(int *time_frame, int *count, DATA forex[])
{
int i = 0;
bool cont;
ifstream infile("forexPrice.txt", ios::in);
if (!infile)
cout << "Error opening input file!";
else
{
*count = 0;
do
{
infile >> forex[i].date >> forex[i].price;
cout << forex[i].date << "\t" << fixed << setprecision(4) << forex[i].price << endl;
i++;
(*count)++;
} while (!infile.eof());
infile.close();
}
do
{
cont = true;
cout << "Enter the number of days to calculate SMA and EMA: ";
cin >> *time_frame;
if (*time_frame < 1 || *time_frame >= *count)
{
cout << "Do not enter number smaller than 1 or larger than " << *count << ". Please enter again.\n";
cont = false;
//break;
}
} while (cont == false);
}
This is the function to calculate SMA and error has shown at line price_total += forex[i].price;
when i use debugger.
void calculate_SMA(int time_frame, int count, DATA forex[])
{
double sma, price_total;
for (int j = time_frame - 1; j < count; j++)
{
price_total = 0.0;
for (int i = 0; i < i + time_frame; i++)
price_total += forex[i].price;
forex[j].SMA = price_total / time_frame;
cout << forex[j].SMA << endl;
}
}