Practice Project 10

Time Series Forecasting Project

Process datetime-indexed databases, decompose trends and seasonality components, train statistical ARIMA/SARIMAX models, and evaluate forecasts against actual parameters.

Domain / Environment
Retail Finance / Conda VM
Difficulty
Intermediate (3/5)
Course Module
Time Series Analysis
Deliverables
Decomposition curves & Forecast evaluation plot
1. System Architecture & Process Workflow

The diagram below displays the time series forecasting process. Raw data is parsed and index frequencies set. This index is split into training and testing sets. An additive decomposition model extracts trend and seasonal factors, while a SARIMAX forecaster fits models and generates predictions.

Date Series Data Date (Index) Monthly_Sales Category: Retail Parse 1. Decomposition Trend & Seasonal Residual errors Fit Model 2. SARIMAX Forecaster AutoRegressive (p) Moving Average (q) 3. Evaluation MAE / RMSE forecast.png Test vs Actual
2. Part 1: Step-by-Step Action Items & Key Execution Steps
STEP 1

Activate Python Virtual Environment

Point the terminal execution environment to the course conda sandbox environment.

$ conda activate ds_ai_ml
This targets active python libraries to the isolated virtual sandbox.
STEP 2

Create Project Folders inside Linux VM

Create a dedicated folder for the project files inside your guest VM home folder directory.

$ mkdir -p ~/Projects/time_series && cd ~/Projects/time_series
This sets up the working directory layout for the time series code.
STEP 3

Save Monthly Sales Time Series Dataset

Create a CSV dataset containing monthly sales records spanning two years.

$ nano monthly_sales.csv
This opens nano editor. Paste the CSV data template from Part 2, press **Ctrl + O** and **Enter** to save, and **Ctrl + X** to exit.
STEP 4

Install Time Series Packages via Pip

Install Statsmodels libraries inside the active conda session.

$ pip install statsmodels matplotlib pandas numpy
This command downloads statsmodels, which provides statistical decomposition models and ARIMA algorithms.
STEP 5

Create forecaster script file in VS Code

Launch VS Code and create a new script file inside the project workspace folder.

Launch VS Code via terminal "code ." -> Right-click in explorer tree -> click New File -> Type: sales_forecaster.py -> Press Enter
This registers an empty file `sales_forecaster.py` inside the active directory editor workspace.
STEP 6

Load Python forecasting logic

Paste the decomposition and ARIMA model code into the newly created python script file.

Click sales_forecaster.py -> Paste python code from Part 2 below -> Save file via Ctrl + S
This writes calculations and visualization directives to the script.
STEP 7

Execute time series forecasting script

Run the validation script using the python engine to compare the models.

$ python sales_forecaster.py
This parses dates, runs additive decomposition sweeps, fits the ARIMA model, and saves forecast plots.
STEP 8

Open and verify generated figures

Open the figures using the default Linux desktop photo viewer to review the forecast trends.

$ xdg-open decomposition_plots.png && xdg-open sales_forecast.png
This command loads the image viewer application on the VM desktop to display the plots.
3. Operational Pipeline Architecture

The flowchart below outlines the time series forecasting pipeline. It details dataset loading, trend/seasonality decomposition, ARIMA model fitting, and saving forecast validation plots.

1. Load Dates Ingest sales rows, index by datetime pd.to_datetime() 2. Decompose Extract trend and seasonal patterns seasonal_decompose 3. Train Split Split partitions chronologically to prevent data leakage data[:split_index] 4. Fit ARIMA Train parameters and run forecast ARIMA(p,d,q).fit() 5. Save Plot Evaluate metrics and save plots to PNG plt.savefig()
4. Part 2: Complete Deliverable Assets & Production Templates

To run the forecasting pipeline, we need the monthly sales CSV dataset and the Python analysis script. Below is a line-by-line explanation of the code, followed by the combined template files.

Step-by-Step Code Construction

Lines 1 - 5

Import Time Series libraries

Include system packages, Pandas, and statsmodels decomposition and ARIMA modules in the script.

import pandas as pd import numpy as np import matplotlib.pyplot as plt from statsmodels.tsa.seasonal import seasonal_decompose from statsmodels.tsa.arima.model import ARIMA
These imports pull standard time-series analysis packages, decomposition methods, and ARIMA forecasting algorithms.
Lines 6 - 12

Configure Date Index

Load the CSV dataset, parse dates, set the date column as the index, and configure a monthly frequency.

df = pd.read_csv("monthly_sales.csv") df["Date"] = pd.to_datetime(df["Date"]) df.set_index("Date", inplace=True) df.index.freq = "MS"
This parses dates, sets the datetime index, and sets a monthly start ('MS') frequency to align statsmodels algorithms.
Lines 13 - 18

Run Time Series Decomposition

Apply additive decomposition to separate the sales series into trend, seasonal, and residual components.

decomposition = seasonal_decompose(df["Sales"], model="additive") fig_decomp = decomposition.plot() fig_decomp.savefig("decomposition_plots.png")
This decomposes the time series, plots trend and seasonal factors, and saves the plot as `decomposition_plots.png`.
Lines 19 - 30

Train ARIMA Model and Forecast

Partition the dataset chronologically, fit the ARIMA model on the training set, and generate forecasts.

train = df.iloc[:18] # First 18 months test = df.iloc[18:] # Last 6 months model = ARIMA(train["Sales"], order=(1, 1, 1)) model_fit = model.fit() forecast = model_fit.forecast(steps=6)
This splits the dataset, fits the ARIMA(1,1,1) model on training rows, and forecasts sales for the remaining 6 months.
Lines 31 - 40

