movavg-aggregation.asciidoc 19 KB

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