# Chapter 37: Dependence, Stationarity, and White Noise
# Fundamentals of Python for Financial Econometrics - Dependence, Stationarity, and White Noise
# Dataset: Ceteris Lab teaching sample

# Dependence, Stationarity, and White Noise
#
# **Opening question:** How can we tell whether a time series contains predictable linear structure rather than random fluctuation?

# %% Cell 2
import numpy as np
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.tsa.stattools import acf

rng = np.random.default_rng(18)
x = rng.normal(size=500)
print(np.round(acf(x, nlags=3, fft=True), 3))
print(round(acorr_ljungbox(x, lags=[10], return_df=True)["lb_pvalue"].iloc[0], 3))

# **Interpretation check:** Interpretation. The simulated white-noise series has small sample autocorrelations and does not reject joint independence at lag 10 in this run.

# %% Cell 4
import numpy as np
from statsmodels.tsa.stattools import adfuller

rng = np.random.default_rng(1818)
level = np.cumsum(rng.normal(size=600))
difference = np.diff(level)
print(round(adfuller(level, regression="c")[1], 4))
print(f"{adfuller(difference, regression='c')[1]:.2e}")

# **Interpretation check:** Interpretation. The random-walk level is consistent with a unit root, while its first difference is strongly stationary in the ADF diagnostic.

# %% Cell 6
import numpy as np
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.tsa.stattools import acf
rng = np.random.default_rng(18)
x = rng.normal(size=500)
print(np.round(acf(x, nlags=3, fft=True), 3))

# Verified source output
#
# ```text
# [1. 0.032 0.046 0.033] 0.844
# ```
#
# ```text
# 0.8381 0.00e+00
# ```
#
# ```text
# [1.    0.032 0.046 0.033]
# 0.844
# ```
#
# ```text
# 0.8381
# 0.00e+00
# ```