Plot Forecast Comparisons

Plot the actual values alongside the ARIMA predictions, and save the plot to disk.

plt.figure() plt.plot(train.index, train["Sales"], label="Train") plt.plot(test.index, test["Sales"], label="Actual Test") plt.plot(test.index, forecast, label="ARIMA Forecast") plt.legend() plt.savefig("sales_forecast.png")
This creates a comparison plot showing training data, actual values, and the forecast, saving it as `sales_forecast.png`.

Production templates

1. Sample Dataset (Save as ~/Projects/time_series/monthly_sales.csv):

Date,Sales 2024-01-01,15000 2024-02-01,16200 2024-03-01,17500 2024-04-01,18000 2024-05-01,20200 2024-06-01,22000 2024-07-01,21500 2024-08-01,22500 2024-09-01,21000 2024-10-01,23000 2024-11-01,24500 2024-12-01,28000 2025-01-01,18500 2025-02-01,19200 2025-03-01,21000 2025-04-01,21500 2025-05-01,23000 2025-06-01,25000 2025-07-01,24000 2025-08-01,26000 2025-09-01,24500 2025-10-01,26500 2025-11-01,28000 2025-12-01,32000

2. Python script (Save as ~/Projects/time_series/sales_forecaster.py):

# sales_forecaster.py - ARIMA Time Series Forecasting import pandas as pd import numpy as np import matplotlib.pyplot as plt from statsmodels.tsa.seasonal import seasonal_decompose from statsmodels.tsa.arima.model import ARIMA def main(): print("=== Loading Monthly Sales Time Series ===") df = pd.read_csv("monthly_sales.csv") df["Date"] = pd.to_datetime(df["Date"]) df.set_index("Date", inplace=True) # Set monthly start frequency df.index.freq = "MS" print(f"Dataset span: {df.index.min().strftime('%Y-%m')} to {df.index.max().strftime('%Y-%m')}") print(f"Total records: {len(df)} months") # 1. Additive decomposition print("\n[Running Time Series Decomposition]") decomposition = seasonal_decompose(df["Sales"], model="additive") plt.style.use('dark_background') fig = decomposition.plot() fig.patch.set_facecolor("#0f172a") decomp_filename = "decomposition_plots.png" fig.savefig(decomp_filename, facecolor="#0f172a", edgecolor="none") print(f"Decomposition plots saved: {decomp_filename}") # 2. Chronological Split (Train: 18 months, Test: 6 months) print("\n[Splitting Dataset]") train = df.iloc[:18] test = df.iloc[18:] print(f" - Train period: {train.index.min().strftime('%Y-%m')} to {train.index.max().strftime('%Y-%m')}") print(f" - Test period: {test.index.min().strftime('%Y-%m')} to {test.index.max().strftime('%Y-%m')}") # 3. Fit ARIMA(1, 1, 1) model print("\n[Fitting ARIMA(1,1,1) Model]") model = ARIMA(train["Sales"], order=(1, 1, 1)) model_fit = model.fit() print(model_fit.summary()) # 4. Generate forecasts forecast_steps = len(test) forecast_res = model_fit.forecast(steps=forecast_steps) forecast_series = pd.Series(forecast_res, index=test.index) # Calculate evaluation metrics errors = test["Sales"] - forecast_series mae = np.mean(np.abs(errors)) rmse = np.sqrt(np.mean(errors ** 2)) mape = np.mean(np.abs(errors) / test["Sales"]) * 100 print("\n[Forecast Evaluation Metrics]") print(f" - Mean Absolute Error (MAE): ${mae:.2f}") print(f" - Root Mean Squared Error (RMSE): ${rmse:.2f}") print(f" - Mean Absolute Percentage Error (MAPE): {mape:.2f}%") # 5. Plot Actual vs Forecast plt.figure(figsize=(10, 5)) plt.plot(train.index, train["Sales"], color="#38bdf8", label="Train Sales", linewidth=2) plt.plot(test.index, test["Sales"], color="#34d399", label="Actual Test Sales", marker='o') plt.plot(test.index, forecast_series, color="#c084fc", label="ARIMA Forecast", marker='x', linestyle="--") plt.title("Monthly Sales Forecast vs Actuals (ARIMA)", color="#f8fafc") plt.xlabel("Date", color="#94a3b8") plt.ylabel("Sales ($)", color="#94a3b8") plt.legend() plt.grid(True, linestyle="--", color="#334155", alpha=0.5) forecast_filename = "sales_forecast.png" plt.savefig(forecast_filename, facecolor="#0f172a", edgecolor="none") print(f"\nForecast comparison plot saved: {forecast_filename}") print("=== Time Series Forecasting Project Successfully Complete! ===") if __name__ == "__main__": main()
5. Deliverables Summary

Verify that the following configurations and outputs exist inside your project workspace.

Created Files / Templates

  • ~/Projects/time_series/monthly_sales.csv - Monthly sales series dataset.
  • ~/Projects/time_series/sales_forecaster.py - Verification python script file.
  • ~/Projects/time_series/decomposition_plots.png - Saved trend and seasonal decomposition charts.
  • ~/Projects/time_series/sales_forecast.png - Actual vs forecast plot.

Verification Artifacts / Execution Proof

  • Summary table of the fitted ARIMA parameters showing significance.
  • Comparative plots showing forecast values mapping along actual trends.
  • MAE, RMSE, and MAPE errors calculated on held-out test data.
6. Closing Explanation: Why We Did This & What It Accomplishes

Architectural Intent & Operational Impact

Why We Did This

What This Accomplishes