Optimized Theta Model
Stepbystep guide on using the OptimizedTheta Model
with Statsforecast
.
Table of Contents
 Introduction
 Optimized Theta Model (OTM)
 Loading libraries and data
 Explore data with the plot method
 Split the data into training and testing
 Implementation of OptimizedTheta with StatsForecast
 Crossvalidation
 Model evaluation
 References
Introduction
The optimized Theta model is a time series forecasting method that is based on the decomposition of the time series into three components: trend, seasonality and noise. The model then forecasts the longterm trend and seasonality, and uses the noise to adjust the shortterm forecasts. The optimized Theta model has been shown to be more accurate than other time series forecasting methods, especially for time series with complex trends and seasonality.
The optimized Theta model was developed by Athanasios N. Antoniadis and Nikolaos D. Tsonis in 2013. The model is based on the Theta forecasting method, which was developed by George E. P. Box and Gwilym M. Jenkins in 1976. Theta method is a time series forecasting method that is based on the decomposition of the time series into three components: trend, seasonality, and noise. The Theta model then forecasts the longterm trend and seasonality, and uses the noise to adjust the shortterm forecasts.
The Theta Optimized model improves on the Theta method by using an optimization algorithm to find the best parameters for the model. The optimization algorithm is based on the Akaike loss function (AIC), which is a measure of the goodness of fit of a model to the data. The optimization algorithm looks for the parameters that minimize the AIC function.
The optimized Theta model has been shown to be more accurate than other time series forecasting methods, especially for time series with complex trends and seasonality. The model has been used to forecast a variety of time series, including sales, production, prices, and weather.
Below are some of the benefits of the optimized Theta model:
 It is more accurate than other time series forecasting methods.
 It’s easy to use.
 Can be used to forecast a variety of time series.
 It is flexible and can be adapted to different scenarios.
If you are looking for an easytouse and accurate time series forecasting method, the Optimized Theta model is a good choice.
The optimized Theta model can be applied in a variety of areas, including:
 Sales: The optimized Theta model can be used to forecast sales of products or services. This can help companies make decisions about production, inventory, and marketing.
 Production: The optimized Theta model can be used to forecast the production of goods or services. This can help companies ensure they have the capacity to meet demand and avoid overproduction.
 Prices: The optimized Theta model can be used to forecast the prices of goods or services. This can help companies make decisions about pricing and marketing strategy.
 Weather: The optimized Theta model can be used to forecast the weather. This can help companies make decisions about agricultural production, travel planning and risk management.
 Other: The optimized Theta model can also be used to forecast other types of time series, including traffic, energy demand, and population.
The Optimized Theta model is a powerful tool that can be used to improve the accuracy of time series forecasts. It is easy to use and can be applied to a variety of areas. If you are looking for a tool to improve your time series forecasts, the Optimized Theta model is a good choice.
Optimized Theta Model (OTM)
Assume that either the time series $Y_1, \cdots Y_n$ is nonseasonal or it has been seasonally adjusted using the multiplicative classical decomposition approach.
Let $X_t$ be the linear combination of two theta lines,
where $\omega \in [0,1]$ is the weight parameter. Assuming that $\theta_1 <1$ and $\theta_2 \geq 1$, the weight $\omega$ can be derived as
It is straightforward to see from Eqs. (1), (2) that $X_t=Y_t, \ t=1, \cdots n$ i.e., the weights are calculated properly in such a way that Eq. (1) reproduces the original series.
Theorem 1: Let $\theta_1 <1$ and $\theta_2 \geq 1$. We will prove that
 the linear system given by $X_t=Y_t$ for all $t=1, \cdots, n$, where $X_t$ is given by Eq.(4), has the single solution
$\omega= (\theta_2 1)/(\theta_2  \theta_1)$
 the error of choosing a nonoptimal weight $\omega_{\delta} =\omega + \delta$ is proportional to the error for a simple linear regression model.
