Skip to content

Adding Holt Winters Functionality to tsa - #3817

Closed
tvanzyl wants to merge 34 commits into
statsmodels:masterfrom
tvanzyl:master
Closed

tvanzyl wants to merge 34 commits into
statsmodels:masterfrom
tvanzyl:master

Conversation

@tvanzyl

@tvanzyl tvanzyl commented Jul 13, 2017

Copy link
Copy Markdown
Contributor

Would like to add the holt winters functionality to tsa.
This includes all the additive, multiplicative, trend, damped and seasonal variations.
Also included are two helper functions for Simple Exponential Smoothing and Holt's Trend Method.

Thanks for all your efforts.

@coveralls

coveralls commented Jul 13, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.813% when pulling 54e9f34 on tvanzyl:master into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 13, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.05%) to 90.81% when pulling f976086 on tvanzyl:master into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 13, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.02%) to 90.84% when pulling f976086 on tvanzyl:master into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 13, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.02%) to 90.84% when pulling 3b62a8e on tvanzyl:master into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 13, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 90.873% when pulling 99237ef on tvanzyl:master into 359f08b on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.005%) to 90.865% when pulling 18b452f on tvanzyl:master into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 13, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.01%) to 90.873% when pulling 18b452f on tvanzyl:master into 359f08b on statsmodels:master.

@bashtage

Copy link
Copy Markdown
Member

See #1489 for reference

Comment thread statsmodels/tsa/holtwinters.py Outdated
try:
from scipy.special import inv_boxcox
except ImportError:
inv_boxcox = lambda x, lam6da: (x**lam6da-1)/lam6da if lam6da != 0 else np.log(x)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is that a 6 in lam6da?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it is the name of the parameter, I just use a "6" instead of a "b", maybe give it another name?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there are some exampels using either lam or lamda

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment thread statsmodels/tsa/holtwinters.py Outdated
"resid", "k"])

def holt_winters(data, alpha=None, beta=None, gamma=None, m=None, h=1, trend=None,
damped=False, seasonal=None, phi=None, optimised=True,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think American English is used in statsmodels.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will change

Comment thread statsmodels/tsa/holtwinters.py Outdated

def holt_winters(data, alpha=None, beta=None, gamma=None, m=None, h=1, trend=None,
damped=False, seasonal=None, phi=None, optimised=True,
boxcoxed=False, remove_bias=False, try_harder=False):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably just boxcox

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try_harder is not a good name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed

Comment thread statsmodels/tsa/holtwinters.py Outdated
Notes
-----
This is a full implementation of the holt winters exponential smoothing as
per [1]. This includes all the unsatble methods as well as the stable methods.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo undstble

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment thread statsmodels/tsa/holtwinters.py Outdated
-----
This is a full implementation of the holt winters exponential smoothing as
per [1]. This includes all the unsatble methods as well as the stable methods.
The implmentaion of the library follows as per the R library as much as possible

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you use the R code? It is not license compatible as far as I know. Or just look at documentation, which is OK.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I never used any R code.

Comment thread statsmodels/tsa/holtwinters.py Outdated
data : array-like
Time series
alpha : float, optional
The alpha value of the simple exponnetial smoothing, if the value is

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed all over

Comment thread statsmodels/tsa/holtwinters.py Outdated
gamma, m, phi, l0, b0, s0, SSE, level,
slope, season, opt, AIC, BIC, AICc, resid, k)

def ses(data, alpha=None, h=1, optimised=True):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ses isn't helpful. Maybe simple_exp_smoothing?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@@ -0,0 +1,96 @@
#!/usr/bin/env python3

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be version agnostic

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I realised once the tests had been run, I was going to have to change a few things.
Trying to figure out what the lowest common denominator will be to get this all working.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


class TestHoltWinters(object):
@classmethod
def setupClass(cls):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use setup_class

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment thread statsmodels/tsa/holtwinters.py Outdated
return max_seen
finally:
warnings.filterwarnings("once")
def holt_mul_dam(x, xi):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This patter of nested function and globals make unit testing really hard since it is difficult to directly test the smallest unit (e.g. a test hat holt_mul_dam works correctly).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@josef-pkt

Copy link
Copy Markdown
Member

I only gave it a very quick look so far.
The main issue I saw is the use of namedtuple. We don't use those because they cannot be changed in future without breaking backwards compatibility. Instead this should use a simple results class, that could also get a plot (plot_forecast) method, for example.

@bashtage

Copy link
Copy Markdown
Member

BTW, I think this is a good idea and there is a lot of demand for this type of function, and so, once ready, it should definitely go in.

1) Stripped all the functions out of the main fucntion
2) Typos etc
3) Tried to find source of backwards compatability issues
4) Changed names of parameters and functions as per request
@tvanzyl

tvanzyl commented Jul 14, 2017

Copy link
Copy Markdown
Contributor Author

Made the changes as per josef-pkt
Added a Result class like the one in seasonal.py

@coveralls

