How to extract the trend component from TBATS forecast (in python)?

173 Views Asked by At

I'm trying to use TBATS to forecast a very simple times series (as suggested here).This is the code I'm using:

#imports
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from tbats import BATS, TBATS

#build a time series
t_max = 500
np.random.seed(2342)
t = np.array(range(0, t_max))

y = 5 * np.sin(t * 2 * np.pi / 7) + \
    2 * np.cos(t * 2 * np.pi / 30.5) + \
    ((t / 20) ** 1.5 + np.random.normal(size = t_max) * t / 50) + 10

# Create a train-test set. The forecast begins at t_fcst + 1
t_fcst = int(t_max * .75)

# this is how long we want to forecast in the future
forecast_period = t_max - t_fcst

train = y[:t_fcst]
t_train = t[:t_fcst]

test  = y[-forecast_period:]
t_test = t[-forecast_period:]

# Create estimator
estimator = TBATS(seasonal_periods=[7, 30.5], use_trend = True)

# Fit model
fitted_model = estimator.fit(train)

y = fitted_model.forecast(steps = forecast_period)

fig, ax = plt.subplots(figsize = (14, 8))

ax.plot(t_train, train, label = 'Train')
ax.plot(t_test,  test, label = 'Test')
ax.plot(t_test,  y, label = 'Forecast')

ax.legend(loc="upper left")

And this is what I get:

enter image description here

If instead of:

estimator = TBATS(seasonal_periods=[7, 30.5], use_trend = True)

I use:

estimator = TBATS(seasonal_periods=[7, 30.5], use_trend = False)

This is what I get:

enter image description here

Any idea what I'm doing wrong? Thanks

0

There are 0 best solutions below