In Theorem 1 , we prove that the solution is unique and that the error from not choosing the optimal weights ($\omega$ and $1\omega$) s proportional to the error of a linear regression model. As a consequence, the STheta method is given simply by setting $\theta_1=0$ and $\theta_2=2$ while from Eq. (2) we get $\omega=0.5$. Thus, Eqs. (1), (2) allow us to construct a generalisation of the Theta model that maintains the recomposition propriety of the original time series for any theta lines $\text{Z}_t (\theta_1)$ and $\text{Z}_t (\theta_2)$.
In order to maintain the modelling of the longterm component and retain a fair comparison with the STheta method, in this work we fix $\theta_1=0$ and focus on the optimisation of the shortterm component, $\theta_2=0$ with $\theta \geq 1$. Thus, $\theta$ is the only parameter that requires estimation so far. The theta decomposition is now given by
$Y_t=(1\frac{1}{\theta}) (\text{A}_n+\text{B}_n t)+ \frac{1}{\theta} \text{Z}_t (\theta), \ t=1, \cdots , n$
The $h$ stepahead forecasts calculated at origin are given by
where $\tilde {\text{Z}}_{n+hn} (\theta)=\tilde {\text{Z}}_{n+1n} (\theta)=\alpha \sum_{i=0}^{n1}(1\alpha)^i \text{Z}_{ni}(\theta)+(1\alpha)^n \ell_{0}^{*}$ is the extrapolation of $\text{Z}_t(\theta)$ by an SES model with $\ell_{0}^{*} \in \mathbb{R}$ as the initial level parameter and $\alpha \in (0,1)$ as the smoothing parameter. Note that for $\theta=2$ Eq. (3) corresponds to Step 4 of the STheta algorithm. After some algebra, we can write
where $\ell_{t}=\alpha Y_t +(1\alpha) \ell_{t1}$ for $t=1, \cdots, n$ and $\ell_{0}=\ell_{0}^{*}/\theta$.
In the light of Eqs. (3), (4), we suggest four stochastic approaches. These approaches differ due to the parameter $\theta$ which may be either fixed at two or optimised, and the coefficients $\text{A}_n$ and $\text{B}_n$, which can be either fixed or dynamic functions. To formulate the state space models, it is helpful to adopt $\mu_{t}$ as the onestepahead forecast at origin $t1$ and $\varepsilon_{t}$ as the respective additive error, i.e., $\varepsilon_{t}=Y_t  \mu_{t}$ if $\mu_{t}= \hat Y_{tt1}$. We assume $\{ \varepsilon_{t} \}$ to be a Gaussian white noise process with mean zero and variance $\sigma^2$.
More on Optimised Theta models
Let $\text{A}_n$ and $\text{B}_n$ be fixed coefficients for all $t=1, \cdots, n$ so that Eqs. (3), (4) configure the state space model given by
with parameters $\ell_{0} \in \mathbb{R}$, $\alpha \in (0,1)$ and $\theta \in [1,\infty)$ . The parameter $\theta$ is to be estimated along with $\alpha$ and $\ell_{0}$ We call this the optimised Theta model (OTM).
The $h$stepahead forecast at origin $n$ is given by
$\hat Y_{n+hn}=E[Y_{n+h}Y_1,\cdots, Y_n]=\ell_{n}+(1\frac{1}{\theta}) \{(1\alpha)^n \text{A}_n +[(h1) + \frac{1(1\alpha)^{n+1}}{\alpha}] \text{B}_n \}$
which is equivalent to Eq. (3). The conditional variance $\text{Var}[Y_{n+h}Y_1, \cdots, Y_n]=[1+(h1)\alpha^2]\sigma^2$ can be computed easily from the state space model. Thus, the $(1\alpha)\%$ prediction interval for $Y_{n+h}$ is given by $\hat Y_{n+hn} \ \pm \ q_{1\alpha/2} \sqrt{[1+(h1)\alpha^2 ]\sigma^2 }$
For $\theta=2$ OTM reproduces the forecasts of the STheta method; hereafter, we will refer to this particular case as the standard Theta model (STM).
Theorem 2: The SESd $(\ell_{0}^{**}, \alpha, b)$ model, where $\ell_{0}^{**} \in \mathbb{R}, \alpha \in (0,1)$ and $b \in \mathbb{R}$ is equivalent to $\text{OTM} (\ell_{0}, \alpha, \theta )$ where $\ell_{0} \in \mathbb{R}$ and $\theta \geq 1$, if
$\ell_{0}^{**} = \ell_{0} + (1 \frac{1}{\theta} )A_n \ \ and \ \ b=(1\frac{1}{\theta} )B_n$
In Theorem 2, we show that OTM is mathematically equivalent to the SESd model. As a corollary of Theorem 2, STM is mathematically equivalent to SESd with $b=\frac{1}{2} \text{B}_n$. Therefore, for $\theta=2$ the corollary also reconfirms the H&B result on the relationship between STheta and the SESd model.
Loading libraries and data
Tip
Statsforecast will be needed. To install, see instructions.
Next, we import plotting libraries and configure the plotting style.
Read Data
month  production  

