# pip install neuralforecast   (needs PyTorch)
import pandas as pd
from neuralforecast import NeuralForecast
from neuralforecast.models import iTransformer

URL = "https://raw.githubusercontent.com/zhouhaoyi/ETDataset/main/ETT-small/ETTh1.csv"
raw = pd.read_csv(URL, parse_dates=["date"])
# long format: one row per (variable, timestamp): iTransformer turns each variable into one token
df = raw.melt(id_vars="date", var_name="unique_id", value_name="y").rename(columns={"date": "ds"})
H, n_series = 96, df["unique_id"].nunique()      # 7 variables
cut = df["ds"].sort_values().unique()[-H]
train, test = df[df["ds"] < cut], df[df["ds"] >= cut]

model = iTransformer(h=H, input_size=336, n_series=n_series, hidden_size=128, n_heads=8,
                     e_layers=2, scaler_type="standard", max_steps=1000, random_seed=1)
nf = NeuralForecast(models=[model], freq="h")
nf.fit(df=train)
fc = nf.predict().merge(test, on=["unique_id", "ds"])
print(fc.groupby("unique_id").apply(lambda g: (g["y"] - g["iTransformer"]).abs().mean()).round(3))
