import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor

URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv"
y = pd.read_csv(URL, index_col="Date", parse_dates=True)["Temp"]

X = pd.DataFrame({f"lag{k}": y.shift(k) for k in (1, 2, 3, 7, 365)})
X["doy"] = y.index.dayofyear
data = X.assign(target=y).dropna()

# three consecutive blocks: fit the model, calibrate the intervals, then test them
n = len(data)
fit, cal, test = data.iloc[: n - 730], data.iloc[n - 730 : n - 365], data.iloc[n - 365 :]
model = HistGradientBoostingRegressor(max_iter=300, learning_rate=0.05, random_state=0)
model.fit(fit.drop(columns="target"), fit["target"])

alpha = 0.1                                                          # target 90% coverage
scores = np.abs(cal["target"] - model.predict(cal.drop(columns="target")))   # nonconformity scores
k = int(np.ceil((len(scores) + 1) * (1 - alpha)))
q = np.sort(scores)[min(k, len(scores)) - 1]                         # finite-sample quantile

pred = model.predict(test.drop(columns="target"))
lo, hi = pred - q, pred + q
covered = np.mean((test["target"] >= lo) & (test["target"] <= hi))
print(f"interval half-width: ±{q:.2f} °C   empirical coverage on the test year: {covered:.1%}")
