Machine Learning | Time Series Forecasting

Master temporal data analysis and prediction techniques

1. Time Series Fundamentals

What is a Time Series?

A time series is a sequence of data points indexed by time. Unlike regular ML where observations are independent, time series data has temporal dependencies - past values influence future values. This autocorrelation is both a challenge and an opportunity for forecasting.

Time Series Components

\[Y_t = T_t + S_t + C_t + R_t\]

  • Trend (T): Long-term increase/decrease
  • Seasonality (S): Regular periodic patterns
  • Cyclical (C): Non-fixed period fluctuations
  • Residual (R): Random noise
Key Concepts
  • Stationarity: Statistical properties constant over time
  • Autocorrelation: Correlation with lagged values
  • Lag: Time steps between observations
  • Horizon: How far ahead to predict
  • Frequency: Hourly, daily, weekly, etc.
Time Series Components Visualization

2. Decomposition & Stationarity

Stationarity

Stationary Series

Properties don't change over time:

  • Constant mean: \(E[Y_t] = \mu\)
  • Constant variance: \(Var(Y_t) = \sigma^2\)
  • Covariance depends only on lag: \(Cov(Y_t, Y_{t-k}) = \gamma_k\)
Tests for Stationarity
  • ADF Test: H₀: unit root (non-stationary)
  • KPSS Test: H₀: stationary
  • Visual: Rolling mean/std plots
  • ACF decay: Should decay quickly
import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import adfuller, kpss
from statsmodels.tsa.seasonal import seasonal_decompose

def check_stationarity(series, name=''):
    """
    Comprehensive stationarity check.
    """
    print(f"=== Stationarity Tests for {name} ===")

    # ADF Test
    adf_result = adfuller(series.dropna())
    print(f"\nADF Test:")
    print(f"  Test Statistic: {adf_result[0]:.4f}")
    print(f"  p-value: {adf_result[1]:.4f}")
    print(f"  Stationary: {'Yes' if adf_result[1] < 0.05 else 'No'}")

    # KPSS Test
    kpss_result = kpss(series.dropna(), regression='c')
    print(f"\nKPSS Test:")
    print(f"  Test Statistic: {kpss_result[0]:.4f}")
    print(f"  p-value: {kpss_result[1]:.4f}")
    print(f"  Stationary: {'Yes' if kpss_result[1] > 0.05 else 'No'}")

    return {
        'adf_stationary': adf_result[1] < 0.05,
        'kpss_stationary': kpss_result[1] > 0.05
    }

def make_stationary(series, max_diff=2):
    """
    Make series stationary through differencing.
    Returns stationary series and number of differences needed.
    """
    d = 0
    temp = series.copy()

    while d < max_diff:
        result = adfuller(temp.dropna())
        if result[1] < 0.05:
            break
        temp = temp.diff().dropna()
        d += 1

    print(f"Series made stationary with d={d} differences")
    return temp, d

# Decomposition
def decompose_series(series, period=12, model='additive'):
    """
    Decompose time series into components.

    model: 'additive' (Y = T + S + R) or 'multiplicative' (Y = T * S * R)
    """
    decomposition = seasonal_decompose(series, model=model, period=period)

    return {
        'trend': decomposition.trend,
        'seasonal': decomposition.seasonal,
        'residual': decomposition.resid,
        'observed': decomposition.observed
    }

# Example usage
df = pd.read_csv('sales_data.csv', parse_dates=['date'], index_col='date')
check_stationarity(df['sales'], 'Sales')

# Decompose
components = decompose_series(df['sales'], period=12)

# Make stationary if needed
stationary_sales, d = make_stationary(df['sales'])
Interview Insight: Why Stationarity Matters

Many statistical models (ARIMA, VAR) assume stationarity. Non-stationary series have time-varying statistics, making parameter estimation unreliable. Always check stationarity first and apply transformations (differencing, log) if needed. Deep learning models are more robust but may still benefit from detrending.

3. Statistical Models (ARIMA Family)

ARIMA(p, d, q)

AutoRegressive Integrated Moving Average combines three components: AR (past values), I (differencing), MA (past errors). It's the workhorse of traditional time series forecasting.

