Seasonal Decomposition of Time Series by Loess with Python
Question: I'm trying to do with Python what I the STL function on R.

The R commands are

    
    
    fit <- stl(elecequip, s.window=5)
    plot(fit)
    

How do I do this in Python? I investigated that statmodels.tsa has some time
series analysis functions but I could specifically found "Seasonal
Decomposition of Time Series by Loess" in the documentation. Similarly on
Python.org there is a library called timeseries 0.5.0, but this doesn't have
documentation and it's home site looks down. I know that there is an option
with rpy2 using a wrapper, but I don't know how to use the wrapper.

Thanks.


Answer: 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](https://github.com/andreas-h/pyloess/blob/master/mpyloess.py). It
is based on the original fortran code that was available with [this
paper](http://www.wessa.net/download/stl.pdf). 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](http://pandas.pydata.org/) DataFrame and
then call [StatsModels](http://statsmodels.sourceforge.net/)
`tsa.seasonal_decompose`. See the [following
example](http://statsmodels.sourceforge.net/stable/release/version0.6.html?highlight=seasonal#seasonal-
decomposition):

    
    
    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()
    

![Three plots produced from above input](http://i.stack.imgur.com/6C0tS.jpg)

You can then recover the individual components of the decomposition from:

    
    
    res.resid
    res.seasonal
    res.trend
    

I hope this helps!

