community/modules/files/fsi-montecarlo-on-batch/FSI_MonteCarlo.ipynb (125 lines of code) (raw):

{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "project_id = \"${project_id}\"\n", "dataset_id = \"${dataset_id}\"\n", "table_id = \"${table_id}\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ONI1Xo0-KtAD", "outputId": "fb9ca475-e4ec-4cd0-e0e6-14f409eefd7a" }, "outputs": [], "source": [ "from google.cloud import bigquery\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import pandas as pd\n", "\n", "client = bigquery.Client(project=project_id)\n", "\n", "df = client.query(f'''\n", "SELECT ticker, cast(price AS FLOAT64) AS price, CAST(OFFSET as INTEGER) AS offset, start_date, end_date, iteration\n", "FROM `{project_id}.{dataset_id}.{table_id}`,\n", "UNNEST(simulation_results) as NUMERIC with OFFSET\n", "WHERE epoch_time IN\n", " # Get the latest simulation runs for each Ticker Symbol\n", "(SELECT MAX(epoch_time) FROM `{project_id}.{dataset_id}.{table_id}` GROUP BY ticker)\n", "'''\n", ").to_dataframe()\n", "# Display the data\n", "df" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define a function to plot the data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "def plot_ticker(t,df):\n", "\n", " dtf = df[(df.ticker==t) &(df.offset == 250)].price.describe(include=[np.float64], percentiles=[.05, .01, .001])\n", " cellText = []\n", " for v in dtf.values:\n", " cellText.append([v])\n", " \n", " pltf = df[df.ticker==t].pivot(index='offset', columns='iteration', values='price')\n", " \n", " fig = plt.figure(figsize=(10,5))\n", " ax1 = fig.add_subplot(122)\n", " pltf.plot(legend=False, ax=ax1, xlabel='Time(days)', ylabel='US$', title=f\"{ df[(df.ticker == t) & (df.offset == 0) & (df.iteration == 4)]}\")\n", " ax2 = fig.add_subplot(121)\n", " font_size=10\n", " bbox=[0, 0, .5, 1]\n", " ax2.axis('off')\n", " mpl_table = ax2.table(cellText = cellText, rowLabels=dtf.index.values, bbox=bbox)\n", " mpl_table.auto_set_font_size(False)\n", " mpl_table.set_fontsize(font_size)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 808 }, "id": "jvBmb_KceX7z", "outputId": "42a3ba9f-b68f-4c7b-d928-0fedeed9216c" }, "outputs": [], "source": [ "ticker_list = df.ticker.unique()\n", "for t in ticker_list:\n", " plot_ticker(t,df)" ] } ], "metadata": { "colab": { "provenance": [] }, "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.11.4" } }, "nbformat": 4, "nbformat_minor": 4 }