# Chapter 39: Unit Roots, Seasonality, and Dynamic Regression
# Fundamentals of Python for Financial Econometrics - Unit Roots, Seasonality, and Dynamic Regression
# Dataset: Ceteris Lab teaching sample

# Unit Roots, Seasonality, and Dynamic Regression
#
# **Opening question:** How can a model distinguish persistent trend, recurring seasonality, and serially correlated errors?

# %% Cell 2
import pandas as pd

series = pd.Series(range(24), index=pd.date_range("2024-01-01", periods=24, freq="MS"))
seasonal_difference = series.diff(12)
print(seasonal_difference.dropna().unique().tolist())

# **Interpretation check:** Interpretation. Each month is exactly 12 units above the same month one year earlier in this deterministic illustration.

# %% Cell 4
import numpy as np
import pandas as pd
from statsmodels.tsa.statespace.sarimax import SARIMAX

rng = np.random.default_rng(39)
dates = pd.date_range("2018-01-01", periods=72, freq="MS")
seasonal = pd.Series(
    50 + 0.2 * np.arange(72) + 4 * np.sin(2 * np.pi * np.arange(72) / 12) + rng.normal(0, 0.8, 72),
    index=dates,
)
fit = SARIMAX(seasonal, order=(1, 1, 1), seasonal_order=(0, 1, 1, 12), trend="n", enforce_stationarity=False).fit(disp=False)
print(round(fit.aic, 2))
print(fit.get_forecast(3).predicted_mean.round(2).tolist())

# **Interpretation check:** Interpretation. The exact values depend on the included processed series and estimation conventions. Residual diagnostics remain necessary.

# Verified source output
#
# ```text
# [12.0]
# ```
#
# ```text
# 313.71 [61.79, 63.49, 64.73]
# ```
#
# ```text
# 313.71
# [61.79, 63.49, 64.73]
# ```
