{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7b35d78b-ba36-4c0f-969a-58a2e2e5ab81",
   "metadata": {},
   "source": [
    "# Moving averages in SQL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85beb777-95c3-46fd-9c6f-ae584ac20d95",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pandas import DataFrame\n",
    "import matplotlib.pyplot as plt\n",
    "from data201 import db_connection, df_query\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad0f88cb-d35b-4fcb-9369-74914bdc6381",
   "metadata": {},
   "outputs": [],
   "source": [
    "conn = db_connection(config_file='stock-prices.ini')\n",
    "cursor = conn.cursor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "452f1122-788e-4863-bf83-73f4658772cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "table = cursor.execute('SELECT * FROM recent_prices')\n",
    "table = cursor.fetchall()\n",
    "table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f73e2fe2-df67-4c8c-91f2-0d636739890d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_moving_averages(cursor, n):\n",
    "    \"\"\"\n",
    "    @cursor the database cursor\n",
    "    @n the number of days to average\n",
    "    \"\"\"\n",
    "    cursor.execute(\n",
    "       f\"\"\"\n",
    "        SELECT days_ago, price,\n",
    "            IF ( ROW_NUMBER() OVER (ORDER BY days_ago) >= {n},\n",
    "                 AVG(price) OVER (ORDER BY days_ago\n",
    "                                  ROWS BETWEEN {n - 1} PRECEDING\n",
    "                                  AND CURRENT ROW),\n",
    "                 NULL\n",
    "            )\n",
    "        FROM recent_prices\n",
    "        ORDER BY days_ago\n",
    "        \"\"\"\n",
    "    )\n",
    "    \n",
    "    return cursor.fetchall()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "05c642e3-7669-427f-bbf4-331a06e07a98",
   "metadata": {},
   "outputs": [],
   "source": [
    "table = []\n",
    "columns = ['days ago', 'price']\n",
    "first = True\n",
    "\n",
    "for days in [3, 5, 10]:\n",
    "    graph_label = f'{days}_day_moving_average'\n",
    "    columns += [graph_label,]\n",
    "    \n",
    "    print()\n",
    "    print(graph_label)\n",
    "    print()\n",
    "\n",
    "    averages = compute_moving_averages(cursor, days)\n",
    "    display(averages)\n",
    "\n",
    "    if first:\n",
    "        table = averages.copy()\n",
    "        first = False\n",
    "    else:\n",
    "        for i in range(len(averages)):\n",
    "            table[i] += (averages[i][2],)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5e4a201-d9da-411b-bdb9-d2abbca70711",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = DataFrame(table)\n",
    "df.columns = columns\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b892a3a-b359-46d0-b53f-0d62832fd779",
   "metadata": {},
   "outputs": [],
   "source": [
    "rows = df.values.tolist()\n",
    "xs   = [row[0] for row in rows]\n",
    "ys   = [row[1] for row in rows]\n",
    "\n",
    "plt.figure(figsize=(15, 10))\n",
    "\n",
    "# Initialize the graph and plot the prices.\n",
    "plt.xticks(xs)\n",
    "plt.plot(xs, ys, linewidth=5)\n",
    "plt.title('Moving Average of Stock Prices')\n",
    "plt.xlabel('Days ago')\n",
    "plt.ylabel('Price')\n",
    "\n",
    "days_ago = [3, 5, 10]\n",
    "\n",
    "for i in range(len(days_ago)):\n",
    "    days = days_ago[i]\n",
    "    graph_label = f'{days}_day_moving_average'\n",
    "\n",
    "    xs   = [row[0] for row in rows]\n",
    "    ys   = [row[1] for row in rows]\n",
    "    avgs = [row[i + 2] for row in rows]\n",
    "    \n",
    "    # Plot the moving average line.\n",
    "    plt.plot(xs[days - 1:], avgs[days - 1:], label=graph_label)\n",
    "    \n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11b6bb83-b19f-4835-a6bb-400fe57309b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "conn.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7891457-aeb7-4a21-89ca-518a1752067e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
