movavg-aggregation.asciidoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. [[search-aggregations-pipeline-movavg-aggregation]]
  2. === Moving Average Aggregation
  3. coming[2.0.0]
  4. experimental[]
  5. Given an ordered series of data, the Moving Average aggregation will slide a window across the data and emit the average
  6. value of that window. For example, given the data `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`, we can calculate a simple moving
  7. average with windows size of `5` as follows:
  8. - (1 + 2 + 3 + 4 + 5) / 5 = 3
  9. - (2 + 3 + 4 + 5 + 6) / 5 = 4
  10. - (3 + 4 + 5 + 6 + 7) / 5 = 5
  11. - etc
  12. Moving averages are a simple method to smooth sequential data. Moving averages are typically applied to time-based data,
  13. such as stock prices or server metrics. The smoothing can be used to eliminate high frequency fluctuations or random noise,
  14. which allows the lower frequency trends to be more easily visualized, such as seasonality.
  15. ==== Syntax
  16. A `moving_avg` aggregation looks like this in isolation:
  17. [source,js]
  18. --------------------------------------------------
  19. {
  20. "moving_avg": {
  21. "buckets_path": "the_sum",
  22. "model": "holt",
  23. "window": 5,
  24. "gap_policy": "insert_zero",
  25. "settings": {
  26. "alpha": 0.8
  27. }
  28. }
  29. }
  30. --------------------------------------------------
  31. .`moving_avg` Parameters
  32. |===
  33. |Parameter Name |Description |Required |Default Value
  34. |`buckets_path` |Path to the metric of interest (see <<bucket-path-syntax, `buckets_path` Syntax>> for more details |Required |
  35. |`model` |The moving average weighting model that we wish to use |Optional |`simple`
  36. |`gap_policy` |Determines what should happen when a gap in the data is encountered. |Optional |`insert_zero`
  37. |`window` |The size of window to "slide" across the histogram. |Optional |`5`
  38. |`settings` |Model-specific settings, contents which differ depending on the model specified. |Optional |
  39. |===
  40. `moving_avg` aggregations must be embedded inside of a `histogram` or `date_histogram` aggregation. They can be
  41. embedded like any other metric aggregation:
  42. [source,js]
  43. --------------------------------------------------
  44. {
  45. "my_date_histo":{ <1>
  46. "date_histogram":{
  47. "field":"timestamp",
  48. "interval":"day"
  49. },
  50. "aggs":{
  51. "the_sum":{
  52. "sum":{ "field": "lemmings" } <2>
  53. },
  54. "the_movavg":{
  55. "moving_avg":{ "buckets_path": "the_sum" } <3>
  56. }
  57. }
  58. }
  59. }
  60. --------------------------------------------------
  61. <1> A `date_histogram` named "my_date_histo" is constructed on the "timestamp" field, with one-day intervals
  62. <2> A `sum` metric is used to calculate the sum of a field. This could be any metric (sum, min, max, etc)
  63. <3> Finally, we specify a `moving_avg` aggregation which uses "the_sum" metric as its input.
  64. Moving averages are built by first specifying a `histogram` or `date_histogram` over a field. You can then optionally
  65. add normal metrics, such as a `sum`, inside of that histogram. Finally, the `moving_avg` is embedded inside the histogram.
  66. The `buckets_path` parameter is then used to "point" at one of the sibling metrics inside of the histogram (see
  67. <<bucket-path-syntax>> for a description of the syntax for `buckets_path`.
  68. ==== Models
  69. The `moving_avg` aggregation includes four different moving average "models". The main difference is how the values in the
  70. window are weighted. As data-points become "older" in the window, they may be weighted differently. This will
  71. affect the final average for that window.
  72. Models are specified using the `model` parameter. Some models may have optional configurations which are specified inside
  73. the `settings` parameter.
  74. ===== Simple
  75. The `simple` model calculates the sum of all values in the window, then divides by the size of the window. It is effectively
  76. a simple arithmetic mean of the window. The simple model does not perform any time-dependent weighting, which means
  77. the values from a `simple` moving average tend to "lag" behind the real data.
  78. [source,js]
  79. --------------------------------------------------
  80. {
  81. "the_movavg":{
  82. "moving_avg":{
  83. "buckets_path": "the_sum",
  84. "model" : "simple"
  85. }
  86. }
  87. }
  88. --------------------------------------------------
  89. A `simple` model has no special settings to configure
  90. The window size can change the behavior of the moving average. For example, a small window (`"window": 10`) will closely
  91. track the data and only smooth out small scale fluctuations:
  92. [[movavg_10window]]
  93. .Moving average with window of size 10
  94. image::images/pipeline_movavg/movavg_10window.png[]
  95. In contrast, a `simple` moving average with larger window (`"window": 100`) will smooth out all higher-frequency fluctuations,
  96. leaving only low-frequency, long term trends. It also tends to "lag" behind the actual data by a substantial amount:
  97. [[movavg_100window]]
  98. .Moving average with window of size 100
  99. image::images/pipeline_movavg/movavg_100window.png[]
  100. ==== Linear
  101. The `linear` model assigns a linear weighting to points in the series, such that "older" datapoints (e.g. those at
  102. the beginning of the window) contribute a linearly less amount to the total average. The linear weighting helps reduce
  103. the "lag" behind the data's mean, since older points have less influence.
  104. [source,js]
  105. --------------------------------------------------
  106. {
  107. "the_movavg":{
  108. "moving_avg":{
  109. "buckets_path": "the_sum",
  110. "model" : "linear"
  111. }
  112. }
  113. --------------------------------------------------
  114. A `linear` model has no special settings to configure
  115. Like the `simple` model, window size can change the behavior of the moving average. For example, a small window (`"window": 10`)
  116. will closely track the data and only smooth out small scale fluctuations:
  117. [[linear_10window]]
  118. .Linear moving average with window of size 10
  119. image::images/pipeline_movavg/linear_10window.png[]
  120. In contrast, a `linear` moving average with larger window (`"window": 100`) will smooth out all higher-frequency fluctuations,
  121. leaving only low-frequency, long term trends. It also tends to "lag" behind the actual data by a substantial amount,
  122. although typically less than the `simple` model:
  123. [[linear_100window]]
  124. .Linear moving average with window of size 100
  125. image::images/pipeline_movavg/linear_100window.png[]
  126. ==== EWMA (Exponentially Weighted)
  127. The `ewma` model (aka "single-exponential") is similar to the `linear` model, except older data-points become exponentially less important,
  128. rather than linearly less important. The speed at which the importance decays can be controlled with an `alpha`
  129. setting. Small values make the weight decay slowly, which provides greater smoothing and takes into account a larger
  130. portion of the window. Larger valuers make the weight decay quickly, which reduces the impact of older values on the
  131. moving average. This tends to make the moving average track the data more closely but with less smoothing.
  132. The default value of `alpha` is `0.5`, and the setting accepts any float from 0-1 inclusive.
  133. [source,js]
  134. --------------------------------------------------
  135. {
  136. "the_movavg":{
  137. "moving_avg":{
  138. "buckets_path": "the_sum",
  139. "model" : "ewma",
  140. "settings" : {
  141. "alpha" : 0.5
  142. }
  143. }
  144. }
  145. --------------------------------------------------
  146. [[single_0.2alpha]]
  147. .EWMA with window of size 10, alpha = 0.2
  148. image::images/pipeline_movavg/single_0.2alpha.png[]
  149. [[single_0.7alpha]]
  150. .EWMA with window of size 10, alpha = 0.7
  151. image::images/pipeline_movavg/single_0.7alpha.png[]
  152. ==== Holt-Linear
  153. The `holt` model (aka "double exponential") incorporates a second exponential term which
  154. tracks the data's trend. Single exponential does not perform well when the data has an underlying linear trend. The
  155. double exponential model calculates two values internally: a "level" and a "trend".
  156. The level calculation is similar to `ewma`, and is an exponentially weighted view of the data. The difference is
  157. that the previously smoothed value is used instead of the raw value, which allows it to stay close to the original series.
  158. The trend calculation looks at the difference between the current and last value (e.g. the slope, or trend, of the
  159. smoothed data). The trend value is also exponentially weighted.
  160. Values are produced by multiplying the level and trend components.
  161. The default value of `alpha` and `beta` is `0.5`, and the settings accept any float from 0-1 inclusive.
  162. [source,js]
  163. --------------------------------------------------
  164. {
  165. "the_movavg":{
  166. "moving_avg":{
  167. "buckets_path": "the_sum",
  168. "model" : "holt",
  169. "settings" : {
  170. "alpha" : 0.5,
  171. "beta" : 0.5
  172. }
  173. }
  174. }
  175. --------------------------------------------------
  176. In practice, the `alpha` value behaves very similarly in `holt` as `ewma`: small values produce more smoothing
  177. and more lag, while larger values produce closer tracking and less lag. The value of `beta` is often difficult
  178. to see. Small values emphasize long-term trends (such as a constant linear trend in the whole series), while larger
  179. values emphasize short-term trends. This will become more apparently when you are predicting values.
  180. [[double_0.2beta]]
  181. .Holt-Linear moving average with window of size 100, alpha = 0.5, beta = 0.2
  182. image::images/pipeline_movavg/double_0.2beta.png[]
  183. [[double_0.7beta]]
  184. .Holt-Linear moving average with window of size 100, alpha = 0.5, beta = 0.7
  185. image::images/pipeline_movavg/double_0.7beta.png[]
  186. ==== Holt-Winters
  187. The `holt_winters` model (aka "triple exponential") incorporates a third exponential term which
  188. tracks the seasonal aspect of your data. This aggregation therefore smooths based on three components: "level", "trend"
  189. and "seasonality".
  190. The level and trend calculation is identical to `holt` The seasonal calculation looks at the difference between
  191. the current point, and the point one period earlier.
  192. Holt-Winters requires a little more handholding than the other moving averages. You need to specify the "periodicity"
  193. of your data: e.g. if your data has cyclic trends every 7 days, you would set `period: 7`. Similarly if there was
  194. a monthly trend, you would set it to `30`. There is currently no periodicity detection, although that is planned
  195. for future enhancements.
  196. There are two varieties of Holt-Winters: additive and multiplicative.
  197. ===== "Cold Start"
  198. Unfortunately, due to the nature of Holt-Winters, it requires two periods of data to "bootstrap" the algorithm. This
  199. means that your `window` must always be *at least* twice the size of your period. An exception will be thrown if it
  200. isn't. It also means that Holt-Winters will not emit a value for the first `2 * period` buckets; the current algorithm
  201. does not backcast.
  202. [[holt_winters_cold_start]]
  203. .Holt-Winters showing a "cold" start where no values are emitted
  204. image::images/pipeline_movavg/triple_untruncated.png[]
  205. Because the "cold start" obscures what the moving average looks like, the rest of the Holt-Winters images are truncated
  206. to not show the "cold start". Just be aware this will always be present at the beginning of your moving averages!
  207. ===== Additive Holt-Winters
  208. Additive seasonality is the default; it can also be specified by setting `"type": "add"`. This variety is preferred
  209. when the seasonal affect is additive to your data. E.g. you could simply subtract the seasonal effect to "de-seasonalize"
  210. your data into a flat trend.
  211. The default value of `alpha`, `beta` and `gamma` is `0.5`, and the settings accept any float from 0-1 inclusive.
  212. The default value of `period` is `1`.
  213. [source,js]
  214. --------------------------------------------------
  215. {
  216. "the_movavg":{
  217. "moving_avg":{
  218. "buckets_path": "the_sum",
  219. "model" : "holt_winters",
  220. "settings" : {
  221. "type" : "add",
  222. "alpha" : 0.5,
  223. "beta" : 0.5,
  224. "gamma" : 0.5,
  225. "period" : 7
  226. }
  227. }
  228. }
  229. --------------------------------------------------
  230. [[holt_winters_add]]
  231. .Holt-Winters moving average with window of size 120, alpha = 0.5, beta = 0.7, gamma = 0.3, period = 30
  232. image::images/pipeline_movavg/triple.png[]
  233. ===== Multiplicative Holt-Winters
  234. Multiplicative is specified by setting `"type": "mult"`. This variety is preferred when the seasonal affect is
  235. multiplied against your data. E.g. if the seasonal affect is x5 the data, rather than simply adding to it.
  236. The default value of `alpha`, `beta` and `gamma` is `0.5`, and the settings accept any float from 0-1 inclusive.
  237. The default value of `period` is `1`.
  238. [WARNING]
  239. ======
  240. Multiplicative Holt-Winters works by dividing each data point by the seasonal value. This is problematic if any of
  241. your data is zero, or if there are gaps in the data (since this results in a divid-by-zero). To combat this, the
  242. `mult` Holt-Winters pads all values by a very small amount (1*10^-10^) so that all values are non-zero. This affects
  243. the result, but only minimally. If your data is non-zero, or you prefer to see `NaN` when zero's are encountered,
  244. you can disable this behavior with `pad: false`
  245. ======
  246. [source,js]
  247. --------------------------------------------------
  248. {
  249. "the_movavg":{
  250. "moving_avg":{
  251. "buckets_path": "the_sum",
  252. "model" : "holt_winters",
  253. "settings" : {
  254. "type" : "mult",
  255. "alpha" : 0.5,
  256. "beta" : 0.5,
  257. "gamma" : 0.5,
  258. "period" : 7,
  259. "pad" : true
  260. }
  261. }
  262. }
  263. --------------------------------------------------
  264. ==== Prediction
  265. All the moving average model support a "prediction" mode, which will attempt to extrapolate into the future given the
  266. current smoothed, moving average. Depending on the model and parameter, these predictions may or may not be accurate.
  267. Predictions are enabled by adding a `predict` parameter to any moving average aggregation, specifying the nubmer of
  268. predictions you would like appended to the end of the series. These predictions will be spaced out at the same interval
  269. as your buckets:
  270. [source,js]
  271. --------------------------------------------------
  272. {
  273. "the_movavg":{
  274. "moving_avg":{
  275. "buckets_path": "the_sum",
  276. "model" : "simple",
  277. "predict" 10
  278. }
  279. }
  280. --------------------------------------------------
  281. The `simple`, `linear` and `ewma` models all produce "flat" predictions: they essentially converge on the mean
  282. of the last value in the series, producing a flat:
  283. [[simple_prediction]]
  284. .Simple moving average with window of size 10, predict = 50
  285. image::images/pipeline_movavg/simple_prediction.png[]
  286. In contrast, the `holt` model can extrapolate based on local or global constant trends. If we set a high `beta`
  287. value, we can extrapolate based on local constant trends (in this case the predictions head down, because the data at the end
  288. of the series was heading in a downward direction):
  289. [[double_prediction_local]]
  290. .Holt-Linear moving average with window of size 100, predict = 20, alpha = 0.5, beta = 0.8
  291. image::images/pipeline_movavg/double_prediction_local.png[]
  292. In contrast, if we choose a small `beta`, the predictions are based on the global constant trend. In this series, the
  293. global trend is slightly positive, so the prediction makes a sharp u-turn and begins a positive slope:
  294. [[double_prediction_global]]
  295. .Double Exponential moving average with window of size 100, predict = 20, alpha = 0.5, beta = 0.1
  296. image::images/pipeline_movavg/double_prediction_global.png[]
  297. The `holt_winters` model has the potential to deliver the best predictions, since it also incorporates seasonal
  298. fluctuations into the model:
  299. [[holt_winters_prediction_global]]
  300. .Holt-Winters moving average with window of size 120, predict = 25, alpha = 0.8, beta = 0.2, gamma = 0.7, period = 30
  301. image::images/pipeline_movavg/triple_prediction.png[]