import numpy as np
import pandas as pd
from catboost import CatBoostRegressor

URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
y = pd.read_csv(URL, index_col="Month", parse_dates=True)["Passengers"].asfreq("MS")

# trees can't extrapolate a trend, so model the year-on-year log growth instead of the level
growth = np.log(y).diff(12)
X = pd.DataFrame({f"lag{k}": growth.shift(k) for k in (1, 2, 3, 12)})
X["month"] = y.index.month.astype(str)            # categorical: CatBoost encodes it itself
data = X.assign(target=growth).dropna()
train, test = data.iloc[:-12], data.iloc[-12:]

model = CatBoostRegressor(iterations=600, depth=4, learning_rate=0.03, loss_function="RMSE",
                          cat_features=["month"], verbose=0, random_seed=0)
model.fit(train.drop(columns="target"), train["target"])

# one-step-ahead: turn predicted growth back into passengers using the value 12 months earlier
pred_growth = model.predict(test.drop(columns="target"))
forecast = y.shift(12).loc[test.index] * np.exp(pred_growth)
print(f"MAE: {np.mean(np.abs(y.loc[test.index] - forecast)):.1f}")
print(dict(zip(model.feature_names_, model.get_feature_importance().round(1).tolist())))
