I want to actively calculate the moving average of stock data using the formula below:
public class Average {
private static double usdJpy;
private int counter = 1;
private double movingAverageUsdJpy_ = 100.5;
public void calculateAverage(){
ReadData myData = new ReadData();
usdGbp = myData.getUsdGbp();
usdJpy = myData.getUsdJpy();
System.out.println("Before: " + movingAverageUsdJpy_);
movingAverageUsdJpy_ = (counter * movingAverageUsdJpy_ + usdJpy) / (counter + 1);
counter++;
System.out.println("Moving Average: " + movingAverageUsdJpy_);
}
}
-> Counter is the number of elements in the array.
My question is since the stock data already has a moving average, I want to set my initial movingAverage value to that (e.g 97.883). However, every time I call my method, the latest value that my program calculated for the movingAverage will be overwritten by the initial value I have set earlier, hence giving me the wrong result. I can't really use final because the movingAverage needs to be updated each time I call the method so really stuck!
Is there a way to fix this problem??