0  19620101  589 
1  19620201  561 
2  19620301  640 
3  19620401  656 
4  19620501  727 
The input to StatsForecast is always a data frame in long format with three columns: unique_id, ds and y:

The
unique_id
(string, int or category) represents an identifier for the series. 
The
ds
(datestamp) column should be of a format expected by Pandas, ideally YYYYMMDD for a date or YYYYMMDD HH:MM:SS for a timestamp. 
The
y
(numeric) represents the measurement we wish to forecast.
ds  y  unique_id  

0  19620101  589  1 
1  19620201  561  1 
2  19620301  640  1 
3  19620401  656  1 
4  19620501  727  1 
We can see that our time variable (ds)
is in an object format, we need
to convert to a date format
Explore Data with the plot method
Plot some series using the plot method from the StatsForecast class. This method prints a random series from the dataset and is useful for basic EDA.
Autocorrelation plots
Decomposition of the time series
How to decompose a time series and why?
In time series analysis to forecast new values, it is very important to know past data. More formally, we can say that it is very important to know the patterns that values follow over time. There can be many reasons that cause our forecast values to fall in the wrong direction. Basically, a time series consists of four components. The variation of those components causes the change in the pattern of the time series. These components are:
 Level: This is the primary value that averages over time.
 Trend: The trend is the value that causes increasing or decreasing patterns in a time series.
 Seasonality: This is a cyclical event that occurs in a time series for a short time and causes shortterm increasing or decreasing patterns in a time series.
 Residual/Noise: These are the random variations in the time series.
Combining these components over time leads to the formation of a time series. Most time series consist of level and noise/residual and trend or seasonality are optional values.
If seasonality and trend are part of the time series, then there will be effects on the forecast value. As the pattern of the forecasted time series may be different from the previous time series.
The combination of the components in time series can be of two types: * Additive * Multiplicative
###Additive time series
If the components of the time series are added to make the time series. Then the time series is called the additive time series. By visualization, we can say that the time series is additive if the increasing or decreasing pattern of the time series is similar throughout the series. The mathematical function of any additive time series can be represented by: $y(t) = level + Trend + seasonality + noise$
Multiplicative time series
If the components of the time series are multiplicative together, then the time series is called a multiplicative time series. For visualization, if the time series is having exponential growth or decline with time, then the time series can be considered as the multiplicative time series. The mathematical function of the multiplicative time series can be represented as.
$y(t) = Level * Trend * seasonality * Noise$
Additive
Multiplicative
Split the data into training and testing
Let’s divide our data into sets 1. Data to train our
Optimized Theta model
. 2. Data to test our model
For the test data we will use the last 12 months to test and evaluate the performance of our model.
Now let’s plot the training data and the test data.
Implementation of OptimizedTheta with StatsForecast
To also know more about the parameters of the functions of the
OptimizedTheta Model
, they are listed below. For more information,
visit the
documentation.
Load libraries
Instantiating Model
Import and instantiate the models. Setting the argument is sometimes
tricky. This article on Seasonal
periods by the
master, Rob Hyndmann, can be useful for season_length
.
We fit the models by instantiating a new StatsForecast object with the following parameters:
models: a list of models. Select the models you want from models and import them.

freq:
a string indicating the frequency of the data. (See pandas’ available frequencies.) 
n_jobs:
n_jobs: int, number of jobs used in the parallel processing, use 1 for all cores. 
fallback_model:
a model to be used if a model fails.
Any settings are passed into the constructor. Then you call its fit method and pass in the historical data frame.
Fit the Model
Let’s see the results of our Optimized Theta Model (OTM)
. We can
observe it with the following instruction:
Let us now visualize the residuals of our models.
As we can see, the result obtained above has an output in a dictionary,
to extract each element from the dictionary we are going to use the
.get()
function to extract the element and then we are going to save
it in a pd.DataFrame()
.
residual Model  

