/******************************************************************************
* Name: Reference Solution
* NetID: ref
* Precept: P00
*
* Partner Name: N/A
* Partner NetID: N/A
* Partner Precept: N/A
*
* Description: Reads, prints, and plots stock prices.
*
* Computes 3-day simple moving average starting on the 3rd
* day. Plots and prints stock price data and moving average.
*
* Example: java-introcs MovingAverage3 < TSLA.txt
*
******************************************************************************/
public class MovingAverage3 {
public static void main(String[] args) {
// Number of trading days
int n = StdIn.readInt();
int DAYS = 3;
// parallel arrays
String[] date = new String[n];
double[] open = new double[n];
double[] high = new double[n];
double[] low = new double[n];
double[] close = new double[n];
double[] ma = new double[n];
// Read in daily prices
for (int i = 0; i < n; i++) {
date[i] = StdIn.readString();
open[i] = StdIn.readDouble();
high[i] = StdIn.readDouble();
low[i] = StdIn.readDouble();
close[i] = StdIn.readDouble();
// compute moving average if needed
if (i >= DAYS - 1) {
// sum of previous 3 days
double sum = 0;
for (int j = i; j > i - DAYS; j--) {
sum += close[j];
}
// compute moving average
ma[i] = sum / DAYS;
}
}
// Plot stock price data
StockPlot.plot(open, high, low, close, ma, DAYS);
// Output the information
StdOut.println(n);
for (int i = 0; i < n; i++) {
StdOut.printf("%s %.2f %.2f %.2f %.2f",
date[i], open[i], high[i], low[i], close[i]);
if (i >= DAYS - 1)
StdOut.printf(" %.2f", ma[i]);
StdOut.println();
}
}
}