1. /* ===========================================================
  2. * JFreeChart : a free chart library for the Java(tm) platform
  3. * ===========================================================
  4. *
  5. * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
  6. *
  7. * Project Info: http://www.jfree.org/jfreechart/index.html
  8. *
  9. * This library is free software; you can redistribute it and/or modify it under the terms
  10. * of the GNU Lesser General Public License as published by the Free Software Foundation;
  11. * either version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
  14. * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  15. * See the GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License along with this
  18. * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  19. * Boston, MA 02111-1307, USA.
  20. *
  21. * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
  22. * in the United States and other countries.]
  23. *
  24. * ------------------
  25. * MovingAverage.java
  26. * ------------------
  27. * (C) Copyright 2003-2005, by Object Refinery Limited.
  28. *
  29. * Original Author: David Gilbert (for Object Refinery Limited);
  30. * Contributor(s): Benoit Xhenseval;
  31. *
  32. * $Id: MovingAverage.java,v 1.3 2005/01/14 17:29:49 mungady Exp $
  33. *
  34. * Changes
  35. * -------
  36. * 28-Jan-2003 : Version 1 (DG);
  37. * 10-Mar-2003 : Added createPointMovingAverage(...) method contributed by Benoit Xhenseval (DG);
  38. * 01-Aug-2003 : Added new method for TimeSeriesCollection, and fixed bug in XYDataset method (DG);
  39. * 15-Jul-2004 : Switched getX() with getXValue() and getY() with getYValue() (DG);
  40. * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG);
  41. *
  42. */
  43. package org.jfree.data.time;
  44. import org.jfree.data.xy.XYDataset;
  45. import org.jfree.data.xy.XYSeries;
  46. import org.jfree.data.xy.XYSeriesCollection;
  47. /**
  48. * A utility class for calculating moving averages of time series data.
  49. */
  50. public class MovingAverage {
  51. /**
  52. * Creates a new {@link TimeSeriesCollection} containing a moving average series for each
  53. * series in the source collection.
  54. *
  55. * @param source the source collection.
  56. * @param suffix the suffix added to each source series name to create the corresponding
  57. * moving average series name.
  58. * @param periodCount the number of periods in the moving average calculation.
  59. * @param skip the number of initial periods to skip.
  60. *
  61. * @return A collection of moving average time series.
  62. */
  63. public static TimeSeriesCollection createMovingAverage(TimeSeriesCollection source,
  64. String suffix,
  65. int periodCount,
  66. int skip) {
  67. // check arguments
  68. if (source == null) {
  69. throw new IllegalArgumentException(
  70. "MovingAverage.createMovingAverage(...) : null source."
  71. );
  72. }
  73. if (periodCount < 1) {
  74. throw new IllegalArgumentException("MovingAverage.createMovingAverage(...) : "
  75. + "periodCount must be greater than or equal to 1.");
  76. }
  77. TimeSeriesCollection result = new TimeSeriesCollection();
  78. for (int i = 0; i < source.getSeriesCount(); i++) {
  79. TimeSeries sourceSeries = source.getSeries(i);
  80. TimeSeries maSeries = createMovingAverage(
  81. sourceSeries, sourceSeries.getName() + suffix, periodCount, skip
  82. );
  83. result.addSeries(maSeries);
  84. }
  85. return result;
  86. }
  87. /**
  88. * Creates a new {@link TimeSeries} containing moving average values for the given series.
  89. * <p>
  90. * If the series is empty (contains zero items), the result is an empty series.
  91. *
  92. * @param source the source series.
  93. * @param name the name of the new series.
  94. * @param periodCount the number of periods used in the average calculation.
  95. * @param skip the number of initial periods to skip.
  96. *
  97. * @return The moving average series.
  98. */
  99. public static TimeSeries createMovingAverage(TimeSeries source,
  100. String name,
  101. int periodCount,
  102. int skip) {
  103. // check arguments
  104. if (source == null) {
  105. throw new IllegalArgumentException(
  106. "MovingAverage.createMovingAverage(...) : null source."
  107. );
  108. }
  109. if (periodCount < 1) {
  110. throw new IllegalArgumentException("MovingAverage.createMovingAverage(...) : "
  111. + "periodCount must be greater than or equal to 1.");
  112. }
  113. TimeSeries result = new TimeSeries(name, source.getTimePeriodClass());
  114. if (source.getItemCount() > 0) {
  115. // if the initial averaging period is to be excluded, then calculate the index of the
  116. // first data item to have an average calculated...
  117. long firstSerial = source.getDataItem(0).getPeriod().getSerialIndex() + skip;
  118. for (int i = source.getItemCount() - 1; i >= 0; i--) {
  119. // get the current data item...
  120. TimeSeriesDataItem current = source.getDataItem(i);
  121. RegularTimePeriod period = current.getPeriod();
  122. long serial = period.getSerialIndex();
  123. if (serial >= firstSerial) {
  124. // work out the average for the earlier values...
  125. int n = 0;
  126. double sum = 0.0;
  127. long serialLimit = period.getSerialIndex() - periodCount;
  128. int offset = 0;
  129. boolean finished = false;
  130. while ((offset < periodCount) && (!finished)) {
  131. if ((i - offset) >= 0) {
  132. TimeSeriesDataItem item = source.getDataItem(i - offset);
  133. RegularTimePeriod p = item.getPeriod();
  134. Number v = item.getValue();
  135. long currentIndex = p.getSerialIndex();
  136. if (currentIndex > serialLimit) {
  137. if (v != null) {
  138. sum = sum + v.doubleValue();
  139. n = n + 1;
  140. }
  141. }
  142. else {
  143. finished = true;
  144. }
  145. }
  146. offset = offset + 1;
  147. }
  148. if (n > 0) {
  149. result.add(period, sum / n);
  150. }
  151. else {
  152. result.add(period, null);
  153. }
  154. }
  155. }
  156. }
  157. return result;
  158. }
  159. /**
  160. * Creates a new {@link TimeSeries} containing moving average values for the given series,
  161. * calculated by number of points (irrespective of the 'age' of those points).
  162. * <p>
  163. * If the series is empty (contains zero items), the result is an empty series.
  164. * <p>
  165. * Developed by Benoit Xhenseval (www.ObjectLab.co.uk).
  166. *
  167. * @param source the source series.
  168. * @param name the name of the new series.
  169. * @param pointCount the number of POINTS used in the average calculation (not periods!)
  170. *
  171. * @return The moving average series.
  172. */
  173. public static TimeSeries createPointMovingAverage(TimeSeries source,
  174. String name, final int pointCount) {
  175. // check arguments
  176. if (source == null) {
  177. throw new IllegalArgumentException("MovingAverage.createMovingAverage(...) : "
  178. + "null source.");
  179. }
  180. if (pointCount < 2) {
  181. throw new IllegalArgumentException("MovingAverage.createMovingAverage(...) : "
  182. + "periodCount must be greater than or equal to 2.");
  183. }
  184. TimeSeries result = new TimeSeries(name, source.getTimePeriodClass());
  185. double rollingSumForPeriod = 0.0;
  186. for (int i = 0; i < source.getItemCount(); i++) {
  187. // get the current data item...
  188. TimeSeriesDataItem current = source.getDataItem(i);
  189. RegularTimePeriod period = current.getPeriod();
  190. rollingSumForPeriod += current.getValue().doubleValue();
  191. if (i > pointCount - 1) {
  192. // remove the point i-periodCount out of the rolling sum.
  193. TimeSeriesDataItem startOfMovingAvg = source.getDataItem(i - pointCount);
  194. rollingSumForPeriod -= startOfMovingAvg.getValue().doubleValue();
  195. result.add(period, rollingSumForPeriod / pointCount);
  196. }
  197. else if (i == pointCount - 1) {
  198. result.add(period, rollingSumForPeriod / pointCount);
  199. }
  200. }
  201. return result;
  202. }
  203. /**
  204. * Creates a new {@link XYDataset} containing the moving averages of each series in the
  205. * <code>source</code> dataset.
  206. *
  207. * @param source the source dataset.
  208. * @param suffix the string to append to source series names to create target series names.
  209. * @param period the averaging period.
  210. * @param skip the length of the initial skip period.
  211. *
  212. * @return The dataset.
  213. */
  214. public static XYDataset createMovingAverage(XYDataset source, String suffix,
  215. long period, final long skip) {
  216. return createMovingAverage(source, suffix, (double) period, (double) skip);
  217. }
  218. /**
  219. * Creates a new {@link XYDataset} containing the moving averages of each series in the
  220. * <code>source</code> dataset.
  221. *
  222. * @param source the source dataset.
  223. * @param suffix the string to append to source series names to create target series names.
  224. * @param period the averaging period.
  225. * @param skip the length of the initial skip period.
  226. *
  227. * @return The dataset.
  228. */
  229. public static XYDataset createMovingAverage(XYDataset source, String suffix,
  230. double period, double skip) {
  231. // check arguments
  232. if (source == null) {
  233. throw new IllegalArgumentException(
  234. "MovingAverage.createMovingAverage(...) : null source (XYDataset)."
  235. );
  236. }
  237. XYSeriesCollection result = new XYSeriesCollection();
  238. for (int i = 0; i < source.getSeriesCount(); i++) {
  239. XYSeries s = createMovingAverage(source, i, source.getSeriesName(i) + suffix,
  240. period, skip);
  241. result.addSeries(s);
  242. }
  243. return result;
  244. }
  245. /**
  246. * Creates a new {@link XYSeries} containing the moving averages of one series in the
  247. * <code>source</code> dataset.
  248. *
  249. * @param source the source dataset.
  250. * @param series the series index (zero based).
  251. * @param name the name for the new series.
  252. * @param period the averaging period.
  253. * @param skip the length of the initial skip period.
  254. *
  255. * @return The dataset.
  256. */
  257. public static XYSeries createMovingAverage(XYDataset source,
  258. int series, String name,
  259. double period, double skip) {
  260. // check arguments
  261. if (source == null) {
  262. throw new IllegalArgumentException("MovingAverage.createMovingAverage(...) : "
  263. + "null source (XYDataset).");
  264. }
  265. if (period < Double.MIN_VALUE) {
  266. throw new IllegalArgumentException("MovingAverage.createMovingAverage(...) : "
  267. + "period must be positive.");
  268. }
  269. if (skip < 0.0) {
  270. throw new IllegalArgumentException("MovingAverage.createMovingAverage(...) : "
  271. + "skip must be >= 0.0.");
  272. }
  273. XYSeries result = new XYSeries(name);
  274. if (source.getItemCount(series) > 0) {
  275. // if the initial averaging period is to be excluded, then calculate the lowest
  276. // x-value to have an average calculated...
  277. double first = source.getXValue(series, 0) + skip;
  278. for (int i = source.getItemCount(series) - 1; i >= 0; i--) {
  279. // get the current data item...
  280. double x = source.getXValue(series, i);
  281. if (x >= first) {
  282. // work out the average for the earlier values...
  283. int n = 0;
  284. double sum = 0.0;
  285. double limit = x - period;
  286. int offset = 0;
  287. boolean finished = false;
  288. while (!finished) {
  289. if ((i - offset) >= 0) {
  290. double xx = source.getXValue(series, i - offset);
  291. Number yy = source.getY(series, i - offset);
  292. if (xx > limit) {
  293. if (yy != null) {
  294. sum = sum + yy.doubleValue();
  295. n = n + 1;
  296. }
  297. }
  298. else {
  299. finished = true;
  300. }
  301. }
  302. else {
  303. finished = true;
  304. }
  305. offset = offset + 1;
  306. }
  307. if (n > 0) {
  308. result.add(x, sum / n);
  309. }
  310. else {
  311. result.add(x, null);
  312. }
  313. }
  314. }
  315. }
  316. return result;
  317. }
  318. }