SimpleMovingAverage { public List<DataPoint> learn() { if (dataPoints.size() < smoothingLength) { throw new IllegalArgumentException("Not enough data!, minimum size = " + smoothingLength); } double[] weights; if (symmetric && smoothingLength % 2 == 0) { weights = new double[smoothingLength - 1 + 2]; Arrays.fill(weights, 1, weights.length - 1, 1.0/smoothingLength ); weights[0] = 0.5/smoothingLength; weights[weights.length - 1] = 0.5/smoothingLength; } else { weights = new double[smoothingLength]; Arrays.fill(weights, 1.0/smoothingLength); } WeightedMovingAverage weightedMovingAverage = new WeightedMovingAverage(dataPoints, weights); return weightedMovingAverage.learn(); } SimpleMovingAverage(List<DataPoint> dataPoints, int smoothingLength ,boolean symmetric); List<DataPoint> learn();  }
@Test public void testResultLength() throws IOException { ModelData rModel = ModelReader.read("trendStatUpwardLowVar"); SimpleMovingAverage simpleMovingAverage = new SimpleMovingAverage(rModel.getData(), 5, false); List<DataPoint> result = simpleMovingAverage.learn(); int nullAtBeginning = nullAt(result, true); int nullAtEnd = nullAt(result, false); Assert.assertTrue(nullAtBeginning == 2); Assert.assertTrue(nullAtEnd == 2); simpleMovingAverage = new SimpleMovingAverage(rModel.getData(), 4, false); result = simpleMovingAverage.learn(); nullAtBeginning = nullAt(result, true); nullAtEnd = nullAt(result, false); Assert.assertTrue(nullAtBeginning == 1); Assert.assertTrue(nullAtEnd == 2); simpleMovingAverage = new SimpleMovingAverage(rModel.getData(), 2, false); result = simpleMovingAverage.learn(); nullAtBeginning = nullAt(result, true); nullAtEnd = nullAt(result, false); Assert.assertTrue(nullAtBeginning == 0); Assert.assertTrue(nullAtEnd == 1); }
@Test public void testDoubleMovingAverages() throws IOException { ModelData rModel = ModelReader.read("trendStatUpwardLowVar"); List<DataPoint> data = rModel.getData().subList(0, 15); SimpleMovingAverage simpleMovingAverage = new SimpleMovingAverage(data, 4, true); List<DataPoint> second = simpleMovingAverage.learn(); int nullAtBeginning = nullAt(second, true); int nullAtEnd = nullAt(second, false); Assert.assertTrue(nullAtBeginning == 2); Assert.assertTrue(nullAtEnd == 2); }
@Test public void testError() { try { new SimpleMovingAverage(Collections.emptyList(), 0, false); Assert.fail(); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); } try { List<DataPoint> dataPoints = Arrays.asList(new DataPoint(0D, 0L), new DataPoint(0D,0L)); new SimpleMovingAverage(dataPoints, 3, false).learn(); Assert.fail(); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); } }