# Chapter 45: Multiple Time Series
# Fundamentals of Python for Financial Econometrics - Multiple Time Series
# Dataset: Ceteris Lab teaching sample

# Multiple Time Series
#
# **Opening question:** When several series move together, which relationships are short-run predictive and which are long-run equilibrating?

# %% Cell 2
import numpy as np
import pandas as pd
from statsmodels.tsa.api import VAR

rng = np.random.default_rng(26)
y = np.zeros((400, 2))
for t in range(1, 400):
    y[t] = [0.55*y[t-1,0] + 0.20*y[t-1,1], -0.10*y[t-1,0] + 0.45*y[t-1,1]] + rng.normal(scale=0.6, size=2)
df = pd.DataFrame(y, columns=["x", "z"])
fit = VAR(df).fit(1)
print(fit.coefs[0].round(2))

# **Interpretation check:** Interpretation. The estimated lag matrix is close to the simulated system, with sampling variation.

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

rng = np.random.default_rng(2601)
common = np.cumsum(rng.normal(size=600))
x = common + rng.normal(scale=0.5, size=600)
y = 1.2*common + rng.normal(scale=0.5, size=600)
spread = y - 1.2*x
print(f"{adfuller(spread)[1]:.2e}")

# **Interpretation check:** Interpretation. The constructed spread is stationary even though the two levels inherit a shared stochastic trend.

# %% Cell 6
import numpy as np
import pandas as pd
from statsmodels.tsa.api import VAR
rng = np.random.default_rng(26)
y = np.zeros((400, 2))
df = pd.DataFrame(y, columns=["x", "z"])

# Verified source output
#
# ```text
# [[ 0.55 0.15] [-0.13 0.47]]
# ```
#
# ```text
# 0.00e+00
# ```
#
# ```text
# [[ 0.55  0.15]
#  [-0.13  0.47]]
# ```
