movavg-aggregation.asciidoc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. [[search-aggregations-pipeline-movavg-aggregation]]
  2. === Moving Average Aggregation
  3. coming[2.0.0-beta1]
  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 <<buckets-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. |`minimize` |If the model should be algorithmically minimized. See <<movavg-minimizer, Minimization>> for more
  39. details |Optional |`false` for most models
  40. |`settings` |Model-specific settings, contents which differ depending on the model specified. |Optional |
  41. |===
  42. `moving_avg` aggregations must be embedded inside of a `histogram` or `date_histogram` aggregation. They can be
  43. embedded like any other metric aggregation:
  44. [source,js]
  45. --------------------------------------------------
  46. {
  47. "my_date_histo":{ <1>
  48. "date_histogram":{
  49. "field":"timestamp",
  50. "interval":"day"
  51. },
  52. "aggs":{
  53. "the_sum":{
  54. "sum":{ "field": "lemmings" } <2>
  55. },
  56. "the_movavg":{
  57. "moving_avg":{ "buckets_path": "the_sum" } <3>
  58. }
  59. }
  60. }
  61. }
  62. --------------------------------------------------
  63. <1> A `date_histogram` named "my_date_histo" is constructed on the "timestamp" field, with one-day intervals
  64. <2> A `sum` metric is used to calculate the sum of a field. This could be any metric (sum, min, max, etc)
  65. <3> Finally, we specify a `moving_avg` aggregation which uses "the_sum" metric as its input.
  66. Moving averages are built by first specifying a `histogram` or `date_histogram` over a field. You can then optionally
  67. add normal metrics, such as a `sum`, inside of that histogram. Finally, the `moving_avg` is embedded inside the histogram.
  68. The `buckets_path` parameter is then used to "point" at one of the sibling metrics inside of the histogram (see
  69. <<buckets-path-syntax>> for a description of the syntax for `buckets_path`.
  70. ==== Models
  71. The `moving_avg` aggregation includes four different moving average "models". The main difference is how the values in the
  72. window are weighted. As data-points become "older" in the window, they may be weighted differently. This will
  73. affect the final average for that window.
  74. Models are specified using the `model` parameter. Some models may have optional configurations which are specified inside
  75. the `settings` parameter.
  76. ===== Simple
  77. The `simple` model calculates the sum of all values in the window, then divides by the size of the window. It is effectively
  78. a simple arithmetic mean of the window. The simple model does not perform any time-dependent weighting, which means
  79. the values from a `simple` moving average tend to "lag" behind the real data.
  80. [source,js]
  81. --------------------------------------------------
  82. {
  83. "the_movavg":{
  84. "moving_avg":{
  85. "buckets_path": "the_sum",
  86. "window" : 30,
  87. "model" : "simple"
  88. }
  89. }
  90. }
  91. --------------------------------------------------
  92. A `simple` model has no special settings to configure
  93. The window size can change the behavior of the moving average. For example, a small window (`"window": 10`) will closely
  94. track the data and only smooth out small scale fluctuations:
  95. [[movavg_10window]]
  96. .Moving average with window of size 10
  97. image::images/pipeline_movavg/movavg_10window.png[]
  98. In contrast, a `simple` moving average with larger window (`"window": 100`) will smooth out all higher-frequency fluctuations,
  99. leaving only low-frequency, long term trends. It also tends to "lag" behind the actual data by a substantial amount:
  100. [[movavg_100window]]
  101. .Moving average with window of size 100
  102. image::images/pipeline_movavg/movavg_100window.png[]
  103. ==== Linear
  104. The `linear` model assigns a linear weighting to points in the series, such that "older" datapoints (e.g. those at
  105. the beginning of the window) contribute a linearly less amount to the total average. The linear weighting helps reduce
  106. the "lag" behind the data's mean, since older points have less influence.
  107. [source,js]
  108. --------------------------------------------------
  109. {
  110. "the_movavg":{
  111. "moving_avg":{
  112. "buckets_path": "the_sum",
  113. "window" : 30,
  114. "model" : "linear"
  115. }
  116. }
  117. --------------------------------------------------
  118. A `linear` model has no special settings to configure
  119. Like the `simple` model, window size can change the behavior of the moving average. For example, a small window (`"window": 10`)
  120. will closely track the data and only smooth out small scale fluctuations:
  121. [[linear_10window]]
  122. .Linear moving average with window of size 10
  123. image::images/pipeline_movavg/linear_10window.png[]
  124. In contrast, a `linear` moving average with larger window (`"window": 100`) will smooth out all higher-frequency fluctuations,
  125. leaving only low-frequency, long term trends. It also tends to "lag" behind the actual data by a substantial amount,
  126. although typically less than the `simple` model:
  127. [[linear_100window]]
  128. .Linear moving average with window of size 100
  129. image::images/pipeline_movavg/linear_100window.png[]
  130. ==== EWMA (Exponentially Weighted)
  131. The `ewma` model (aka "single-exponential") is similar to the `linear` model, except older data-points become exponentially less important,
  132. rather than linearly less important. The speed at which the importance decays can be controlled with an `alpha`
  133. setting. Small values make the weight decay slowly, which provides greater smoothing and takes into account a larger
  134. portion of the window. Larger valuers make the weight decay quickly, which reduces the impact of older values on the
  135. moving average. This tends to make the moving average track the data more closely but with less smoothing.
  136. The default value of `alpha` is `0.3`, and the setting accepts any float from 0-1 inclusive.
  137. The EWMA model can be <<movavg-minimizer, Minimized>>
  138. [source,js]
  139. --------------------------------------------------
  140. {
  141. "the_movavg":{
  142. "moving_avg":{
  143. "buckets_path": "the_sum",
  144. "window" : 30,
  145. "model" : "ewma",
  146. "settings" : {
  147. "alpha" : 0.5
  148. }
  149. }
  150. }
  151. --------------------------------------------------
  152. [[single_0.2alpha]]
  153. .EWMA with window of size 10, alpha = 0.2
  154. image::images/pipeline_movavg/single_0.2alpha.png[]
  155. [[single_0.7alpha]]
  156. .EWMA with window of size 10, alpha = 0.7
  157. image::images/pipeline_movavg/single_0.7alpha.png[]
  158. ==== Holt-Linear
  159. The `holt` model (aka "double exponential") incorporates a second exponential term which
  160. tracks the data's trend. Single exponential does not perform well when the data has an underlying linear trend. The
  161. double exponential model calculates two values internally: a "level" and a "trend".
  162. The level calculation is similar to `ewma`, and is an exponentially weighted view of the data. The difference is
  163. that the previously smoothed value is used instead of the raw value, which allows it to stay close to the original series.
  164. The trend calculation looks at the difference between the current and last value (e.g. the slope, or trend, of the
  165. smoothed data). The trend value is also exponentially weighted.
  166. Values are produced by multiplying the level and trend components.
  167. The default value of `alpha` is `0.3` and `beta` is `0.1`. The settings accept any float from 0-1 inclusive.
  168. The Holt-Linear model can be <<movavg-minimizer, Minimized>>
  169. [source,js]
  170. --------------------------------------------------
  171. {
  172. "the_movavg":{
  173. "moving_avg":{
  174. "buckets_path": "the_sum",
  175. "window" : 30,
  176. "model" : "holt",
  177. "settings" : {
  178. "alpha" : 0.5,
  179. "beta" : 0.5
  180. }
  181. }
  182. }
  183. --------------------------------------------------
  184. In practice, the `alpha` value behaves very similarly in `holt` as `ewma`: small values produce more smoothing
  185. and more lag, while larger values produce closer tracking and less lag. The value of `beta` is often difficult
  186. to see. Small values emphasize long-term trends (such as a constant linear trend in the whole series), while larger
  187. values emphasize short-term trends. This will become more apparently when you are predicting values.
  188. [[double_0.2beta]]
  189. .Holt-Linear moving average with window of size 100, alpha = 0.5, beta = 0.2
  190. image::images/pipeline_movavg/double_0.2beta.png[]
  191. [[double_0.7beta]]
  192. .Holt-Linear moving average with window of size 100, alpha = 0.5, beta = 0.7
  193. image::images/pipeline_movavg/double_0.7beta.png[]
  194. ==== Holt-Winters
  195. The `holt_winters` model (aka "triple exponential") incorporates a third exponential term which
  196. tracks the seasonal aspect of your data. This aggregation therefore smooths based on three components: "level", "trend"
  197. and "seasonality".
  198. The level and trend calculation is identical to `holt` The seasonal calculation looks at the difference between
  199. the current point, and the point one period earlier.
  200. Holt-Winters requires a little more handholding than the other moving averages. You need to specify the "periodicity"
  201. of your data: e.g. if your data has cyclic trends every 7 days, you would set `period: 7`. Similarly if there was
  202. a monthly trend, you would set it to `30`. There is currently no periodicity detection, although that is planned
  203. for future enhancements.
  204. There are two varieties of Holt-Winters: additive and multiplicative.
  205. ===== "Cold Start"
  206. Unfortunately, due to the nature of Holt-Winters, it requires two periods of data to "bootstrap" the algorithm. This
  207. means that your `window` must always be *at least* twice the size of your period. An exception will be thrown if it
  208. isn't. It also means that Holt-Winters will not emit a value for the first `2 * period` buckets; the current algorithm
  209. does not backcast.
  210. [[holt_winters_cold_start]]
  211. .Holt-Winters showing a "cold" start where no values are emitted
  212. image::images/pipeline_movavg/triple_untruncated.png[]
  213. Because the "cold start" obscures what the moving average looks like, the rest of the Holt-Winters images are truncated
  214. to not show the "cold start". Just be aware this will always be present at the beginning of your moving averages!
  215. ===== Additive Holt-Winters
  216. Additive seasonality is the default; it can also be specified by setting `"type": "add"`. This variety is preferred
  217. when the seasonal affect is additive to your data. E.g. you could simply subtract the seasonal effect to "de-seasonalize"
  218. your data into a flat trend.
  219. The default values of `alpha` and `gamma` are `0.3` while `beta` is `0.1`. The settings accept any float from 0-1 inclusive.
  220. The default value of `period` is `1`.
  221. The additive Holt-Winters model can be <<movavg-minimizer, Minimized>>
  222. [source,js]
  223. --------------------------------------------------
  224. {
  225. "the_movavg":{
  226. "moving_avg":{
  227. "buckets_path": "the_sum",
  228. "window" : 30,
  229. "model" : "holt_winters",
  230. "settings" : {
  231. "type" : "add",
  232. "alpha" : 0.5,
  233. "beta" : 0.5,
  234. "gamma" : 0.5,
  235. "period" : 7
  236. }
  237. }
  238. }
  239. --------------------------------------------------
  240. [[holt_winters_add]]
  241. .Holt-Winters moving average with window of size 120, alpha = 0.5, beta = 0.7, gamma = 0.3, period = 30
  242. image::images/pipeline_movavg/triple.png[]
  243. ===== Multiplicative Holt-Winters
  244. Multiplicative is specified by setting `"type": "mult"`. This variety is preferred when the seasonal affect is
  245. multiplied against your data. E.g. if the seasonal affect is x5 the data, rather than simply adding to it.
  246. The default values of `alpha` and `gamma` are `0.3` while `beta` is `0.1`. The settings accept any float from 0-1 inclusive.
  247. The default value of `period` is `1`.
  248. The multiplicative Holt-Winters model can be <<movavg-minimizer, Minimized>>
  249. [WARNING]
  250. ======
  251. Multiplicative Holt-Winters works by dividing each data point by the seasonal value. This is problematic if any of
  252. your data is zero, or if there are gaps in the data (since this results in a divid-by-zero). To combat this, the
  253. `mult` Holt-Winters pads all values by a very small amount (1*10^-10^) so that all values are non-zero. This affects
  254. the result, but only minimally. If your data is non-zero, or you prefer to see `NaN` when zero's are encountered,
  255. you can disable this behavior with `pad: false`
  256. ======
  257. [source,js]
  258. --------------------------------------------------
  259. {
  260. "the_movavg":{
  261. "moving_avg":{
  262. "buckets_path": "the_sum",
  263. "window" : 30,
  264. "model" : "holt_winters",
  265. "settings" : {
  266. "type" : "mult",
  267. "alpha" : 0.5,
  268. "beta" : 0.5,
  269. "gamma" : 0.5,
  270. "period" : 7,
  271. "pad" : true
  272. }
  273. }
  274. }
  275. --------------------------------------------------
  276. ==== Prediction
  277. All the moving average model support a "prediction" mode, which will attempt to extrapolate into the future given the
  278. current smoothed, moving average. Depending on the model and parameter, these predictions may or may not be accurate.
  279. Predictions are enabled by adding a `predict` parameter to any moving average aggregation, specifying the nubmer of
  280. predictions you would like appended to the end of the series. These predictions will be spaced out at the same interval
  281. as your buckets:
  282. [source,js]
  283. --------------------------------------------------
  284. {
  285. "the_movavg":{
  286. "moving_avg":{
  287. "buckets_path": "the_sum",
  288. "window" : 30,
  289. "model" : "simple",
  290. "predict" 10
  291. }
  292. }
  293. --------------------------------------------------
  294. The `simple`, `linear` and `ewma` models all produce "flat" predictions: they essentially converge on the mean
  295. of the last value in the series, producing a flat:
  296. [[simple_prediction]]
  297. .Simple moving average with window of size 10, predict = 50
  298. image::images/pipeline_movavg/simple_prediction.png[]
  299. In contrast, the `holt` model can extrapolate based on local or global constant trends. If we set a high `beta`
  300. value, we can extrapolate based on local constant trends (in this case the predictions head down, because the data at the end
  301. of the series was heading in a downward direction):
  302. [[double_prediction_local]]
  303. .Holt-Linear moving average with window of size 100, predict = 20, alpha = 0.5, beta = 0.8
  304. image::images/pipeline_movavg/double_prediction_local.png[]
  305. In contrast, if we choose a small `beta`, the predictions are based on the global constant trend. In this series, the
  306. global trend is slightly positive, so the prediction makes a sharp u-turn and begins a positive slope:
  307. [[double_prediction_global]]
  308. .Double Exponential moving average with window of size 100, predict = 20, alpha = 0.5, beta = 0.1
  309. image::images/pipeline_movavg/double_prediction_global.png[]
  310. The `holt_winters` model has the potential to deliver the best predictions, since it also incorporates seasonal
  311. fluctuations into the model:
  312. [[holt_winters_prediction_global]]
  313. .Holt-Winters moving average with window of size 120, predict = 25, alpha = 0.8, beta = 0.2, gamma = 0.7, period = 30
  314. image::images/pipeline_movavg/triple_prediction.png[]
  315. [[movavg-minimizer]]
  316. ==== Minimization
  317. Some of the models (EWMA, Holt-Linear, Holt-Winters) require one or more parameters to be configured. Parameter choice
  318. can be tricky and sometimes non-intuitive. Furthermore, small deviations in these parameters can sometimes have a drastic
  319. effect on the output moving average.
  320. For that reason, the three "tunable" models can be algorithmically *minimized*. Minimization is a process where parameters
  321. are tweaked until the predictions generated by the model closely match the output data. Minimization is not fullproof
  322. and can be susceptible to overfitting, but it often gives better results than hand-tuning.
  323. Minimization is disabled by default for `ewma` and `holt_linear`, while it is enabled by default for `holt_winters`.
  324. Minimization is most useful with Holt-Winters, since it helps improve the accuracy of the predictions. EWMA and
  325. Holt-Linear are not great predictors, and mostly used for smoothing data, so minimization is less useful on those
  326. models.
  327. Minimization is enabled/disabled via the `minimize` parameter:
  328. [source,js]
  329. --------------------------------------------------
  330. {
  331. "the_movavg":{
  332. "moving_avg":{
  333. "buckets_path": "the_sum",
  334. "model" : "holt_winters",
  335. "window" : 30,
  336. "minimize" : true, <1>
  337. "settings" : {
  338. "period" : 7
  339. }
  340. }
  341. }
  342. --------------------------------------------------
  343. <1> Minimization is enabled with the `minimize` parameter
  344. When enabled, minimization will find the optimal values for `alpha`, `beta` and `gamma`. The user should still provide
  345. appropriate values for `window`, `period` and `type`.
  346. [WARNING]
  347. ======
  348. Minimization works by running a stochastic process called *simulated annealing*. This process will usually generate
  349. a good solution, but is not guaranteed to find the global optimum. It also requires some amount of additional
  350. computational power, since the model needs to be re-run multiple times as the values are tweaked. The run-time of
  351. minimization is linear to the size of the window being processed: excessively large windows may cause latency.
  352. Finally, minimization fits the model to the last `n` values, where `n = window`. This generally produces
  353. better forecasts into the future, since the parameters are tuned around the end of the series. It can, however, generate
  354. poorer fitting moving averages at the beginning of the series.
  355. ======