0  271.899414 
1  114.671692 
2  4.768066 
…  … 
153  60.233887 
154  92.472839 
155  44.143982 
Forecast Method
If you want to gain speed in productive settings where you have multiple
series or models we recommend using the
StatsForecast.forecast
method instead of .fit
and .predict
.
The main difference is that the .forecast
doest not store the fitted
values and is highly scalable in distributed environments.
The forecast method takes two arguments: forecasts next h
(horizon)
and level
.

h (int):
represents the forecast h steps into the future. In this case, 12 months ahead. 
level (list of floats):
this optional parameter is used for probabilistic forecasting. Set the level (or confidence percentile) of your prediction interval. For example,level=[90]
means that the model expects the real value to be inside that interval 90% of the times.
The forecast object here is a new data frame that includes a column with
the name of the model and the y hat values, as well as columns for the
uncertainty intervals. Depending on your computer, this step should take
around 1min. (If you want to speed things up to a couple of seconds,
remove the AutoModels like
ARIMA
and
Theta
)
ds  OptimizedTheta  

unique_id  
1  19750101  839.682800 
1  19750201  802.071838 
1  19750301  896.117126 
…  …  … 
1  19751001  824.135498 
1  19751101  795.691162 
1  19751201  833.316345 
Let’s visualize the fitted values
ds  y  OptimizedTheta  

unique_id  
1  19620101  589.0  860.899414 
1  19620201  561.0  675.671692 
1  19620301  640.0  635.231934 
1  19620401  656.0  614.731323 
1  19620501  727.0  609.770752 
Adding 95% confidence interval with the forecast method
ds  OptimizedTheta  OptimizedThetalo95  OptimizedThetahi95  

unique_id  
1  19750101  839.682800  742.509583  955.414307 
1  19750201  802.071838  643.581360  945.119263 
1  19750301  896.117126  710.785217  1065.057495 
…  …  …  …  … 
1  19751001  824.135498  555.948975  1084.320312 
1  19751101  795.691162  503.148010  1036.519531 
1  19751201  833.316345  530.259949  1106.636963 
unique_id  ds  OptimizedTheta  

0  1  19750101  839.682800 
1  1  19750201  802.071838 
2  1  19750301  896.117126 
…  …  …  … 
9  1  19751001  824.135498 
10  1  19751101  795.691162 
11  1  19751201  833.316345 
ds  y  unique_id  OptimizedTheta  

0  19750101  834  1  839.682800 
1  19750201  782  1  802.071838 
2  19750301  892  1  896.117126 
…  …  …  …  … 
9  19751001  827  1  824.135498 
10  19751101  797  1  795.691162 
11  19751201  843  1  833.316345 
Predict method with confidence interval
To generate forecasts use the predict method.
The predict method takes two arguments: forecasts the next h
(for
horizon) and level
.

h (int):
represents the forecast h steps into the future. In this case, 12 months ahead. 
level (list of floats):
this optional parameter is used for probabilistic forecasting. Set the level (or confidence percentile) of your prediction interval. For example,level=[95]
means that the model expects the real value to be inside that interval 95% of the times.
The forecast object here is a new data frame that includes a column with the name of the model and the y hat values, as well as columns for the uncertainty intervals.
This step should take less than 1 second.
ds  OptimizedTheta  

unique_id  
1  19750101  839.682800 
1  19750201  802.071838 
1  19750301  896.117126 
…  …  … 
1  19751001  824.135498 
1  19751101  795.691162 
1  19751201  833.316345 
ds  OptimizedTheta  OptimizedThetalo80  OptimizedThetahi80  OptimizedThetalo95  OptimizedThetahi95  

unique_id  
1  19750101  839.682800  766.665955  928.326233  742.509583  955.414307 
1  19750201  802.071838  704.290100  899.335876  643.581360  945.119263 
1  19750301  896.117126  761.334717  1007.408630  710.785217  1065.057495 
…  …  …  …  …  …  … 
1  19751001  824.135498  623.904114  996.567322  555.948975  1084.320312 
1  19751101  795.691162  576.546753  975.490967  503.148010  1036.519531 
1  19751201  833.316345  606.713989  1033.886230  530.259949  1106.636963 
We can join the forecast result with the historical data using the
pandas function pd.concat()
, and then be able to use this result for
graphing.
y  unique_id  OptimizedTheta  OptimizedThetalo80  OptimizedThetahi80  OptimizedThetalo95  OptimizedThetahi95  

