Skip to content

About

End-to-end statistical and deep learning time series forecasting suite comparing Exploratory Diagnostics, CUSUM change-point detection, ARIMA/SARIMA grid search, 9 ETS state-space models, and Keras MLP/RNN/LSTM neural networks on bundled equity and FRED macro datasets.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

๐Ÿ“ˆ Univariate Time Series Forecasting Suite

End-to-end statistical and deep learning framework for univariate financial and macroeconomic time series forecasting โ€” combining Exploratory Diagnostics, CUSUM Change-Point Detection, ARIMA/SARIMA Grid Search, 9 ETS State-Space Models, and MLP/RNN/LSTM Neural Networks across Equity Index and FRED Macro datasets.

Overview โ€ข Notebooks & Modules โ€ข Datasets โ€ข Methodology โ€ข Architecture โ€ข Structure โ€ข Setup & Usage

Python 3 Statsmodels ARIMA SARIMA ETS TensorFlow Keras MIT License

Statistical Diagnostics CUSUM Change Detection Time Series Cross-Validation Data Sources


๐Ÿ“Š Overview

Time-Series-Forecasting is a structured research suite comparing classical econometric time-series models against deep neural architectures on multi-horizon out-of-sample forecasting tasks. Each analytical stage is isolated into a dedicated Jupyter notebook with rigorous pre-modeling statistical testing, information-criterion model selection, residual diagnostics, and horizon-level error profiling (MAE and MAPE).

What This Suite Solves

  • Non-Stationarity & Structural Break Auditing: Verifies variance stability, unit roots (ADF, KPSS), non-linearity (BDS), heteroscedasticity (Engle ARCH), and abrupt regime shifts (CUSUM) before model fitting.
  • Classical vs. Neural Benchmarking: Evaluates ARIMA, seasonal SARIMA, all nine ExponentialSmoothing (ETS) specifications, and TensorFlow/Keras (MLP, SimpleRNN, LSTM) models under consistent multi-step horizons ([1, 5, 21] trading days for daily equities; [1, 3, 12] months for monthly macro series).
  • Time-Aware Cross-Validation: Uses timeseries-cv (tsxv) expanding/rolling splitters (Forward Chaining, K-Fold, Group K-Fold, and variable-input rolling windows) to prevent look-ahead leakage.

๐Ÿ““ Notebooks and Module Catalog

File Role Implemented Techniques & Outputs
ExploratoryDataAnalysis.ipynb Statistical Profiling & EDA Summary stats, histogram + KDE, ECDF, yearly/monthly boxplots, 300-period rolling mean/std, additive & multiplicative seasonal_decompose, Hodrick-Prescott filter (lamb=107360000000), Box-Cox ($\lambda = 0.02$, $\lambda = 0$) & arcsinh transforms, ACF/PACF (maxLags=40), Q-Q plot, CUSUM (threshold=6, drift=3), Kurtosis, Skewness, Jarque-Bera, KS, ARCH LM, ADF, KPSS, and BDS tests.
ARIMA.ipynb Non-Seasonal Box-Jenkins Stationarity & normality battery on raw, $\ln(y_t)$, $\Delta y_t$, and $\Delta \ln(y_t)$; grid search (ARIMA_grid) ranked by AIC, BIC, and HQIC; rolling cross-validation via split_train_variableInput; residual tests (Kurtosis, Skewness, JB, KS, ARCH, BDS, Breusch-Godfrey, Box-Pierce, Ljung-Box); SPY 1/5/21-day forecasts (MAE = 3.63, 4.44, 7.91).
SARIMA.ipynb Seasonal ARIMA (SARIMAX) Grid search (SARIMA_grid) over $(p,d,q) \times t \times (P,D,Q,m)$ with trend t in ['n', 'c'] and m = 12; IQR-based initial outlier replacement (replace_initial_outliers) before residual diagnostics; full diagnostic battery; FRED TRFVOLUSM227NFWA 1/3/12-month forecasts (MAE = 117.24, 902.34, 1615.14 for SARIMA(1,1,1)n(1,1,1,12)).
ExponenTialSmoothing.ipynb ETS State-Space Family Fits and compares 9 ExponentialSmoothing specifications (TS (N, N), (A, N), (Ad, N), (N, A), (A, A), (Ad, A), (N, M), (A, M), (Ad, M)); AIC/BIC selection; full residual validation; SPY 1/5/21-day forecasts (e.g., damped Holt TS (Ad, N): MAE = 3.70, 4.68, 8.78).
DeepNeuralNetwork.ipynb Neural Forecasting Benchmark Sequential Keras MLP (50-100-80-30-horizon ReLU), SimpleRNN (100-50-25-horizon linear), and LSTM (25-25-50-30-20-15-horizon linear) trained with adam + mae loss (numInputs=12, train_epochs=10); MinMaxScaler / StandardScaler / revert_logDiff; Forward Chaining, K-Fold, and Group K-Fold CV; outlier-trimmed multi-run forecasting (SPY MLP run MAE = 0.24, 1.74, 4.30).
DNN_ourApproach.ipynb Refined MLP & 3-Layer LSTM Focused MLP (50-100-80-30-horizon) and LSTM (25-50-15-horizon) workflow trained for train_epochs = 50 using GroupKFold (split_train_val_groupKFold, n_steps_input=12, n_steps_jump=1); multi-run trimmed statistics (MAX_ITER=4, PRED_OUTL=2) and in-sample vs. out-of-sample visual comparison (SPY MAE = 1.40, 2.12, 4.36).
detect_sum.py CUSUM Change-Point Module Implements detect_cusum(x, threshold, drift, ending, show, ax) and _plot(...) (authored by Marcos Duarte / BMC, adapted from Gustafsson 2000) to detect positive and negative cumulative structural shifts in 1D arrays.

๐Ÿ“ Datasets

Four CSV datasets are bundled in the repository root for offline reproducibility alongside pandas_datareader loaders inside the notebooks:

File Series / Asset Source Frequency Date Range Observations Columns
SPY.csv SPDR S&P 500 ETF Trust (SPY) Yahoo Finance Daily 1993-01-29 โ†’ 2019-09-27 6,715 Date, High, Low, Open, Close, Volume, Adj Close
PSI_20_Data_1992_Stooq.csv Euronext Lisbon PSI-20 Index Stooq Daily 1992-12-31 โ†’ 2019-11-29 6,808 Date, Open, High, Low, Close, Volume
CPIAUCSL.csv US Consumer Price Index (CPIAUCSL) FRED Monthly 1947-01-01 โ†’ 2019-09-01 873 DATE, CPIAUCSL
TRFVOLUSM227NFWA.csv US Vehicle Miles Traveled (VMT) FRED Monthly 1970-01-01 โ†’ 2019-09-01 597 DATE, TRFVOLUSM227NFWA

๐Ÿงฎ Mathematical Methodology

1. Seasonal ARIMA โ€” $\text{SARIMA}(p, d, q) \times (P, D, Q)_m$

Using the backshift operator $B$ ($B^k y_t = y_{t-k}$), the multiplicative seasonal model estimated in SARIMA.ipynb (and its non-seasonal subset in ARIMA.ipynb) is:

$$\Phi_P(B^m),\phi_p(B),(1 - B^m)^D,(1 - B)^d,y_t = c + \Theta_Q(B^m),\theta_q(B),\varepsilon_t$$

where $(p,d,q)$ are non-seasonal autoregressive, differencing, and moving-average orders, $(P,D,Q)_m$ are their seasonal counterparts with period $m = 12$, and candidate models are ranked by AIC, BIC, and HQIC.

2. Exponential Smoothing (ETS) State-Space Formulations

ExponenTialSmoothing.ipynb evaluates nine combinations of trend $T \in {\text{N}, \text{A}, \text{Ad}}$ and seasonality $S \in {\text{N}, \text{A}, \text{M}}$. For the damped additive Holt-Winters specification $\text{TS}(A_d, A)$ with smoothing parameters $(\alpha, \beta, \gamma)$, damping factor $\zeta \in (0,1)$, and period $m$:

$$\ell_t = \alpha(y_t - s_{t-m}) + (1 - \alpha)(\ell_{t-1} + \zeta b_{t-1})$$ $$b_t = \beta(\ell_t - \ell_{t-1}) + (1 - \beta)\zeta b_{t-1}$$ $$s_t = \gamma(y_t - \ell_{t-1} - \zeta b_{t-1}) + (1 - \gamma)s_{t-m}$$ $$\hat{y}_{t+h \mid t} = \ell_t + \left(\sum_{i=1}^{h}\zeta^i\right)b_t + s_{t + h - m(\lfloor (h-1)/m \rfloor + 1)}$$

3. Two-Sided CUSUM Change-Point Detection (detect_sum.py)

For a series $x_t$, one-step differences $s_t = x_t - x_{t-1}$ accumulate upward and downward drift-adjusted sums:

$$g_t^+ = \max!\left(0,; g_{t-1}^+ + s_t - \delta\right), \qquad g_t^- = \max!\left(0,; g_{t-1}^- - s_t - \delta\right)$$

An abrupt change alarm triggers whenever $g_t^+ > \tau$ or $g_t^- > \tau$, where $\delta$ is drift and $\tau$ is threshold.

4. Multi-Horizon Forecast Evaluation

All forecasting notebooks evaluate cumulative horizon error over $H \in {1, 5, 21}$ (daily) or $H \in {1, 3, 12}$ (monthly):

$$\text{MAE}_H = \frac{1}{H}\sum_{i=1}^{H} \left|y_i - \hat{y}_i\right|, \qquad \text{MAPE}_H = \frac{100%}{H}\sum_{i=1}^{H} \left|\frac{y_i - \hat{y}_i}{y_i}\right|$$


๐Ÿ—๏ธ Architecture

flowchart LR
    subgraph Data["Data Sources and Local CSVs"]
        CSV["Local CSV Datasets\n(SPY, PSI-20, CPIAUCSL, TRFVOLUSM227NFWA)"]
        DR["pandas_datareader\n(Yahoo Finance and FRED)"]
    end

    subgraph EDA["Diagnostic and Stationarity Layer"]
        EDANB["ExploratoryDataAnalysis.ipynb\n(HP Filter, Seasonal Decompose, Box-Cox)"]
        CUSUM["detect_sum.py\n(detect_cusum Abrupt Shift Detector)"]
        TESTS["Hypothesis Battery\n(ADF, KPSS, JB, KS, ARCH, BDS, Ljung-Box)"]
    end

    subgraph Models["Forecasting Pipelines"]
        AR["ARIMA.ipynb & SARIMA.ipynb\n(IC Grid Search + Residual Validation)"]
        ETS["ExponenTialSmoothing.ipynb\n(9 ETS Configurations)"]
        DNN["DeepNeuralNetwork.ipynb & DNN_ourApproach.ipynb\n(Keras MLP, SimpleRNN, LSTM + tsxv CV)"]
    end

    subgraph Eval["Out-of-Sample Evaluation"]
        HOR["Multi-Horizon Metrics\n(horizon_mae & horizon_mape)"]
        VIZ["In-Sample vs Out-of-Sample Plots"]
    end

    CSV --> EDANB
    DR --> EDANB
    EDANB --> CUSUM
    EDANB --> TESTS
    TESTS --> AR
    TESTS --> ETS
    TESTS --> DNN
    AR --> HOR
    ETS --> HOR
    DNN --> HOR
    HOR --> VIZ
Loading

๐Ÿ“‚ Repository Structure

Time-Series-Forecasting/
โ”œโ”€โ”€ .gitattributes
โ”œโ”€โ”€ .gitignore
โ”œโ”€โ”€ LICENSE                               # MIT License
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ detect_sum.py                         # Standalone CUSUM abrupt change-point detector
โ”œโ”€โ”€ ExploratoryDataAnalysis.ipynb         # Data inspection, decomposition, CUSUM & unit root tests
โ”œโ”€โ”€ ARIMA.ipynb                           # Non-seasonal ARIMA grid search, CV & diagnostics
โ”œโ”€โ”€ SARIMA.ipynb                          # Seasonal SARIMAX grid search, CV & outlier handling
โ”œโ”€โ”€ ExponenTialSmoothing.ipynb            # 9-model ETS benchmark, IC selection & diagnostics
โ”œโ”€โ”€ DeepNeuralNetwork.ipynb               # Keras MLP / SimpleRNN / LSTM with tsxv CV variants
โ”œโ”€โ”€ DNN_ourApproach.ipynb                 # Refined MLP & 3-layer LSTM with Group K-Fold CV
โ”œโ”€โ”€ SPY.csv                               # S&P 500 ETF daily data (1993-2019, 6,715 rows)
โ”œโ”€โ”€ PSI_20_Data_1992_Stooq.csv            # PSI-20 index daily data (1992-2019, 6,808 rows)
โ”œโ”€โ”€ CPIAUCSL.csv                          # US CPI monthly data (1947-2019, 873 rows)
โ””โ”€โ”€ TRFVOLUSM227NFWA.csv                  # US Vehicle Miles Traveled monthly data (1970-2019, 597 rows)

๐Ÿš€ Installation and Usage

Prerequisites

  • Python 3.7+ (recommended 3.8โ€“3.10 for legacy statsmodels.tsa.arima_model.ARIMA & tensorflow.keras compatibility; note modern statsmodels>=0.14 moved ARIMA to statsmodels.tsa.arima.model.ARIMA and removed the freq keyword in favor of period in seasonal_decompose)
  • Jupyter Notebook or JupyterLab

1. Clone and Create a Virtual Environment

git clone https://github.com/khalid-naami/Time-Series-Forecasting.git
cd Time-Series-Forecasting

python -m venv .venv

Activate the environment:

# Windows (PowerShell)
.venv\Scripts\Activate.ps1
# macOS / Linux
source .venv/bin/activate

2. Install Dependencies

pip install numpy pandas scipy statsmodels scikit-learn tensorflow matplotlib seaborn pandas-datareader xlsxwriter timeseries-cv jupyter

3. Launch Jupyter and Run Notebooks

jupyter notebook
  1. Start with ExploratoryDataAnalysis.ipynb to inspect distributional properties, stationarity, and CUSUM change-points.
  2. Select a series cell inside ARIMA.ipynb, SARIMA.ipynb, ExponenTialSmoothing.ipynb, DeepNeuralNetwork.ipynb, or DNN_ourApproach.ipynb (switch between live pandas_datareader loaders or uncomment the local pd.read_csv(...) block for PSI_20_Data_1992_Stooq.csv / bundled CSVs).
  3. Use detect_sum.py directly in Python scripts:
import pandas as pd
from detect_sum import detect_cusum

df = pd.read_csv("SPY.csv")
ta, tai, taf, amp = detect_cusum(df["Close"].values, threshold=6, drift=3, ending=True, show=True)

๐ŸŒ External Data Providers, Disclaimers and License

  • Data Sources: Yahoo Finance (SPY), FRED (CPIAUCSL, TRFVOLUSM227NFWA via pandas_datareader), and Stooq (PSI_20_Data_1992_Stooq.csv).
  • CUSUM Attribution: detect_sum.py implements detect_cusum by Marcos Duarte (BMC, MIT License) based on Gustafsson (2000), Adaptive Filtering and Change Detection.
  • Cross-Validation: Time-series split utilities use tsxv (timeseries-cv).
  • Disclaimer: Provided strictly for academic, research, and educational purposes. Historical forecasting benchmarks do not constitute investment advice.
  • License: Released under the MIT License โ€” see LICENSE for details.

About

End-to-end statistical and deep learning time series forecasting suite comparing Exploratory Diagnostics, CUSUM change-point detection, ARIMA/SARIMA grid search, 9 ETS state-space models, and Keras MLP/RNN/LSTM neural networks on bundled equity and FRED macro datasets.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages