"""
Forecasting India's GDP with SARIMA  (airline model, SARIMA(0,1,1)(0,1,1)_4)
==========================================================================
Prof. V. Ravichandran | The Mountain Path Academy | https://themountainpathacademy.com
Guide: https://themountainpathacademy.com/india-gdp-sarima-forecasting

Reads the linked MoSPI series from the guide's Excel workbook, estimates the model
with a dummy for each COVID-affected quarter, checks the residuals, back-tests
against a naive rule, and forecasts the next four quarters with 80% / 95% intervals.

    pip install pandas numpy statsmodels matplotlib openpyxl
    python gdp_sarima_forecast.py india-gdp-sarima-forecast.xlsx
"""
import sys
import warnings

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.tsa.statespace.sarimax import SARIMAX

warnings.filterwarnings("ignore")
ORDER, SEASONAL = (0, 1, 1), (0, 1, 1, 4)
COVID = ["Q1 FY21", "Q2 FY21", "Q3 FY21", "Q4 FY21", "Q1 FY22"]
H = 4


def load(path):
    df = pd.read_excel(path, sheet_name="Linked_Series", header=4)
    df = df[["Quarter", "Quarter end", "Real GDP (₹ lakh crore)"]].dropna()
    df.columns = ["label", "qend", "gdp"]
    return df.reset_index(drop=True)


def next_labels(last, h):
    q, fy = int(last[1]), int(last.split("FY")[1])
    out = []
    for _ in range(h):
        q += 1
        if q == 5:
            q, fy = 1, fy + 1
        out.append(f"Q{q} FY{fy:02d}")
    return out


def dummies(labels):
    return pd.DataFrame({c: (labels == c).astype(float) for c in COVID})


def fit(gdp, labels):
    # a dated quarterly index helps the optimiser reach the true maximum of the likelihood
    idx = pd.period_range("2011Q2", periods=len(gdp), freq="Q-DEC")
    y = pd.Series(np.log(np.asarray(gdp, dtype=float)), index=idx)
    X = dummies(np.asarray(labels)).set_index(idx)
    return SARIMAX(y, exog=X, order=ORDER, seasonal_order=SEASONAL).fit(disp=False, method='bfgs', maxiter=2000)


def forecast(res, gdp, h=H):
    f = res.get_forecast(h, exog=pd.DataFrame(0.0, index=range(h), columns=COVID).values)
    m, se = np.asarray(f.predicted_mean), np.asarray(f.se_mean)
    base = np.concatenate([gdp, np.exp(m)])[len(gdp) - 4: len(gdp) - 4 + h]
    g = lambda x: (np.exp(x) / base - 1) * 100
    return pd.DataFrame({"gdp_lakh_cr": np.exp(m), "yoy_%": g(m), "lo80": g(m - 1.2816 * se), "hi80": g(m + 1.2816 * se),
                         "lo95": g(m - 1.96 * se), "hi95": g(m + 1.96 * se)})


def backtest(df, start=24):
    yoy = df.gdp / df.gdp.shift(4) - 1
    e_s, e_n = {h: [] for h in range(1, 5)}, {h: [] for h in range(1, 5)}
    for t in range(start, len(df) - 1):
        tr = df.iloc[: t + 1]
        try:
            fc = forecast(fit(tr.gdp.values, tr.label.values), tr.gdp.values)
        except Exception:
            continue
        last = (tr.gdp.iloc[-1] / tr.gdp.iloc[-5] - 1) * 100
        for h in range(1, 5):
            j = t + h
            if j < len(df) and df.label[j] not in COVID:
                e_s[h].append(fc["yoy_%"].iloc[h - 1] - yoy[j] * 100)
                e_n[h].append(last - yoy[j] * 100)
    rm = lambda e: np.sqrt(np.mean(np.square(e)))
    return pd.DataFrame({"SARIMA": [rm(e_s[h]) for h in e_s], "Naive": [rm(e_n[h]) for h in e_n]},
                        index=[f"h={h}" for h in e_s]).round(2)


def main(path):
    df = load(path)
    res = fit(df.gdp.values, df.label.values)
    print(res.summary().tables[1])
    print("\nLjung-Box:\n", acorr_ljungbox(res.resid[5:], lags=[4, 8], model_df=2, return_df=True).round(3))
    fc = forecast(res, df.gdp.values)
    fc.index = next_labels(df.label.iloc[-1], H)
    print("\nForecast:\n", fc.round(2))
    fy26 = df.gdp.iloc[-6:-2].sum()
    print(f"\nImplied FY27 growth: {((df.gdp.iloc[-2:].sum() + fc.gdp_lakh_cr.iloc[:2].sum()) / fy26 - 1) * 100:.2f}%")
    print("\nBack-test RMSE (pp):\n", backtest(df))

    hist = (df.gdp / df.gdp.shift(4) - 1).iloc[-20:] * 100
    x_h, x_f = list(df.label.iloc[-20:]), list(fc.index)
    xb = [x_h[-1]] + x_f
    fig, ax = plt.subplots(figsize=(11, 5.5))
    ax.plot(x_h, hist.values, color="#123a63", lw=2.5, marker="o", label="Actual YoY growth")
    ax.fill_between(xb, [hist.iloc[-1]] + list(fc.lo95), [hist.iloc[-1]] + list(fc.hi95), color="#c0972f", alpha=.18, label="95%")
    ax.fill_between(xb, [hist.iloc[-1]] + list(fc.lo80), [hist.iloc[-1]] + list(fc.hi80), color="#c0972f", alpha=.38, label="80%")
    ax.plot(xb, [hist.iloc[-1]] + list(fc["yoy_%"]), color="#8e2130", lw=2.5, ls="--", marker="o", label="SARIMA forecast")
    ax.set_title("India real GDP growth: actual and SARIMA forecast", loc="left", color="#123a63", fontweight="bold")
    ax.set_ylabel("% YoY"); ax.grid(alpha=.25); ax.legend(frameon=False, ncol=2); plt.xticks(rotation=45)
    fig.text(.99, .01, "themountainpathacademy.com", ha="right", fontsize=8, color="#123a63")
    plt.tight_layout(); plt.savefig("sarima_forecast.png", dpi=150)
    print("\nChart saved: sarima_forecast.png")


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "india-gdp-sarima-forecast.xlsx")
