Time series forecasting is a technique for predicting future values based on past data collected over time. This is useful in economics, sales, weather prediction, stock prices, and many more fields. In this article, we introduce three popular forecasting models: ARIMA, Facebook Prophet, and LSTM neural networks.
A time series is a sequence of data points measured at regular time intervals (e.g., daily sales, hourly temperatures, monthly stock prices). The key idea is that each value often depends on its previous values.
from statsmodels.tsa.arima.model import ARIMA
import pandas as pd
# Example: Forecast a monthly time series
data = pd.read_csv('monthly-sales.csv') # Must have 'Month' and 'Sales' columns
model = ARIMA(data['Sales'], order=(2,1,2))
model_fit = model.fit()
forecast = model_fit.forecast(steps=12)
print(forecast)
from prophet import Prophet
import pandas as pd
# Load data: must have columns 'ds' (date) and 'y' (value)
df = pd.read_csv('monthly-sales.csv')
df = df.rename(columns={'Month': 'ds', 'Sales': 'y'})
model = Prophet()
model.fit(df)
future = model.make_future_dataframe(periods=12, freq='M')
forecast = model.predict(future)
print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(12))
from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np
# Simulated data: X_train shape (samples, time_steps, features)
X_train = np.random.rand(100, 12, 1) # 100 samples, 12 time steps, 1 feature
y_train = np.random.rand(100)
model = Sequential()
model.add(LSTM(50, activation='relu', input_shape=(12, 1)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
model.fit(X_train, y_train, epochs=30, batch_size=16)
This uses randomly generated data for illustration. For real use, reshape your own time series into sequences and targets.
Time series forecasting is a crucial tool for making decisions based on past data. With models like ARIMA, Prophet, and LSTM, you can analyze trends, forecast the future, and discover hidden patterns in your temporal data. Start with ARIMA or Prophet for easier projects, and explore LSTM for more complex tasks!