#!/usr/bin/env python3 """Ch. 30, figure « gdc » (DONNÉES RÉELLES, Banque du Canada, API Valet, téléchargées le 2026-10-31) : rendements des obligations de référence du gouvernement du Canada à 5 et 10 ans et taux hypothécaire conventionnel 5 ans affiché, moyennes mensuelles 2006-2026. Sortie : ch30-fig-gdc.pdf.""" from __future__ import annotations import sys, pathlib, io sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) import pandas as pd, matplotlib.pyplot as plt from traite.style import setup, palette, savefig, LARGEUR, ROOT RAW = ROOT / "data/raw/bdc_valet" def lire(nom: str) -> pd.Series: txt = (RAW / f"{nom}.csv").read_text(encoding="utf-8-sig") obs = txt[txt.index('"OBSERVATIONS"'):].split("\n", 1)[1] df = pd.read_csv(io.StringIO(obs)); df.columns = ["date", "val"] df["date"] = pd.to_datetime(df["date"]); df["val"] = pd.to_numeric(df["val"], errors="coerce") return df.dropna().set_index("date")["val"] def main(): setup() s10 = lire("BD.CDN.10YR.DQ.YLD"); s5 = lire("BD.CDN.5YR.DQ.YLD"); hyp = lire("V80691335") deb = "2006-01-01" m10 = s10[deb:].resample("MS").mean(); m5 = s5[deb:].resample("MS").mean(); mh = hyp[deb:].resample("MS").mean() fig, ax = plt.subplots(figsize=(LARGEUR, 3.2)) ax.plot(mh.index, mh.values, color=palette.cat[1], lw=1.4, label="Taux hypothécaire conventionnel 5 ans affiché (V80691335)") ax.plot(m10.index, m10.values, color=palette.cat[0], lw=1.6, label="Obligation GdC 10 ans (BD.CDN.10YR.DQ.YLD)") ax.plot(m5.index, m5.values, color=palette.cat[2], lw=1.2, label="Obligation GdC 5 ans (BD.CDN.5YR.DQ.YLD)") last10 = s10.iloc[-1]; lasth = hyp.iloc[-1] ax.annotate(f"{last10:.2f} % (29 oct. 2026)".replace(".", ","), xy=(s10.index[-1], last10), xytext=(pd.Timestamp("2022-03-01"), 1.0), fontsize=8, arrowprops=dict(arrowstyle="-", color=palette.ink2, lw=0.7)) ax.annotate(f"{lasth:.2f} %".replace(".", ","), xy=(hyp.index[-1], lasth), xytext=(pd.Timestamp("2024-09-01"), 7.6), fontsize=8, arrowprops=dict(arrowstyle="-", color=palette.ink2, lw=0.7)) ax.set_ylabel("Taux (%)"); ax.set_ylim(0, 9) ax.legend(loc="upper right", fontsize=7.5) savefig(fig, "ch30/ch30-fig-gdc.pdf") if __name__ == "__main__": main()