import numpy as np
import pandas as pd
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ExpSineSquared, WhiteKernel, ConstantKernel as C

URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
y = pd.read_csv(URL, index_col="Month", parse_dates=True)["Passengers"]
t = np.arange(len(y), dtype=float).reshape(-1, 1)          # time index in months
z = np.log(y.values)
t_tr, z_tr, t_te = t[:-12], z[:-12], t[-12:]

kernel = (C(1.0) * RBF(length_scale=60.0)                                    # long-term trend
          + C(0.1) * ExpSineSquared(length_scale=1.0, periodicity=12.0,
                                    periodicity_bounds="fixed") * RBF(100.0)  # slowly changing yearly cycle
          + WhiteKernel(noise_level=1e-3))                                    # observation noise
gp = GaussianProcessRegressor(kernel=kernel, normalize_y=True, n_restarts_optimizer=3, random_state=0)
gp.fit(t_tr, z_tr)
print("learned kernel:", gp.kernel_)

mean, std = gp.predict(t_te, return_std=True)
forecast, lo, hi = np.exp(mean), np.exp(mean - 1.28 * std), np.exp(mean + 1.28 * std)   # 80% band
print(f"MAE: {np.mean(np.abs(y.values[-12:] - forecast)):.1f}")
print(f"80% band covers {np.mean((y.values[-12:] >= lo) & (y.values[-12:] <= hi)):.0%} of the test months")