coveralls commented Jul 14, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 90.891% when pulling 87b8e39 on tvanzyl:master into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 14, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 90.891% when pulling fa81468 on tvanzyl:master into 359f08b on statsmodels:master.

@coveralls

coveralls commented Jul 14, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 90.891% when pulling 829d779 on tvanzyl:master into 359f08b on statsmodels:master.

@tvanzyl tvanzyl left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Completed All Changes

@josef-pkt josef-pkt added this to the 0.9 milestone Dec 5, 2017
@josef-pkt

Copy link
Copy Markdown
Member

I would like to merge this this week, especially because of the high demand for this.
(I'm not planning on a full review but try to play with the notebook.)

@tvanzyl

tvanzyl commented Dec 6, 2017

Copy link
Copy Markdown
Contributor Author

@ChadFulton Sorry, not enough time around exams to tackle all of this. Happy to get the functionality in as I just wanted to have something in a statsmodels release to use in my course next year.
Happy to work with you on the PR. You know the framework better than I.
Also want to collaborate on a state space based implementation in then new year. I believe it will fit with the statsmodels framework and will make it easier to get confidence intervals etc.

@coveralls

coveralls commented Dec 6, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-8.9%) to 81.957% when pulling 8440a00 on tvanzyl:master into 359f08b on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 2 alerts - view on lgtm.com

new alerts:

  • 2 for Module-level cyclic import

Comment posted by lgtm.com

@josef-pkt

josef-pkt commented Dec 6, 2017 •

Copy link
Copy Markdown
Member

The notebook looks very good.

(I will add some comments here as a try out a few things in the notebook)

aic and similar should be lower case, see eg. RegressionResult

about notebook:

  • line breaks: some lines can be split to improve readability, e.g. DataFrame generation can have a line breach before columns argument.
  • I think it would be better to use a variation on result for the return by fit in the notebooks instead of fitx, e.g. I usually use resx or res_xxx or results, Kerby often uses rslt. That just help remembering that it is a results instance.

@josef-pkt

Copy link
Copy Markdown
Member

from Chad's comment

Although I know we're trying to mirror Hyndman's package, we should consider using more user-friendly names; e.g. instead of alpha, beta, gamma, maybe smoothing_level, smoothing_slope, smoothing_seasonal, damping_slope, and instead of l0, b0, s_i maybe initial_level, initial_slope, initial_seasons.

I have no idea what any of the Greeks are. Even if we keep those greek letters for now, then they need to be explained somewhere, like a language dictionary. I only checked one docstring and it doesn't mention what each greek parameter stands for.

@josef-pkt josef-pkt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a few review comments for now

Comment thread statsmodels/tsa/holtwinters.py Outdated
opt = res
hwfit = self._predict(h=0, alpha=alpha, beta=beta, gamma=gamma, phi=phi, l0=l0,
b0=b0, s0=s0, use_boxcox=use_boxcox, lamda=lamda, remove_bias=remove_bias)
hwfit.opt = opt

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this attaches to the wrapper instance, and should be corrected to
hwfit._results.opt = opt

_results is the original results instance behind the wrapper

