TimeSeriesPercentageChangeOperator extends Function1D<DateDoubleTimeSeries<?>, DateDoubleTimeSeries<?>> { @Override public DateDoubleTimeSeries<?> evaluate(DateDoubleTimeSeries<?> ts) { ArgumentChecker.notNull(ts, "time series"); ArgumentChecker.isTrue(ts.size() > _lag, "time series length must be > lag"); final int[] times = ts.timesArrayFast(); final double[] values = ts.valuesArrayFast(); final int n = times.length; final int[] resultTimes = new int[n - _lag]; final double[] percentageChanges = new double[n - _lag]; for (int i = _lag; i < n; i++) { ArgumentChecker.isTrue(values[i - _lag] != 0.0d, "value equal to 0 at date {}, no relative change can be computed", times[i - _lag]); resultTimes[i - _lag] = times[i]; percentageChanges[i - _lag] = (values[i] - values[i - _lag]) / values[i - _lag]; } return ImmutableLocalDateDoubleTimeSeries.of(resultTimes, percentageChanges); } TimeSeriesPercentageChangeOperator();  TimeSeriesPercentageChangeOperator(int lag); @Override DateDoubleTimeSeries<?> evaluate(DateDoubleTimeSeries<?> ts);  }
@Test(expectedExceptions = IllegalArgumentException.class) public void nullTsException() { OP_REL_1.evaluate((LocalDateDoubleTimeSeries) null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void tooShortTimeSeriesException() { LocalDateDoubleTimeSeries tooShortTs = ImmutableLocalDateDoubleTimeSeries.of( new LocalDate[] {LocalDate.of(2014, 1, 2) }, new Double[] {1.0 }); OP_REL_1.evaluate(tooShortTs); }
@Test(expectedExceptions = IllegalArgumentException.class) public void zeroValue() { LocalDateDoubleTimeSeries zeroValueTs = ImmutableLocalDateDoubleTimeSeries.of( new LocalDate[] {LocalDate.of(2014, 1, 2), LocalDate.of(2014, 1, 3), LocalDate.of(2014, 1, 4) }, new Double[] {1.0, 0.0, 1.0 }); OP_REL_1.evaluate(zeroValueTs); }
@Test public void relative1() { DateDoubleTimeSeries<?> tsRet1 = OP_REL_1.evaluate(TS_1); assertEquals(NB_DATA_1 - 1, tsRet1.size()); for (int i = 1; i < NB_DATA_1; i++) { LocalDate dateTs = TS_1.getTimeAtIndex(i); LocalDate dateRet = (LocalDate) tsRet1.getTimeAtIndex(i - 1); assertEquals(dateTs, dateRet); double retComputed = tsRet1.getValueAtIndex(i - 1); double retExpected = (TS_1.getValueAtIndex(i) - TS_1.getValueAtIndex(i - 1)) / TS_1.getValueAtIndex(i - 1); assertEquals(retExpected, retComputed, TOLERANCE_DIFF); } }
@Test public void relative2() { DateDoubleTimeSeries<?> tsRet = OP_REL_2.evaluate(TS_1); assertEquals(NB_DATA_1 - 2, tsRet.size()); for (int i = 2; i < NB_DATA_1; i++) { LocalDate dateTs = TS_1.getTimeAtIndex(i); LocalDate dateRet = (LocalDate) tsRet.getTimeAtIndex(i - 2); assertEquals(dateTs, dateRet); double retComputed = tsRet.getValueAtIndex(i - 2); double retExpected = (TS_1.getValueAtIndex(i) - TS_1.getValueAtIndex(i - 2)) / TS_1.getValueAtIndex(i - 2); assertEquals(retExpected, retComputed, TOLERANCE_DIFF); } }