Forecasting Models
Forecasting Models
In time series forecasting, a moving average (MA) is a commonly used method for
smoothing out short-term fluctuations and highlighting longer-term trends or cycles. The
moving average is calculated by taking the average of a specified number of data points
within a time series. It is particularly useful for identifying trends and seasonality in the
data.
There are different types of moving averages, such as simple moving average (SMA),
weighted moving average (WMA), and exponential moving average (EMA), each with its
own characteristics and applications.
Here's a simple Python code example for calculating a simple moving average (SMA)
using the pandas library:
import pandas as pd
# Sample time series data
data = {'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'],
'value': [10, 15, 20, 25, 30]}
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
# Calculate simple moving average with window size 3
df['SMA_3'] = df['value'].rolling(window=3).mean()
print(df)
As for further reading, here are some links that might be helpful:
Simple Exponential Smoothing (SES) is a popular method used in time series forecasting
to predict future data points based on the historical data. It is a technique that assigns
exponentially decreasing weights over time to the historical data, giving more weight to
recent observations while gradually decreasing the influence of older observations.
The SES method uses a single smoothing factor (alpha) to give different weights to the
observations. The forecast at time t+1 is a weighted average of the actual observation at
time t and the forecast for time t. The formula for Simple Exponential Smoothing is:
Where:
Simple Exponential Smoothing (SES) is a basic time series forecasting method that
assigns exponentially decreasing weights over time. It is particularly useful for forecasting
data with no clear trend or seasonality.
Holt-Winters Method
The Holt-Winters method is a popular technique for time series forecasting that takes
into account trend and seasonality. It uses a triple exponential smoothing approach to
make predictions. In Python, you can use the statsmodels library to implement the Holt-
Winters method. Here's a simple example of how to use the Holt-Winters method in
Python:
ARIMA
Autoregressive Integrated Moving Average (ARIMA) is a popular method for time series
forecasting. It is a combination of three components: autoregression (AR), differencing (I),
and moving average (MA).
Here's a simple example of how to use ARIMA in Python using the statsmodels library:
As for learning more about ARIMA, here are a few links to get you started:
1. Statsmodels documentation
2. Introduction to ARIMA
3. ARIMA model in Python
Here's an example of how to implement SARIMA in Python using the statsmodels library:
1. Statsmodels Documentation
2. Time Series Analysis in Python - A Comprehensive Guide with Examples
3. Introduction to SARIMA for Time Series Forecasting
Here's an example of how to use SARIMAX in Python using the statsmodels library:
For more information and detailed examples, you can refer to the following links:
1. Statsmodels documentation on
SARIMAX: https://www.statsmodels.org/stable/generated/statsmodels.tsa.statesp
ace.sarimax.SARIMAX.html
2. A tutorial on time series analysis with
SARIMAX: https://www.machinelearningplus.com/time-series/arima-model-time-
series-forecasting-python/
3. A detailed explanation of SARIMAX with Python
examples: https://www.machinelearningplus.com/time-series/arima-model-time-
series-forecasting-python-part-2/
Vector Autoregression (VAR) is a statistical model used in time series analysis to capture
the evolving relationship between multiple time series variables. It is widely used for
forecasting and understanding the interdependencies among variables.
Here's a simple example of how to implement VAR in Python using the statsmodels
library:
Deep AR :
The DeepAR (Deep Autoregressive) model is a popular algorithm for time series
forecasting developed by Amazon. It's a type of recurrent neural network (RNN) designed
to handle sequences of data and make predictions based on historical patterns. DeepAR
is capable of capturing complex patterns and dependencies in the time series data.
Here's a simple example of how to use DeepAR in Python using the GluonTS library,
which is developed by Amazon for probabilistic time series modeling:
forecasts = list(forecast_it)
This example demonstrates how to use the DeepAR model from the GluonTS library to
train a model on synthetic time series data and generate forecasts.
For more information and resources about DeepAR and time series forecasting, you can
refer to the following links:
These resources should provide you with a deeper understanding of the DeepAR model
and its applications in time series forecasting.
Functional Time Series (FTS) models are a class of time series forecasting models that
capture the time-varying dynamics of a system by considering the entire functional form
of the time series. FTS models are particularly useful when dealing with complex and non-
linear time series patterns. One popular implementation of FTS is the Functional
Autoregressive Model (FAR) which extends the traditional autoregressive model to a
functional form.
Here's an example of how you can use the fable package in R to fit a Functional Time
Series model to a time series data:
library(fable)
library(tsibble)
# Load the data
data <- tsibble(data = your_data, index = your_time_index)
# Fit a functional time series model
fts_model <- data %>%
model(
fts_model = ARIMA(your_variable ~ fable::fable::arima(p = 1, d = 0, q = 1))
) %>%
forecast(h = 10)
This code snippet uses the fable package to fit a Functional Time Series model using an
ARIMA approach. You would need to replace your_data and your_time_index with your
actual data and time index.
For Python, you can use the ftsa package to work with Functional Time Series models.
Here's a simple example of how to fit an FTS model using Python:
import ftsaimport pandas as pd
# Load the data
data = pd.read_csv('your_data.csv')
# Fit a functional time series model
fts_model = ftsa.ARIMA(order=(1, 0, 1))
fts_model.fit(data['your_variable'])
forecast = fts_model.forecast(steps=10)
You would need to replace 'your_data.csv' with the path to your actual data file
and 'your_variable' with the column name of the variable you want to forecast.
Here are some links to learn more about Functional Time Series (FTS) models:
Long Short-Term Memory (LSTM) is a type of recurrent neural network (RNN) architecture
that is well-suited for time series forecasting due to its ability to capture long-term
dependencies in data. LSTMs are particularly effective when working with sequences of
data, making them a popular choice for time series forecasting tasks.
Here's a simple example of how you can use LSTM for time series forecasting using the
Keras library in Python:
time_step = 100
X_train, y_train = create_dataset(train, time_step)
X_test, y_test = create_dataset(test, time_step)
# Reshape input to be [samples, time steps, features] which is required for LSTM
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
# Define the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50, return_sequences=True))
model.add(LSTM(50))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# Train the model
model.fit(X_train, y_train, validation_data=(X_test,
GRU
Gated Recurrent Unit (GRU) is a type of recurrent neural network (RNN) that is often used
for time series forecasting due to its ability to capture long-term dependencies in
sequential data. Here's a simple example of how to use GRU for time series forecasting in
Python using the Keras library:
time_steps = 10
X, y = create_dataset(scaled_data, time_steps)
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
# Reshape the input data for the GRU
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
# Build the GRU model
model = Sequential()
model.add(GRU(50, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mean_squared_error')
# Train the model
model.fit(X_train, y_train, epochs=100, batch_size=32, validation_data=(X_test, y_test),
verbose=1)
As for more resources, you can refer to the following links for further understanding and
examples:
RNN
Recurrent Neural Networks (RNNs) are commonly used in time series forecasting due to
their ability to capture sequential information. They are particularly effective when dealing
with time-dependent data, making them suitable for tasks such as stock price prediction,
weather forecasting, and more.
Here's a simple example of how you can use an RNN for time series forecasting using the
Keras library in Python:
time_steps = 10
X, y = create_dataset(time_series_data, time_steps)
# Reshape the input data for the RNN
X = X.reshape(-1, time_steps, 1)
# Build the RNN model
model = Sequential([
SimpleRNN(50, activation='relu', input_shape=(time_steps, 1)),
Dense(1)
])
model.compile(optimizer='adam', loss='mse')
# Train the model
model.fit(X, y, epochs=100, batch_size=32)
# Forecasting# Assuming you have a test dataset stored in a variable called 'test_data'#
Preprocess the test data in the same way as the training data
test_data = (test_data - mean) / std
X_test, y_test = create_dataset(test_data, time_steps)
X_test = X_test.reshape(-1, time_steps, 1)
# Make predictions
predictions = model.predict(X_test)
# Plot the results
plt.plot(y_test, label='True Data')
plt.plot(predictions, label='Predicted Data')
plt.legend()
plt.show()
Prophet
Prophet is a forecasting tool developed by Facebook for time series data. It is designed to
handle the common challenges of business time series forecasting such as seasonality,
holidays, and outliers. Here's a simple example of how to use Prophet in Python: