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
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).
- 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, seasonalSARIMA, all nineExponentialSmoothing(ETS) specifications, andTensorFlow/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.
| 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 (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, 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 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. |
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 |
Using the backshift operator SARIMA.ipynb (and its non-seasonal subset in ARIMA.ipynb) is:
where
ExponenTialSmoothing.ipynb evaluates nine combinations of trend
For a series
An abrupt change alarm triggers whenever drift and threshold.
All forecasting notebooks evaluate cumulative horizon error over
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
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)
- Python
3.7+(recommended3.8โ3.10for legacystatsmodels.tsa.arima_model.ARIMA&tensorflow.kerascompatibility; note modernstatsmodels>=0.14movedARIMAtostatsmodels.tsa.arima.model.ARIMAand removed thefreqkeyword in favor ofperiodinseasonal_decompose) - Jupyter Notebook or JupyterLab
git clone https://github.com/khalid-naami/Time-Series-Forecasting.git
cd Time-Series-Forecasting
python -m venv .venvActivate the environment:
# Windows (PowerShell)
.venv\Scripts\Activate.ps1# macOS / Linux
source .venv/bin/activatepip install numpy pandas scipy statsmodels scikit-learn tensorflow matplotlib seaborn pandas-datareader xlsxwriter timeseries-cv jupyterjupyter notebook- Start with
ExploratoryDataAnalysis.ipynbto inspect distributional properties, stationarity, and CUSUM change-points. - Select a series cell inside
ARIMA.ipynb,SARIMA.ipynb,ExponenTialSmoothing.ipynb,DeepNeuralNetwork.ipynb, orDNN_ourApproach.ipynb(switch between livepandas_datareaderloaders or uncomment the localpd.read_csv(...)block forPSI_20_Data_1992_Stooq.csv/ bundled CSVs). - Use
detect_sum.pydirectly 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)- Data Sources: Yahoo Finance (
SPY), FRED (CPIAUCSL,TRFVOLUSM227NFWAviapandas_datareader), and Stooq (PSI_20_Data_1992_Stooq.csv). - CUSUM Attribution:
detect_sum.pyimplementsdetect_cusumby 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.