{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e00535f1-f5b6-485f-9c63-f25fedf163de",
   "metadata": {},
   "source": [
    "# Moving averages in Python"
   ]
  },
  {
   "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\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": "75bc48de-6157-4328-9437-0e254f3e97ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "table = cursor.execute('SELECT * FROM recent_prices')\n",
    "table = cursor.fetchall()\n",
    "table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "958997f8-09b8-446b-b23b-0ea223c357be",
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_moving_averages(table, n):\n",
    "    \"\"\"\n",
    "    @table the table of days, prices, and averages\n",
    "    @n the number of prices to average\n",
    "    \"\"\"\n",
    "    last_prices = []  # last n prices\n",
    "\n",
    "    for i in range(len(table)):\n",
    "        last_prices += [table[i][1],]  # append a new price\n",
    "        \n",
    "        if i >= n:\n",
    "            last_prices.pop(0)   # remove the oldest price\n",
    "            \n",
    "        if i < n - 1:\n",
    "            table[i] += (None,)  # no average for first n-1 days\n",
    "        else:\n",
    "            table[i] += (sum(last_prices)/n,)  # moving average\n",
    "\n",
    "    return table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8ba64f7-fda6-4cdd-a763-01664e995eea",
   "metadata": {},
   "outputs": [],
   "source": [
    "for days in [3, 5, 10]:\n",
    "    table = compute_moving_averages(table, days)\n",
    "    \n",
    "table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5e4a201-d9da-411b-bdb9-d2abbca70711",
   "metadata": {},
   "outputs": [],
   "source": [
    "columns = ['days ago', 'price']\n",
    "\n",
    "for days in [3, 5, 10]:\n",
    "    label = f'{days}_day_moving_average'\n",
    "    columns += [label,]\n",
    "\n",
    "df = DataFrame(table)\n",
    "df.columns = columns\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56955050-fba0-49d7-9862-55f124390323",
   "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": "ffe8b41a-9987-4f1f-9e5d-ba92cabab966",
   "metadata": {},
   "outputs": [],
   "source": [
    "cursor.close()\n",
    "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
}