AR(p) - AutoRegressive

\[Y_t = c + \sum_{i=1}^{p} \phi_i Y_{t-i} + \epsilon_t\]

Predict using past p values. ACF decays, PACF cuts off at lag p.

I(d) - Integrated

\[Y'_t = Y_t - Y_{t-1}\]

Differencing d times to achieve stationarity. Usually d ∈ {0, 1, 2}.

MA(q) - Moving Average

\[Y_t = c + \sum_{j=1}^{q} \theta_j \epsilon_{t-j} + \epsilon_t\]

Predict using past q errors. PACF decays, ACF cuts off at lag q.

SARIMA for Seasonal Data

SARIMA(p,d,q)(P,D,Q)m adds seasonal components with period m:

from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
import pmdarima as pm

class ARIMAForecaster:
    """
    ARIMA/SARIMA forecasting with automatic order selection.
    """

    def __init__(self, seasonal_period=None):
        self.seasonal_period = seasonal_period
        self.model = None
        self.fitted = None

    def auto_arima(self, series, **kwargs):
        """
        Automatically find best ARIMA order using AIC.
        """
        self.model = pm.auto_arima(
            series,
            seasonal=self.seasonal_period is not None,
            m=self.seasonal_period or 1,
            d=None,  # Auto-detect differencing
            D=None,  # Auto-detect seasonal differencing
            start_p=0, start_q=0,
            max_p=5, max_q=5,
            start_P=0, start_Q=0,
            max_P=2, max_Q=2,
            information_criterion='aic',
            trace=True,
            error_action='ignore',
            suppress_warnings=True,
            stepwise=True,
            **kwargs
        )

        print(f"\nBest model: ARIMA{self.model.order}")
        if self.seasonal_period:
            print(f"Seasonal: {self.model.seasonal_order}")
        print(f"AIC: {self.model.aic():.2f}")

        return self

    def fit_manual(self, series, order, seasonal_order=None):
        """
        Fit ARIMA with specified order.
        """
        self.fitted = SARIMAX(
            series,
            order=order,
            seasonal_order=seasonal_order,
            enforce_stationarity=False,
            enforce_invertibility=False
        ).fit(disp=False)

        print(self.fitted.summary())
        return self

    def forecast(self, steps, return_conf_int=True):
        """
        Generate forecasts with confidence intervals.
        """
        if self.model:
            forecast = self.model.predict(n_periods=steps, return_conf_int=return_conf_int)
            if return_conf_int:
                return forecast[0], forecast[1]
            return forecast
        elif self.fitted:
            forecast = self.fitted.get_forecast(steps=steps)
            pred = forecast.predicted_mean
            conf_int = forecast.conf_int()
            return pred, conf_int
        else:
            raise ValueError("Model not fitted")

    def diagnose(self):
        """
        Check model residuals for white noise.
        """
        if self.fitted:
            self.fitted.plot_diagnostics(figsize=(12, 8))
        elif self.model:
            residuals = self.model.resid()
            # Check residuals
            from scipy.stats import normaltest
            stat, p = normaltest(residuals)
            print(f"Normality test p-value: {p:.4f}")

# Example usage
forecaster = ARIMAForecaster(seasonal_period=12)
forecaster.auto_arima(train_data)
predictions, conf_int = forecaster.forecast(steps=12)

# Manual fitting
forecaster.fit_manual(
    train_data,
    order=(1, 1, 1),
    seasonal_order=(1, 1, 1, 12)
)
forecaster.diagnose()

Prophet by Meta

from prophet import Prophet
import pandas as pd

class ProphetForecaster:
    """
    Facebook Prophet for business time series.
    Handles seasonality, holidays, and missing data well.
    """

    def __init__(self):
        self.model = None

    def fit(self, df, date_col='ds', value_col='y', **kwargs):
        """
        Fit Prophet model.

        Prophet expects columns: 'ds' (datestamp), 'y' (value)
        """
        # Prepare data
        prophet_df = df[[date_col, value_col]].copy()
        prophet_df.columns = ['ds', 'y']

        # Initialize model
        self.model = Prophet(
            yearly_seasonality=kwargs.get('yearly_seasonality', True),
            weekly_seasonality=kwargs.get('weekly_seasonality', True),
            daily_seasonality=kwargs.get('daily_seasonality', False),
            seasonality_mode=kwargs.get('seasonality_mode', 'additive'),
            changepoint_prior_scale=kwargs.get('changepoint_prior_scale', 0.05),
        )

        # Add custom seasonality if needed
        if kwargs.get('monthly_seasonality'):
            self.model.add_seasonality(
                name='monthly',
                period=30.5,
                fourier_order=5
            )

        # Add holidays
        if 'holidays' in kwargs:
            for holiday in kwargs['holidays']:
                self.model.add_country_holidays(country_name=holiday)

        # Fit
        self.model.fit(prophet_df)
        return self

    def forecast(self, periods, freq='D'):
        """
        Generate forecast.
        """
        future = self.model.make_future_dataframe(periods=periods, freq=freq)
        forecast = self.model.predict(future)

        return forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]

    def plot_components(self):
        """
        Visualize trend and seasonality components.
        """
        return self.model.plot_components(self.forecast(0))

