Decomposition & Smoothing#
statista.time_series.decomposition
#
Decomposition and smoothing mixin for TimeSeries.
Decomposition
#
Bases: _TimeSeriesStub
Time series decomposition and smoothing methods.
Source code in src/statista/time_series/decomposition.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | |
classical_decompose(period=None, model='additive', column=None, plot=True, **kwargs)
#
Classical seasonal decomposition using moving averages.
Decomposes the time series into trend, seasonal, and residual components.
- Additive: Y(t) = Trend(t) + Seasonal(t) + Residual(t)
- Multiplicative: Y(t) = Trend(t) * Seasonal(t) * Residual(t)
Implemented from scratch (no statsmodels dependency).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period
|
int
|
Length of the seasonal cycle (e.g., 12 for monthly data with annual seasonality, 7 for daily data with weekly seasonality). Required — there is no auto-detection. |
None
|
model
|
str
|
"additive" or "multiplicative". Default "additive". |
'additive'
|
column
|
str
|
Column to decompose. If None, uses first column. |
None
|
plot
|
bool
|
Whether to produce a 4-panel decomposition plot. Default True. |
True
|
**kwargs
|
Any
|
Passed to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[DataFrame, tuple[Figure, Axes] | None]
|
(decomposition_df, (fig, axes)) or (decomposition_df, None). decomposition_df has columns: observed, trend, seasonal, residual. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If period is None or data length < 2 * period. |
Examples:
Decompose a synthetic monthly series with trend and seasonality:
>>> import numpy as np
>>> from statista.time_series import TimeSeries
>>> np.random.seed(42)
>>> t = np.arange(120)
>>> seasonal = 5 * np.sin(2 * np.pi * t / 12)
>>> trend = 0.1 * t
>>> data = trend + seasonal + np.random.randn(120) * 0.5
>>> ts = TimeSeries(data)
>>> result, _ = ts.classical_decompose(period=12, plot=False)
>>> list(result.columns)
['observed', 'trend', 'seasonal', 'residual']
>>> result.shape
(120, 4)
>>> round(float(result["trend"].dropna().mean()), 4)
5.8866
Verify seasonal component captures the pattern:
Decompose a shorter series with stronger trend:
>>> np.random.seed(42)
>>> t2 = np.arange(48)
>>> data2 = 10 + 0.5 * t2 + 3 * np.sin(2 * np.pi * t2 / 12) + np.random.randn(48) * 0.3
>>> ts2 = TimeSeries(data2)
>>> result2, _ = ts2.classical_decompose(period=12, plot=False)
>>> round(float(result2["trend"].iloc[24]), 4)
21.3941
References
Persons, W.M. (1919). Indices of business conditions. Review of Economics and Statistics, 1(1), 5-107.
Source code in src/statista/time_series/decomposition.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
smooth(method='moving_average', window=10, **params)
#
Apply smoothing to the time series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Smoothing method. - "moving_average": Centered moving average via pandas rolling. - "exponential": Exponential weighted moving average via pandas ewm. - "savgol": Savitzky-Golay filter (preserves peaks better than MA). Extra param: polyorder (default 2). |
'moving_average'
|
window
|
int
|
Window size. For savgol, must be odd. Default 10. |
10
|
**params
|
Any
|
Method-specific parameters (e.g., polyorder for savgol). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
TimeSeries |
Any
|
New TimeSeries with smoothed values. Same index as original. |
Examples:
Moving average smoothing (NaN at edges where window is incomplete):
>>> import numpy as np
>>> from statista.time_series import TimeSeries
>>> np.random.seed(42)
>>> ts = TimeSeries(np.random.randn(100))
>>> smoothed = ts.smooth(method="moving_average", window=10)
>>> smoothed.shape
(100, 1)
>>> round(float(smoothed.dropna().iloc[0, 0]), 4)
0.4481
Exponential weighted moving average (no NaN values):
>>> np.random.seed(42)
>>> ts2 = TimeSeries(np.random.randn(100))
>>> smoothed2 = ts2.smooth(method="exponential", window=10)
>>> round(float(smoothed2.iloc[0, 0]), 4)
0.4967
>>> round(float(smoothed2.iloc[2, 0]), 4)
0.3486
Savitzky-Golay filter preserves peaks better (reduces std less aggressively):
>>> np.random.seed(42)
>>> ts3 = TimeSeries(np.random.randn(100))
>>> smoothed3 = ts3.smooth(method="savgol", window=11, polyorder=2)
>>> round(float(smoothed3.iloc[0, 0]), 4)
0.2353
>>> round(float(smoothed3.values.std() / ts3.values.std()), 4)
0.4354
Source code in src/statista/time_series/decomposition.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | |
envelope(window=30, lower_pct=5, upper_pct=95, column=None, **kwargs)
#
Plot the time series with rolling percentile envelope bands.
Shows the natural variability range of the data over a rolling window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Rolling window size. Default 30. |
30
|
lower_pct
|
float
|
Lower percentile for the band (0-100). Default 5. |
5
|
upper_pct
|
float
|
Upper percentile for the band (0-100). Default 95. |
95
|
column
|
str
|
Column to plot. If None, uses first column. |
None
|
**kwargs
|
Any
|
Passed to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[Figure, Axes]
|
(Figure, Axes) |
Examples:
>>> import numpy as np
>>> from statista.time_series import TimeSeries
>>> ts = TimeSeries(np.random.randn(200))
>>> fig, ax = ts.envelope(window=20)