{
 "cells": [
  {
   "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 DATA225utils import make_connection, dataframe_query\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad0f88cb-d35b-4fcb-9369-74914bdc6381",
   "metadata": {},
   "outputs": [],
   "source": [
    "conn = make_connection(config_file='stock-prices.ini')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e94198c-77f5-444c-8052-5235596aa432",
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_moving_average(conn, days, label):\n",
    "    \"\"\"\n",
    "    @cursor the database cursor\n",
    "    @count the number of days for the moving average\n",
    "    @label label for the moving average\n",
    "    \"\"\"\n",
    "    _, df = dataframe_query(conn,\n",
    "        f'SELECT days_ago, price, '\n",
    "        f'       CASE WHEN ROW_NUMBER() OVER (ORDER BY days_ago) >= {days} '\n",
    "        f'           THEN AVG(price) OVER (ORDER BY days_ago '\n",
    "        f'                                 ROWS BETWEEN {days - 1} PRECEDING '\n",
    "        f'                                 AND CURRENT ROW) '\n",
    "        f'           ELSE NULL '\n",
    "        f'       END AS {label} '\n",
    "        f'FROM recent_prices '\n",
    "        f'ORDER BY days_ago'\n",
    "    )\n",
    "    \n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6422882-56b3-4d47-b34f-3c3a878e58f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(15, 10))\n",
    "\n",
    "first = True\n",
    "\n",
    "for days in [3, 5, 10]:\n",
    "    graph_label = f'{days}_day_moving_average'\n",
    "    \n",
    "    df = compute_moving_average(conn, days, graph_label)\n",
    "    display(df)        \n",
    "\n",
    "    rows = df.values.tolist()\n",
    "    xs   = [row[0] for row in rows]\n",
    "    ys   = [row[1] for row in rows]\n",
    "    avgs = [row[2] for row in rows]\n",
    "    \n",
    "    # Initialize the graph.\n",
    "    if first:\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",
    "        first = False\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": "markdown",
   "id": "0fe44922-50fb-4284-943a-82bf05ea190f",
   "metadata": {},
   "source": [
    "#### (c) 2023 by Ronald Mak"
   ]
  },
  {
   "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.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}