also for consistency with other models we should call it mle_retvals instead of opt

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment thread statsmodels/tsa/holtwinters.py Outdated
# (s0 + gamma) + (b0 + beta) + (l0 + alpha) + phi
k = m * seasoning + 2 * trending + 2 + 1 * damped
AIC = self.nobs * np.log(SSE / self.nobs) + (k) * 2
AICc = AIC + (2 * (k + 2) * (k + 3)) / (self.nobs - k - 3)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's just a temp variable here
but we follow lower case for names of objects except classes also for acronyms.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment thread statsmodels/tsa/holtwinters.py Outdated
'lamda': lamda,
'remove_bias': remove_bias}
hwfit = HoltWintersResults(self, self.params, fittedfcast=fitted, fittedvalues=fitted[:-h - 1],
fcast=fitted[-h - 1:], SSE=SSE, level=level,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's better to rename fcast to fcastvalues in analogy to fittedvalues

(I'm just inspecting a results instance to see what the attributes are.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

},
"outputs": [],
"source": [
"fit1 = ExponentialSmoothing(aust, seasonal_periods=4, trend='add', seasonal='add', use_boxcox=True).fit()\n",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

incorrect usage
use_boxcox has no effect here.
It took me a while to realize that it has to be a fit keyword.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed the **kwargs should ensure we don't let this through in future

@josef-pkt

Copy link
Copy Markdown
Member

params is a dict, which is inconsistent with our methods in general.
I think it's ok in this case given that we don't inherit anything besides datahandling and predict.

Comment thread statsmodels/tsa/holtwinters.py Outdated
"""

def __init__(self, endog, trend=None, damped=False, seasonal=None,
seasonal_periods=None, dates=None, freq=None, missing='none', **kwargs):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should remove the **kwargs here. AFAICS, they are not used in this case, and just swallow without feedback any incorrect keywords

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

if use_boxcox == 'log':
lamda = 0.0
y = boxcox(data, 0.0)
elif use_boxcox:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is missing the case when lamda is already a float.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@josef-pkt

Copy link
Copy Markdown
Member

general pattern: only the results should know about fit results.
Currently the model has params attached, which I guess is unused.

having use_boxcox as fit argument and not as model argument might be a bit fragile. I haven't managed yet to think may way through boxcox forecasting in the code.
There is currently duplicated computation of the boxcox transformation in fit and _predict, AFAICS. Also each call to _predict does the full boxcox transformation

should slope be renamed to trend, to follow eg seasonal_decompose and some statespace models, or is this something different?

@josef-pkt

Copy link
Copy Markdown
Member

general, theoretical question:

I was surprised in the plot that seasonal component is not centered at zero.
How is the constant included or split up between componenets? Is it a fixed rule or does it depend on how the recursive structure or time series iteration is initialized?

@ChadFulton

Copy link
Copy Markdown
Member

@ChadFulton Sorry, not enough time around exams to tackle all of this. Happy to get the functionality in as I just wanted to have something in a statsmodels release to use in my course next year.
Happy to work with you on the PR. You know the framework better than I.
Also want to collaborate on a state space based implementation in then new year. I believe it will fit with the statsmodels framework and will make it easier to get confidence intervals etc.

Thanks for getting all of this setup. We can move slowly, but we're glad to get it in!

I would like to merge this this week, especially because of the high demand for this.

I agree, great!

@coveralls

coveralls commented Dec 7, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-8.9%) to 81.959% when pulling a6ba32f on tvanzyl:master into 359f08b on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 2 alerts - view on lgtm.com

new alerts:

  • 2 for Module-level cyclic import

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

So far, I only looked at the latest changes, and they look good to me. I will try again later today.

I think the greek translation should also go in the docstring, either in notes or in explanation for each parameter. It is useful to have the link between statsmodels names and shortcut names used in the reference(s) if there is a dominant reference or consistent Letters/Greeks across references.
alpha = smoothing_level
beta = smoothing_slope
gamma = smoothing_seasonal
phi = damping_slope

One thing I think I forgot to mention: Result statistics like aic can go into the results class now. They can be computed lazily on demand, see for example linear_model.RegressionResults. fittedvalues and similar are computed in the fit method and cannot be moved to the results class as in RegressionResults.

One more that I did't finish looking at yesterday: Should we already have optimizer options in fit in case the default doesn't work, e.g. just for the minimize case, e.g. minimize_kwds as extra dict in fit arguments?

@josef-pkt

Copy link
Copy Markdown
Member

To check that the notebook examples work with a different dataset, and it does. The forecast looks good. The only time I needed to spend is on getting the pandas index.

with classical airpassenger dataset, which has increasing seasonal amplitude

df_ap = pd.read_csv("AirPassengers.csv")
index = pd.DatetimeIndex(start='1949', end='1960-M12', freq='MS')
ap = pd.Series(df_ap['AirPassengers'].values, index)

res_ap = ExponentialSmoothing(ap, seasonal_periods=12, trend='add', seasonal='add').fit(use_boxcox=True)

ax = ap.plot(figsize=(10,6), marker='o', color='black', title="Forecasts from Holt-Winters' multiplicative method" )
ax.set_ylabel("International visitor night in Australia (millions)")
ax.set_xlabel("Year")
res_ap.fittedvalues.plot(ax=ax, style='--', color='red')
res_ap.forecast(36).plot(ax=ax, style='--', marker='o', color='red', legend=True)
print("Figure 7.6: Forecasting airpassenger using Holt-Winters method with both additive and multiplicative seasonality.")
plt.show()

@josef-pkt

Copy link
Copy Markdown
Member

A plot_forecast method would be nice for quick inspection. AFAIR, we have it in some other models.

I think I'm stopping with reviewing. It seems to work well out of the box and we can add or change things during the next release cycle.
We need to rebase this and push the rebased version to a new PR so the history in this PR stays unchanged. There are a few commits that need squashing, especially those with the full notebook output. I can do the interactive rebase, unless you are familiar enough with git to do it.

@josef-pkt

Copy link
Copy Markdown
Member

for minimal squashing:
"Added a jupyter notebook Oct 5 adds" full notebook
second commit after "fixed the unit tests and cleared the jupyter notebook" clears notebook

"fixed the notebook with the latest changes to the api as requested" on Dec 6 changes to full notebook
next commit clears notebool

@josef-pkt

Copy link
Copy Markdown
Member

I merged the rebased version in PR #4176

@tvanzyl Thanks for this extension, many users will be glad this is in
@bashtage @ChadFulton Thanks for reviewing

It's open for extensions and some refactoring for the next release.

@astrojuanlu

Copy link
Copy Markdown

Awesome! When is the next stable release? :)

@josef-pkt

Copy link
Copy Markdown
Member

When is the next stable release?

My guess is now mid January.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants