irongit
time-series-cookbook/ch1/1.05_decomposing_a_time_series.py
53 lines1.7 KBPython
1"""
2# Finding trend, seasonality, and remainder.
3- Trend: Long term change.
4- Seasonality: Repeated patterns over fixed interval such as daily.
5- Remainder (irregular): Left from removing trend and seasonal components.
6
7# 2 methods
81. Classic method: Can be multiplicative or additive where the sum/product of
9 trend, seasonality, and remainder recreate the original data
10 - Logarithmic data is the same for both
11 - Trend is estimated with a moving average
12 - Seasonality estimated by averaging values for each period
132. Local regression: STL/MSTL uses LOESS (locally weighted scatterplot smothing)
14 to be more flexible
15
16Removing seasonality improves neural network forcasting performance
17"""
18import os
19from statsmodels.tsa.seasonal import seasonal_decompose, STL, MSTL
20import pandas as pd
21import matplotlib.pyplot as plt
22
23# Chart config
24plt.rcParams['figure.figsize'] = (12, 6)
25
26# Ensure assets directory
27os.makedirs("assets", exist_ok=True)
28
29# Load solar data
30data = pd.read_csv(
31 "../assets/datasets/time_series_solar.csv",
32 parse_dates=["Datetime"],
33 index_col="Datetime",
34)
35series = data["Incoming Solar"]
36
37# Resample to daily
38series_daily = series.resample("D").sum()
39
40# Perform yearly seasonal decomposition with classical method
41result = seasonal_decompose(x=series_daily, model='additive', period=365)
42result.plot()
43plt.savefig("assets/classical_decomposition.png")
44
45# Perform yearly decomposition with Seasonal Trend decomposition using LOESS (STL)
46result = STL(endog=series_daily, period=365).fit()
47result.plot()
48plt.savefig("assets/stl_decomposition.png")
49
50# Perform yearly decomposition with mutliple STL (MSTL)
51result = MSTL(endog=series_daily, periods=(7, 365)).fit()
52result.plot()
53plt.savefig("assets/mstl_decomposition.png")