# Example
prophet = ProphetForecaster()
prophet.fit(
    df,
    date_col='date',
    value_col='sales',
    yearly_seasonality=True,
    weekly_seasonality=True,
    changepoint_prior_scale=0.1  # More flexible trend
)
forecast = prophet.forecast(periods=30, freq='D')

4. ML & Deep Learning Models

Feature Engineering for Time Series

import pandas as pd
import numpy as np

def create_time_features(df, date_col='date'):
    """
    Create temporal features for ML models.
    """
    df = df.copy()
    df['date'] = pd.to_datetime(df[date_col])

    # Calendar features
    df['year'] = df['date'].dt.year
    df['month'] = df['date'].dt.month
    df['day'] = df['date'].dt.day
    df['dayofweek'] = df['date'].dt.dayofweek
    df['dayofyear'] = df['date'].dt.dayofyear
    df['weekofyear'] = df['date'].dt.isocalendar().week
    df['quarter'] = df['date'].dt.quarter

    # Cyclical encoding (for periodicity)
    df['month_sin'] = np.sin(2 * np.pi * df['month'] / 12)
    df['month_cos'] = np.cos(2 * np.pi * df['month'] / 12)
    df['day_sin'] = np.sin(2 * np.pi * df['dayofweek'] / 7)
    df['day_cos'] = np.cos(2 * np.pi * df['dayofweek'] / 7)

    # Binary features
    df['is_weekend'] = df['dayofweek'].isin([5, 6]).astype(int)
    df['is_month_start'] = df['date'].dt.is_month_start.astype(int)
    df['is_month_end'] = df['date'].dt.is_month_end.astype(int)

    return df

def create_lag_features(df, target_col, lags=[1, 7, 14, 28]):
    """
    Create lagged features.
    """
    df = df.copy()
    for lag in lags:
        df[f'{target_col}_lag_{lag}'] = df[target_col].shift(lag)
    return df

def create_rolling_features(df, target_col, windows=[7, 14, 28]):
    """
    Create rolling statistics.
    """
    df = df.copy()
    for window in windows:
        df[f'{target_col}_roll_mean_{window}'] = df[target_col].shift(1).rolling(window).mean()
        df[f'{target_col}_roll_std_{window}'] = df[target_col].shift(1).rolling(window).std()
        df[f'{target_col}_roll_min_{window}'] = df[target_col].shift(1).rolling(window).min()
        df[f'{target_col}_roll_max_{window}'] = df[target_col].shift(1).rolling(window).max()
    return df

def create_expanding_features(df, target_col):
    """
    Create expanding window features (cumulative).
    """
    df = df.copy()
    df[f'{target_col}_expanding_mean'] = df[target_col].shift(1).expanding().mean()
    df[f'{target_col}_expanding_std'] = df[target_col].shift(1).expanding().std()
    return df

LSTM for Time Series

import torch
import torch.nn as nn
import numpy as np

