Query Details

SMA And EMA Examples

Query

// Simple moving average (SMA) version, curve smoothing.
let window = 7d;
let bucket = 1d;
let min_t = toscalar(OfficeActivity
| where TimeGenerated > ago(window)
| summarize min(TimeGenerated));
let max_t = toscalar(OfficeActivity
| where TimeGenerated > ago(window)
| summarize max(TimeGenerated));
OfficeActivity
| make-series totalAuditCountByDay=count() default=0 on TimeGenerated in range(min_t, max_t, bucket)
| extend buckets=range(min_t, max_t, bucket)
| extend 3d_SimpleMovingAvg=series_fir(totalAuditCountByDay, dynamic([1,1,1])), 3d_SimpleMovingAvg_centered=series_fir(totalAuditCountByDay, dynamic([1,1,1]), true, true), 5d_SimpleMovingAvg=series_fir(totalAuditCountByDay, dynamic([1,1,1,1,1]))
| project buckets,3d_SimpleMovingAvg, 3d_SimpleMovingAvg_centered, 5d_SimpleMovingAvg
| render timechart
 
// Exponential moving average (EMA) version over X days
// l sub p is the estimate or smoothed value of the data, smoothing coefficient more aggressive towards 0
let window = 30d;
let bucket = 1d;
let min_t = toscalar(OfficeActivity | where TimeGenerated > ago(window) | summarize min(TimeGenerated));
let max_t = toscalar(OfficeActivity | where TimeGenerated > ago(window) | summarize max(TimeGenerated));
let series_exp_smooth = (series:dynamic, alpha:real)
{
series_iir(series, pack_array(alpha), pack_array(1, alpha-1))
};
OfficeActivity
| make-series totalAuditCountByDay=count() default=0 on TimeGenerated in range(min_t, max_t, bucket)
| extend lp_num1 = series_exp_smooth(totalAuditCountByDay, 0.6)
| extend lp_num2 = series_exp_smooth(totalAuditCountByDay, 0.5)
| extend lp_num3 = series_exp_smooth(totalAuditCountByDay, 0.4)
| render timechart

Explanation

The query calculates moving averages for the "totalAuditCountByDay" metric in the "OfficeActivity" dataset.

The first part of the query uses a simple moving average (SMA) method with a window of 7 days. It calculates three different moving averages: a 3-day SMA, a centered 3-day SMA, and a 5-day SMA. The results are displayed in a timechart.

The second part of the query uses an exponential moving average (EMA) method with a window of 30 days. It calculates three different moving averages using different smoothing coefficients (0.6, 0.5, and 0.4). The results are also displayed in a timechart.

Details

Rod Trent profile picture

Rod Trent

Released: March 26, 2020

Tables

OfficeActivity

Keywords

OfficeActivity,TimeGenerated,make-series,count(),default=0,range(),extend,series_fir,dynamic(),project,render,series_iir,pack_array()

Operators

toscalarwheresummarizemake-seriesextendprojectrenderseries_firrangepack_arrayseries_iir

Actions