{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8a2b2530",
   "metadata": {},
   "source": [
    "<div style=\"background-color:#000;\"><img src=\"pqn.png\"></img></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70c08f76",
   "metadata": {},
   "source": [
    "This code retrieves U.S. Treasury bond yield data using the OpenBB SDK and visualizes the yield curve over time. It sets up the necessary imports, initializes plotting parameters, and configures the OpenBB SDK with a FRED API key. The script extracts treasury yield data for various maturities and indicates whether the yield curve is inverted. An animation is created to dynamically display the yield curve changes over time, highlighting inversions in red."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f47685af",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.animation as animation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "876b4eac",
   "metadata": {},
   "outputs": [],
   "source": [
    "from openbb_terminal.sdk import openbb"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77931a95",
   "metadata": {},
   "source": [
    "Define font properties for the plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21676002",
   "metadata": {},
   "outputs": [],
   "source": [
    "font = {\n",
    "    \"family\": \"normal\",\n",
    "    \"weight\": \"normal\",\n",
    "    \"size\": 12\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8a309f7",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.rc('font', **font)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24fa7787",
   "metadata": {},
   "source": [
    "Configure OpenBB SDK with FRED API key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3632ee19",
   "metadata": {},
   "outputs": [],
   "source": [
    "openbb.keys.fred(\n",
    "    key=\"3d20c1fcbb26ea21b9f78fafbbdce900\",\n",
    "    persist=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8bad0715",
   "metadata": {},
   "source": [
    "Define treasury bond maturities to be retrieved"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab0acba1",
   "metadata": {},
   "outputs": [],
   "source": [
    "maturities = ['3m', '6m', '1y', '2y', '3y', '5y', '7y', '10y', '30y']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "717bade2",
   "metadata": {},
   "source": [
    "Retrieve treasury bond yield data from OpenBB SDK for specified maturities and time range"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55e6010a",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = openbb.economy.treasury(\n",
    "    instruments=[\"nominal\"],\n",
    "    maturities=maturities,\n",
    "    start_date=\"1985-01-01\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4edab174",
   "metadata": {},
   "source": [
    "Rename columns to match maturities list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96be72bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "data.columns = maturities"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad0285d8",
   "metadata": {},
   "source": [
    "Add a column to indicate if yield curve is inverted (30y yield less than 3m yield)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b852c95a",
   "metadata": {},
   "outputs": [],
   "source": [
    "data[\"inverted\"] = data[\"30y\"] < data[\"3m\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ee1c2ee",
   "metadata": {},
   "source": [
    "Initialize plot figure and axis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a134e05",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure()\n",
    "ax = fig.add_subplot(1, 1, 1)\n",
    "line, = ax.plot([], [])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c115cca",
   "metadata": {},
   "source": [
    "Set x and y-axis limits for the plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c552c60f",
   "metadata": {},
   "outputs": [],
   "source": [
    "ax.set_xlim(0, 7)\n",
    "ax.set_ylim(0, 20)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6014ed6b",
   "metadata": {},
   "source": [
    "Define tick locations and labels for both axes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24cb514e",
   "metadata": {},
   "outputs": [],
   "source": [
    "ax.set_xticks(range(8))\n",
    "ax.set_yticks([2, 4, 6, 8, 10, 12, 14, 16, 18])\n",
    "ax.set_xticklabels([\"1m\",\"3m\",\"6m\",\"1y\",\"5y\",\"10y\",\"20y\",\"30y\"])\n",
    "ax.set_yticklabels([2, 4, 6, 8, 10, 12, 14, 16, 18])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c3581ec",
   "metadata": {},
   "source": [
    "Force y-axis labels to appear on the left side"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af5728b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "ax.yaxis.set_label_position(\"left\")\n",
    "ax.yaxis.tick_left()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e34a8998",
   "metadata": {},
   "source": [
    "Add labels for both axes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e470b81",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "plt.ylabel(\"Yield (%)\")\n",
    "plt.xlabel(\"Time to maturty\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25541eb8",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def init_func():\n",
    "    \"\"\"Initialize plot with empty data and title\"\"\"\n",
    "    line.set_data([], [])\n",
    "    plt.title(\"U.S. Treasury Bond Yield Curve\")\n",
    "    return line"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3826d2c",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def animate(i):\n",
    "    \"\"\"Update plot data for each frame in the animation\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    i : int\n",
    "        Current frame index\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    line : Line2D object\n",
    "    \"\"\"\n",
    "    x = range(0, len(maturities))\n",
    "    y = data[maturities].iloc[i]\n",
    "    dt_ = data.index[i].strftime(\"%Y-%m-%d\")\n",
    "    \n",
    "    # Change line color based on yield curve inversion\n",
    "    if data.inverted.iloc[i]:\n",
    "        line.set_color(\"r\")\n",
    "    else:\n",
    "        line.set_color(\"y\")\n",
    "    \n",
    "    line.set_data(x, y)\n",
    "    \n",
    "    plt.title(f\"U.S. Treasury Bond Yield Curve ({dt_})\")\n",
    "    return line,"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "144c195f",
   "metadata": {},
   "source": [
    "Create animation for the yield curve using the animate function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ccd9ff8",
   "metadata": {},
   "outputs": [],
   "source": [
    "ani = animation.FuncAnimation(\n",
    "    fig, animate, init_func=init_func, frames=len(data.index), interval=5, blit=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "305bb8bf",
   "metadata": {},
   "source": [
    "<a href=\"https://pyquantnews.com/\">PyQuant News</a> is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to <a href=\"https://gettingstartedwithpythonforquantfinance.com/\">get started with Python for quant finance</a>. For educational purposes. Not investment advise. Use at your own risk."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