ds  
19620101  589.0  1  NaN  NaN  NaN  NaN  NaN 
19620201  561.0  1  NaN  NaN  NaN  NaN  NaN 
19620301  640.0  1  NaN  NaN  NaN  NaN  NaN 
…  …  …  …  …  …  …  … 
19751001  NaN  NaN  824.135498  623.904114  996.567322  555.948975  1084.320312 
19751101  NaN  NaN  795.691162  576.546753  975.490967  503.148010  1036.519531 
19751201  NaN  NaN  833.316345  606.713989  1033.886230  530.259949  1106.636963 
Now let’s visualize the result of our forecast and the historical data of our time series, also let’s draw the confidence interval that we have obtained when making the prediction with 95% confidence.
Let’s plot the same graph using the plot function that comes in
Statsforecast
, as shown below.
Crossvalidation
In previous steps, we’ve taken our historical data to predict the future. However, to asses its accuracy we would also like to know how the model would have performed in the past. To assess the accuracy and robustness of your models on your data perform CrossValidation.
With time series data, Cross Validation is done by defining a sliding window across the historical data and predicting the period following it. This form of crossvalidation allows us to arrive at a better estimation of our model’s predictive abilities across a wider range of temporal instances while also keeping the data in the training set contiguous as is required by our models.
The following graph depicts such a Cross Validation Strategy:
Perform time series crossvalidation
Crossvalidation of time series models is considered a best practice but most implementations are very slow. The statsforecast library implements crossvalidation as a distributed operation, making the process less timeconsuming to perform. If you have big datasets you can also perform Cross Validation in a distributed cluster using Ray, Dask or Spark.
In this case, we want to evaluate the performance of each model for the
last 5 months (n_windows=5)
, forecasting every second months
(step_size=12)
. Depending on your computer, this step should take
around 1 min.
The cross_validation method from the StatsForecast class takes the following arguments.

df:
training data frame 
h (int):
represents h steps into the future that are being forecasted. In this case, 12 months ahead. 
step_size (int):
step size between each window. In other words: how often do you want to run the forecasting processes. 
n_windows(int):
number of windows used for cross validation. In other words: what number of forecasting processes in the past do you want to evaluate.
The crossvaldation_df object is a new data frame that includes the following columns:
unique_id:
index. If you dont like working with index just run crossvalidation_df.resetindex()ds:
datestamp or temporal indexcutoff:
the last datestamp or temporal index for the n_windows.y:
true value"model":
columns with the model’s name and fitted value.
ds  cutoff  y  OptimizedTheta  

unique_id  
1  19720101  19711201  826.0  828.836365 
1  19720201  19711201  799.0  792.592346 
1  19720301  19711201  890.0  883.269592 
…  …  …  …  … 
1  19741001  19731201  812.0  812.183838 
1  19741101  19731201  773.0  783.898376 
1  19741201  19731201  813.0  821.124329 
Model Evaluation
We can now compute the accuracy of the forecast using an appropiate
accuracy metric. Here we’ll use the Root Mean Squared Error (RMSE). To
do this, we first need to install datasetsforecast
, a Python library
developed by Nixtla that includes a function to compute the RMSE.
The function to compute the RMSE takes two arguments:
 The actual values.
 The forecasts, in this case,
Optimized Theta Model (OTM)
.
As you have noticed, we have used the cross validation results to perform the evaluation of our model.
Now we are going to evaluate our model with the results of the
predictions, we will use different types of metrics
MAE, MAPE, MASE, RMSE, SMAPE
to evaluate the accuracy
.
mae  mape  mase  rmse  smape  

OptimizedTheta  6.740209  0.782753  0.30312  8.701501  0.778689 
Acknowledgements
We would like to thank Naren Castellon for writing this tutorial.
References
 Kostas I. Nikolopoulos, Dimitrios D. Thomakos. Forecasting with the Theta MethodTheory and Applications. 2019 John Wiley & Sons Ltd.
 Jose A. Fiorucci, Tiago R. Pellegrini, Francisco Louzada, Fotios Petropoulos, Anne B. Koehler (2016). “Models for optimising the theta method and their relationship to state space models”. International Journal of Forecasting.
 Nixtla Parameters.
 Pandas available frequencies.
 Rob J. Hyndman and George Athanasopoulos (2018). “Forecasting principles and practice, Time series crossvalidation”..
 Seasonal periods Rob J Hyndman.