class LSTMForecaster(nn.Module):
    """
    LSTM model for time series forecasting.
    """

    def __init__(self, input_size, hidden_size=64, num_layers=2, dropout=0.2):
        super().__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers

        self.lstm = nn.LSTM(
            input_size=input_size,
            hidden_size=hidden_size,
            num_layers=num_layers,
            batch_first=True,
            dropout=dropout if num_layers > 1 else 0
        )

        self.fc = nn.Linear(hidden_size, 1)

    def forward(self, x):
        # x shape: (batch, seq_len, input_size)
        lstm_out, _ = self.lstm(x)
        # Take last output
        last_out = lstm_out[:, -1, :]
        prediction = self.fc(last_out)
        return prediction

def create_sequences(data, seq_length, forecast_horizon=1):
    """
    Create sequences for LSTM training.
    """
    X, y = [], []
    for i in range(len(data) - seq_length - forecast_horizon + 1):
        X.append(data[i:(i + seq_length)])
        y.append(data[i + seq_length + forecast_horizon - 1])
    return np.array(X), np.array(y)

# Training example
def train_lstm(model, train_loader, val_loader, epochs=100, lr=0.001):
    criterion = nn.MSELoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=10)

    best_val_loss = float('inf')

    for epoch in range(epochs):
        model.train()
        train_loss = 0
        for X_batch, y_batch in train_loader:
            optimizer.zero_grad()
            predictions = model(X_batch)
            loss = criterion(predictions.squeeze(), y_batch)
            loss.backward()
            optimizer.step()
            train_loss += loss.item()

        # Validation
        model.eval()
        val_loss = 0
        with torch.no_grad():
            for X_batch, y_batch in val_loader:
                predictions = model(X_batch)
                val_loss += criterion(predictions.squeeze(), y_batch).item()

        train_loss /= len(train_loader)
        val_loss /= len(val_loader)
        scheduler.step(val_loss)

        if val_loss < best_val_loss:
            best_val_loss = val_loss
            torch.save(model.state_dict(), 'best_model.pt')

        if epoch % 10 == 0:
            print(f"Epoch {epoch}: Train Loss={train_loss:.4f}, Val Loss={val_loss:.4f}")
Interview Insight: When to Use What

ARIMA: Small datasets, single series, interpretability needed. Prophet: Business data with holidays, missing values, multiple seasonalities. XGBoost/LightGBM: Many features, multiple series, fast training. LSTM/Transformer: Complex patterns, long sequences, multiple related series.

5. Evaluation & Cross-Validation

Time Series Cross-Validation

Standard k-fold CV doesn't work for time series (data leakage!). Use walk-forward validation: train on past, validate on future, slide the window forward.

Error Metrics

MAE: \(\frac{1}{n}\sum|y_i - \hat{y}_i|\)

RMSE: \(\sqrt{\frac{1}{n}\sum(y_i - \hat{y}_i)^2}\)

MAPE: \(\frac{100}{n}\sum\left|\frac{y_i - \hat{y}_i}{y_i}\right|\)

MASE: Scale-free, compares to naive forecast

Choosing Metrics
  • MAE: Robust to outliers, interpretable
  • RMSE: Penalizes large errors more
  • MAPE: Percentage, but undefined for y=0
  • MASE: Compare across different series
  • sMAPE: Symmetric MAPE, bounded
from sklearn.metrics import mean_absolute_error, mean_squared_error
import numpy as np

def time_series_metrics(y_true, y_pred, y_naive=None):
    """
    Calculate comprehensive time series metrics.
    """
    y_true, y_pred = np.array(y_true), np.array(y_pred)

    mae = mean_absolute_error(y_true, y_pred)
    rmse = np.sqrt(mean_squared_error(y_true, y_pred))

    # MAPE (avoid division by zero)
    mask = y_true != 0
    mape = np.mean(np.abs((y_true[mask] - y_pred[mask]) / y_true[mask])) * 100

    # sMAPE (symmetric)
    smape = np.mean(2 * np.abs(y_true - y_pred) / (np.abs(y_true) + np.abs(y_pred))) * 100

    metrics = {
        'MAE': mae,
        'RMSE': rmse,
        'MAPE': mape,
        'sMAPE': smape
    }

    # MASE (if naive forecast provided)
    if y_naive is not None:
        naive_mae = mean_absolute_error(y_true, y_naive)
        metrics['MASE'] = mae / naive_mae if naive_mae > 0 else np.inf

    return metrics

