{ "cells": [ { "cell_type": "markdown", "id": "b05d41ed-eeb0-4936-85ab-dbf12efc82d4", "metadata": {}, "source": [ "# Exponential smoothing in SQL" ] }, { "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, df_query\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')" ] }, { "cell_type": "code", "execution_count": null, "id": "c08c9a81-7d93-4814-bbda-441a850331f0", "metadata": {}, "outputs": [], "source": [ "def compute_exponential_smoothings(conn, alpha, label):\n", " \"\"\"\n", " @conn the database connection\n", " @alpha the alpha value for exponential smoothing\n", " @label label for the exponentially smoothed values\n", " \"\"\"\n", " conn.cursor().execute('SET @smoothed = NULL')\n", " \n", " return df_query(conn,\n", " f\"\"\" \n", " SELECT days_ago, price,\n", " @smoothed := ({alpha}*price\n", " + (1-{alpha})*(IF (@smoothed IS NULL, price, @smoothed)))\n", " AS '{label}'\n", " FROM recent_prices\n", " ORDER BY days_ago\n", " \"\"\"\n", " )" ] }, { "cell_type": "code", "execution_count": null, "id": "8c1c0f1f-5020-48fc-bdb5-575d15df9791", "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(15, 10))\n", "\n", "first = True\n", "\n", "for a in [5, 2]:\n", " alpha = a/10\n", " graph_label = f'{alpha = }'\n", " \n", " df = compute_exponential_smoothings(conn, alpha, 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", " exps = [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('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 }