# Time series examples: six charts from freely available data
# Dr Nicky Grant, drnickygrant.com. Companion to the ECON30401 lecture notes, weeks 1 and 2.
# Needs: pandas, numpy, matplotlib, scipy   (pip install pandas numpy matplotlib scipy)
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm

# Clean copies of each series, with their sources, are kept on the site.
BASE = os.environ.get("TS_DATA", "https://www.drnickygrant.com/teaching/data/")
OUT = os.environ.get("TS_OUT", ".")
plt.rcParams.update({"font.family": "DejaVu Serif", "font.size": 11,
                     "axes.spines.top": False, "axes.spines.right": False})


def monthly(file):
    """Read a month,value file and index it by month."""
    d = pd.read_csv(BASE + file)
    d.index = pd.PeriodIndex(d["month"], freq="M").to_timestamp()
    return d.iloc[:, 1]


def save(fig, name):
    fig.tight_layout()
    fig.savefig(os.path.join(OUT, name), dpi=200)
    plt.close(fig)


# 1. UK CPI inflation to August 2016 with a fan of AR(1) forecasts (ONS series D7G7)
cpi = monthly("uk-cpi-inflation-d7g7.csv")
y = cpi[:"2016-08"].to_numpy()
X = np.column_stack([np.ones(len(y) - 1), y[:-1]])
(c, phi), *_ = np.linalg.lstsq(X, y[1:], rcond=None)      # OLS of y_t on 1 and y_{t-1}
resid = y[1:] - X @ np.array([c, phi])
sigma = np.sqrt(resid @ resid / (len(resid) - 2))
H = 36                                                      # forecast three years ahead
mean, var, f, se = y[-1], 0.0, [], []
for h in range(H):
    mean = c + phi * mean                                   # E[Y_{T+h} | Y_T]
    var = sigma**2 + phi**2 * var                           # forecast-error variance
    f.append(mean); se.append(np.sqrt(var))
f, se = np.array(f), np.array(se)
months = pd.date_range("2016-08-01", periods=H + 1, freq="MS")
fig, ax = plt.subplots(figsize=(6.2, 4.6))
hist = cpi["2012-01":"2016-08"]
ax.plot(hist.index, hist, color="#b22222", lw=1.6)
for share, colour in [(0.90, "#f6c7b6"), (0.60, "#ef9a84"), (0.30, "#e06650")]:
    z = norm.ppf(0.5 + share / 2)
    ax.fill_between(months, np.r_[y[-1], f - z * se], np.r_[y[-1], f + z * se], color=colour, lw=0)
ax.axvspan(months[0], months[-1], color="0.93", zorder=-1)
ax.axhline(2, color="0.4", lw=0.8, ls="--")
ax.set_ylabel("% change on a year earlier")
ax.set_title("UK CPI inflation and an AR(1) forecast fan", fontsize=11)
save(fig, "fig1-uk-cpi-forecast-fan.png")

# 2. Daily FTSE 100 returns, 1991 to 1998 (R datasets package, EuStockMarkets)
ftse = pd.read_csv(BASE + "ftse-daily-1991-1998.csv")
ret = 100 * np.log(ftse["ftse"]).diff()
fig, ax = plt.subplots(figsize=(7.6, 3.0))
ax.plot(ftse["time"], ret, color="k", lw=0.5)
ax.axhline(0, color="0.5", lw=0.6)
ax.set_ylabel("log return, %")
ax.set_xlabel("Daily FTSE 100 returns, 1991 to 1998")
save(fig, "fig2-ftse-daily-returns.png")

# 3. US population at each census, 1790 to 1990 (US Census Bureau)
pop = pd.read_csv(BASE + "us-population-1790-1990.csv")
fig, ax = plt.subplots(figsize=(6.0, 4.2))
ax.plot(pop["year"], pop["population_millions"], "s-", color="k", ms=4, mfc="white", lw=0.9)
ax.set_ylabel("millions")
ax.set_xlabel("US population at each census, 1790 to 1990")
save(fig, "fig3-us-population.png")

# 4. UK unemployment rate, monthly (ONS series MGSX)
u = monthly("uk-unemployment-rate-mgsx.csv")
fig, ax = plt.subplots(figsize=(6.0, 4.2))
ax.plot(u.index, u, color="k", lw=0.9)
ax.set_ylabel("%")
ax.set_xlabel("UK unemployment rate, monthly")
save(fig, "fig4-uk-unemployment.png")

# 5. UK retail sales, value, not seasonally adjusted, 2010 to 2019 (ONS series J5AH)
r = monthly("uk-retail-sales-j5ah.csv")["2010-01":"2019-12"]
fig, ax = plt.subplots(figsize=(6.0, 4.2))
ax.plot(r.index, r, "s-", color="k", ms=2.5, mfc="white", lw=0.8)
ax.set_ylabel("index")
ax.set_xlabel("UK retail sales, monthly, not seasonally adjusted")
save(fig, "fig5-uk-retail-sales.png")

# 6. UK Bank Rate at the end of each month, 1987 to 2017 (Bank of England)
br = monthly("uk-bank-rate-1987-2017.csv")
fig, ax = plt.subplots(figsize=(6.0, 3.3))
ax.step(br.index, br, where="post", color="#0f5c5c", lw=1.4)
ax.set_ylabel("%")
ax.set_xlabel("UK Bank Rate, 1987 to 2017")
save(fig, "fig6-uk-bank-rate.png")
print("Six charts written to", os.path.abspath(OUT))
