# Seasonal Decompose

To calculate the prediction bounds, refer to the [STL Decomposition.ipynb](https://github.com/ritvikmath/Time-Series-Analysis/blob/master/STL%20Decomposition.ipynb) notebook that investigates the option of adding the mean and the standard deviations of the residuals into the trend and seasonal components.

Calculating the lower band

```none
lower = avg_over_time(
  (mean_over_time(Residuals[5m:])
  -$Bound*stddev_over_time(Residuals[5m:]))[5m:])
  + Trend
  + Seasonal Component
```

Calculating the upper band

```none
upper = avg_over_time(
  (mean_over_time(Residuals[5m:])
  +$Bound*stddev_over_time(Residuals[5m:]))[5m:])
  + Trend
  + Seasonal Component
```

## In Dashboards

To use the `seasonal_decompose` operator in a dashboard, apply the following function:

```none
seasonal_decompose( \
  ${promql} \ (1)
  ${seasonality}, \ (2)
  0,\
  ${window},\ (3)
  ${band},\ (4)
  ${bound} (5)
)
```

|     |     |
| --- | --- |
| **1** | `${promql}`: PromQL query to evaluate |
| **2** | `${seasonality}`: Number of minutes to check for seasonality (1440 minutes per day) |
| **3** | `${window}`: Number of milliseconds in the window (1,800,000 ms for a 30-minute window) |
| **4** | `${band}`: 4 = lower band, 5 = upper band, 6 = both upper and lower bands |
| **5** | `${bound}`: Number of standard deviations (stdv): 1, 2, or 3 |

## Limitations

If the evaluated metrics do not exhibit true seasonality, Seasonal Decompose may create incorrect (invalid) alerts, or mask valid alerting conditions.

## Next steps

For an in-depth discussion of the Seasonal Decomposition approach, see these resources:

- Documentation for [statsmodels.tsa.seasonal.seasonal_decompose](https://www.statsmodels.org/stable/generated/statsmodels.tsa.seasonal.seasonal_decompose.html)

- [Decomposition of time series](https://en.wikipedia.org/wiki/Decomposition_of_time_series) in Wikipedia

- [Time-Series-Analysis/STL Decomposition.ipynb](https://github.com/ritvikmath/Time-Series-Analysis/blob/master/STL%20Decomposition.ipynb) GitHub repository