class TimeSeriesCV:
    """
    Walk-forward cross-validation for time series.
    """

    def __init__(self, n_splits=5, test_size=None, gap=0):
        self.n_splits = n_splits
        self.test_size = test_size
        self.gap = gap  # Gap between train and test (avoid leakage)

    def split(self, X):
        """
        Generate train/test indices.
        """
        n_samples = len(X)
        test_size = self.test_size or n_samples // (self.n_splits + 1)

        for i in range(self.n_splits):
            test_start = n_samples - (self.n_splits - i) * test_size
            test_end = test_start + test_size
            train_end = test_start - self.gap

            train_idx = np.arange(0, train_end)
            test_idx = np.arange(test_start, min(test_end, n_samples))

            yield train_idx, test_idx

    def cross_val_score(self, model_fn, X, y, metric_fn):
        """
        Run cross-validation and return scores.
        """
        scores = []

        for train_idx, test_idx in self.split(X):
            X_train, X_test = X[train_idx], X[test_idx]
            y_train, y_test = y[train_idx], y[test_idx]

            # Fit model
            model = model_fn()
            model.fit(X_train, y_train)

            # Predict
            y_pred = model.predict(X_test)

            # Score
            score = metric_fn(y_test, y_pred)
            scores.append(score)

        return np.array(scores)

# Usage
cv = TimeSeriesCV(n_splits=5, gap=1)
scores = cv.cross_val_score(
    model_fn=lambda: LGBMRegressor(),
    X=features.values,
    y=target.values,
    metric_fn=lambda y, p: -mean_absolute_error(y, p)
)
print(f"CV Score: {-scores.mean():.4f} (+/- {scores.std():.4f})")

6. Interview Questions

Strategies depend on the missingness pattern:

  1. Forward/Backward fill: Use last/next known value
    df['value'].fillna(method='ffill')
  2. Interpolation: Linear, polynomial, or spline
    df['value'].interpolate(method='linear')
  3. Seasonal decomposition: Fill using seasonal pattern
  4. Model-based: Use ARIMA or similar to impute
  5. Indicator variable: Add feature marking imputed values

Key considerations:

  • Don't use future values to fill past (data leakage)
  • Consider if missingness is informative
  • Some models (Prophet) handle missing values natively

Cold start problem in forecasting:

  1. Transfer learning: Use similar products' data
    • Find analogous products (same category, price range)
    • Scale based on expected differences
  2. Hierarchical models: Learn at category level, apply to item
  3. Feature-based: Build regression using product attributes
    • Price, category, brand, seasonality indicators
    • Marketing spend, distribution
  4. Bayesian approach: Start with prior (category average), update as data comes in
  5. Expert judgment: Incorporate business knowledge as priors

As data accumulates: Transition to product-specific model, blend with category model initially.

AspectARIMAExponential Smoothing
Approach Regression on lagged values and errors Weighted average with exponentially decaying weights
Stationarity Requires stationary data (after differencing) Handles trend and seasonality directly
Parameters p, d, q (and P, D, Q, m for SARIMA) α (level), β (trend), γ (seasonality)
Interpretability Coefficients show autocorrelation structure Weights show smoothing behavior
Best for Data with complex autocorrelation Simple trend/seasonality patterns

Key insight: They can produce similar forecasts but come from different theoretical frameworks. ETS (Error, Trend, Seasonal) is the state-space formulation of exponential smoothing with prediction intervals.

Key Takeaways
  • Check stationarity: Transform if needed before modeling
  • Understand components: Trend, seasonality, residuals
  • Walk-forward CV: Never use future data for training
  • Feature engineering: Lags, rolling stats, calendar features
  • Multiple metrics: MAPE, RMSE, MASE for different views
  • Model selection: Match model complexity to data size