from arch import arch_model
from arch.data import sp500

prices = sp500.load()["Adj Close"]
returns = 100 * prices.pct_change().dropna()        # percent returns help the optimiser

# GJR-GARCH(1,1) with Student-t errors: the leverage term (o=1) lets bad news raise volatility more
model = arch_model(returns, mean="Constant", vol="GARCH", p=1, o=1, q=1, dist="t")
res = model.fit(disp="off", last_obs="2017-12-31")  # fit on data up to the end of 2017
print(res.params.round(4))

a, g, b = res.params["alpha[1]"], res.params["gamma[1]"], res.params["beta[1]"]
print(f"persistence α + γ/2 + β = {a + g / 2 + b:.3f}")

fc = res.forecast(horizon=10, start="2017-12-29", reindex=False)
print((fc.variance.iloc[0] ** 0.5).round(3))         # 1- to 10-day-ahead volatility, % per day
