{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b90dfeb2-dbc8-4675-b91e-32f290a2798e",
   "metadata": {},
   "source": [
    "# Exponential smoothing in Python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bbf544a-2be3-4579-ade3-404f4d850ef1",
   "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": "2dcedb2f-42ab-4b8a-bc71-8c9bdeb59793",
   "metadata": {},
   "outputs": [],
   "source": [
    "conn = db_connection(config_file='stock-prices.ini')\n",
    "cursor = conn.cursor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d660401-5a87-4e00-a6b5-2cfa83f9ae0c",
   "metadata": {},
   "outputs": [],
   "source": [
    "table = cursor.execute('SELECT * FROM recent_prices')\n",
    "table = cursor.fetchall()\n",
    "table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15cf6629-4564-47ad-8bb9-ae94aa74a4c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_exponential_smoothing(table, alpha):\n",
    "    \"\"\"\n",
    "    @table the table of days, prices, and averages\n",
    "    @alpha the alpha for exponential smoothing\n",
    "    \"\"\"\n",
    "    smoothed = None\n",
    "    \n",
    "    for i in range(len(table)):\n",
    "        price = table[i][1]\n",
    "        smoothed = (alpha*price\n",
    "                 + (1 - alpha)*(price if smoothed is None else smoothed))\n",
    "        table[i] += (smoothed,)\n",
    "\n",
    "    return table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39a095c7-6d3e-4462-8e7f-47e7e6946000",
   "metadata": {},
   "outputs": [],
   "source": [
    "for alpha in [0.5, 0.2]:\n",
    "    table = compute_exponential_smoothing(table, alpha)\n",
    "\n",
    "table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "368700e8-8e7e-4385-a464-7502568f7294",
   "metadata": {},
   "outputs": [],
   "source": [
    "columns = ['days ago', 'price']\n",
    "\n",
    "for alpha in [0.5, 0.2]:\n",
    "    label = f'{alpha = }'\n",
    "    columns += [label,]\n",
    "\n",
    "df = DataFrame(table)\n",
    "df.columns = columns\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9a30b7c5-2426-4694-93e2-4d2d3984c720",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(15, 10))\n",
    "\n",
    "alphas = [0.5, 0.2]\n",
    "first = True\n",
    "\n",
    "for i in range(len(alphas)):\n",
    "    alpha = alphas[i]\n",
    "    graph_label = f'{alpha = }'\n",
    "\n",
    "    rows = df.values.tolist()\n",
    "    xs   = [row[0] for row in rows]\n",
    "    ys   = [row[1] for row in rows]\n",
    "    exps = [row[i + 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('Exponentially Smoothed 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, exps, label=graph_label)\n",
    "    \n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b750ca51-c26e-43df-98b3-ec64a65eff16",
   "metadata": {},
   "outputs": [],
   "source": [
    "conn.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e9ace8a-3452-456d-aa22-2c88df721822",
   "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
}
