Seasonal Decomposition Of Time Series By Loess With Python
Solution 1:
I've been having a similar issue and am trying to find the best path forward.
Here is a github repo for an STL decomposition based on the Loess procedure. It is based on the original fortran code that was available with this paper. It is really just a python wrapper around the original Fortran code, so you know its likely works well and isn't buggy.
If you want something more Python centric and are willing to go with a slightly simpler decomposition routine, StatsModels has one:
Try moving your data into a Pandas DataFrame and then call StatsModelstsa.seasonal_decompose
. See the following example:
import statsmodels.api as sm
dta = sm.datasets.co2.load_pandas().data
# deal with missing values. see issue
dta.co2.interpolate(inplace=True)
res = sm.tsa.seasonal_decompose(dta.co2)
resplot = res.plot()
You can then recover the individual components of the decomposition from:
res.resid
res.seasonal
res.trend
I hope this helps!
Solution 2:
You can also call R from python using rpy2
from rpy2.robjects import r
def decompose(series, frequency, s_window, **kwargs):
df = pd.DataFrame()
df['date'] = series.index
s = [x for x in series.values]
length = len(series)
s = r.ts(s, frequency=frequency)
decomposed = [x for x in r.stl(s, s_window, **kwargs).rx2('time.series')]
df['observed'] = series.values
df['trend'] = decomposed[length:2*length]
df['seasonal'] = decomposed[0:length]
df['residual'] = decomposed[2*length:3*length]
returndf
The above function assumes that your series has a datetime index. It returns a dataframe with the individual components that you can then graph with your favorite graphing library.
You can pass the parameters for stl seen here, but change any period to underscore, for example the positional argument in the above function is s_window, but in the above link it is s.window. Also, I found some of the above code on this repository.
Post a Comment for "Seasonal Decomposition Of Time Series By Loess With Python"