Last active
December 4, 2020 21:36
-
-
Save mvervuurt/2f6cba57deb97582e7534a8f36327662 to your computer and use it in GitHub Desktop.
Python Time Series ETS Decomposition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Assume Pandas DataFrame or Series | |
#moving average | |
df.ts_col.rolling(window=6).mean() #example 6 months rolling window | |
df.ts_col.rolling(window=12).mean() #example 12 months rolling window | |
#exponentially weighted moving average | |
df.ts_col.ewm(spane=12).mean() | |
from statsmodels.tsa.holtwinters import SimpleExpSmoothing | |
span = 12 | |
alpha = 2/(span+1) | |
df['SES12']=SimpleExpSmoothing(df['Thousands of Passengers']).fit(smoothing_level=alpha,optimized=False).fittedvalues.shift(-1) | |
#hodrick prescot filter | |
from statsmodels.tsa.filters.hp_filter import hpfilter | |
gdp_cycle, gdp_trend = hpfilter(df['realgdp'], lamb=1600) | |
#seasonal decomposition | |
#remember to freq because statsmodels uses it | |
df.index.freq = 'MS' | |
from statsmodels.tsa.seasonal import seasonal_decompose | |
result = seasonal_decompose(airline['Thousands of Passengers'], model='multiplicative') # model='mul' also works | |
result.plot(); | |
#double exponential smoothing | |
from statsmodels.tsa.holtwinters import ExponentialSmoothing | |
#additive trend | |
df['DESadd12'] = ExponentialSmoothing(df['Thousands of Passengers'], trend='add').fit().fittedvalues.shift(-1) | |
#multiplicative trend | |
df['DESmul12'] = ExponentialSmoothing(df['Thousands of Passengers'], trend='mul').fit().fittedvalues.shift(-1) | |
#triple exponential smoothing | |
# trend is linear and seasonality is additive | |
df['TESadd12'] = ExponentialSmoothing(df['Thousands of Passengers'],trend='add',seasonal='add',seasonal_periods=12).fit().fittedvalues | |
# trend is exponential and seasonality is multiplicative | |
df['TESmult12'] = ExponentialSmoothing(df['Thousands of Passengers'],trend='mul',seasonal='mul',seasonal_periods=12).fit().fittedvalues |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment