Merged PR 5371: Flagging w. random predictor + DWH connection improvements + restructure

Connecting to DWH:
* Any existing notebook (AB, Flagging & Template) now have an initial simplified block to connect to the DWH. This is done to handle the DRY, as we're going to start adding more and more experiment notebooks very soon (and we have already 4 notebooks).
* This reads from a new `utils/dwh_utils.py` in which we handle the connection and test it accordingly.
* This also requires an optional `settings.json` path configuration to avoid warnings (not errors) when reading from `dwh_utils`.

Flagging:
* All flagging notebooks now go within the folder `data_driven_risk_assessment`. The already existing notebook `flagging_performance_monitoring` has also been moved here.
* There's a new `experiments` folder to store the different experiments on flagging.
* A new notebook has been added containing a straight-forward baseline: a random predictor, which randomly flags as risk bookings on a test set based on the observed booking claim rate on a previous train dataset.

I confirm that all existing notebooks work well after the connection changes.

Once merged, or to review, you will need to re-install requirements.txt as I added sklearn.

Related work items: #30804
This commit is contained in:
Oriol Roqué Paniagua 2025-06-10 05:59:12 +00:00
parent 2662f994f0
commit 38f63afbf7
8 changed files with 634 additions and 533 deletions

View file

@ -12,89 +12,39 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This script connects to a Data Warehouse (DWH) using PostgreSQL. \n",
"# This should be common for all Notebooks, but you might need to adjust the path to the `dwh_utils` module.\n",
"\n",
"import sys\n",
"import os\n",
"sys.path.append(os.path.abspath(\"./utils\")) # Adjust path if needed\n",
"\n",
"from dwh_utils import read_credentials, create_postgres_engine, query_to_dataframe, test_connection\n",
"\n",
"# --- Connect to DWH ---\n",
"creds = read_credentials()\n",
"dwh_pg_engine = create_postgres_engine(creds)\n",
"\n",
"# --- Test Query ---\n",
"test_connection()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pathlib\n",
"import yaml\n",
"import pandas as pd\n",
"import numpy as np\n",
"from sqlalchemy import create_engine\n",
"import seaborn as sns\n",
"import matplotlib.pyplot as plt\n",
"from statsmodels.stats.proportion import proportions_ztest\n",
"from scipy import stats\n"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"/home/uri/.superhog-dwh/credentials.yml\n"
]
}
],
"source": [
"CREDS_FILEPATH = pathlib.Path.home() / \".superhog-dwh\" / \"credentials.yml\"\n",
"print(CREDS_FILEPATH)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"# Prepare connection to DWH\n",
"# Function to read credentials from the YAML file\n",
"def read_credentials(yaml_path: str, env: str = \"prd\"):\n",
" with open(yaml_path, \"r\") as file:\n",
" credentials = yaml.safe_load(file)\n",
" return credentials[\"envs\"][env]\n",
"# Function to create a PostgreSQL connection string\n",
"def create_postgres_engine(creds: dict):\n",
" user = creds[\"user\"]\n",
" password = creds[\"password\"]\n",
" host = creds[\"host\"]\n",
" port = creds[\"port\"]\n",
" database = creds[\"database\"]\n",
" # Create the connection string for SQLAlchemy\n",
" connection_string = f\"postgresql://{user}:{password}@{host}:{port}/{database}\"\n",
" engine = create_engine(connection_string)\n",
" return engine\n",
"# Function to execute a query and return the result as a pandas DataFrame\n",
"def query_to_dataframe(engine, query: str):\n",
" with engine.connect() as connection:\n",
" df = pd.read_sql(query, connection)\n",
" return df\n",
"dwh_creds = read_credentials(yaml_path=CREDS_FILEPATH, env=\"prd\")\n",
"dwh_pg_engine = create_postgres_engine(creds=dwh_creds)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" ?column?\n",
"0 1\n"
]
}
],
"source": [
"# Silly query to test things out\n",
"test_df = query_to_dataframe(engine=dwh_pg_engine, query=\"SELECT 1;\")\n",
"print(test_df.head())"
"from scipy import stats"
]
},
{
@ -135,21 +85,9 @@
},
{
"cell_type": "code",
"execution_count": 18,
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Empty DataFrame\n",
"Columns: [ab_test_name, variation, last_update, guest_journeys_count, guest_journey_started_count, guest_journey_completed_count, guest_journey_with_responses_count, guest_journey_with_payment_count, guest_revenue_count, deposit_count, waiver_count, check_in_cover_count, guest_revenue_sum, deposit_sum, waiver_sum, check_in_cover_sum, guest_revenue_avg_per_guest_journey, guest_revenue_sdv_per_guest_journey, deposit_avg_per_guest_journey, deposit_sdv_per_guest_journey, waiver_avg_per_guest_journey, waiver_sdv_per_guest_journey, check_in_cover_avg_per_guest_journey, check_in_cover_sdv_per_guest_journey, csat_avg_per_guest_journey_with_response, csat_sdv_per_guest_journey_with_response]\n",
"Index: []\n",
"\n",
"[0 rows x 26 columns]\n"
]
}
],
"outputs": [],
"source": [
"# Query to extract data\n",
"data_extraction_query = \"\"\"\n",
@ -213,24 +151,9 @@
},
{
"cell_type": "code",
"execution_count": 19,
"execution_count": null,
"metadata": {},
"outputs": [
{
"ename": "IndexError",
"evalue": "single positional indexer is out-of-bounds",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[19], line 9\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[38;5;66;03m# Find the total count and other metadata\u001b[39;00m\n\u001b[1;32m 8\u001b[0m total_count \u001b[38;5;241m=\u001b[39m grouped_data\u001b[38;5;241m.\u001b[39msum()\n\u001b[0;32m----> 9\u001b[0m ab_test_name \u001b[38;5;241m=\u001b[39m \u001b[43mdf\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mab_test_name\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m]\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43miloc\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m \u001b[38;5;66;03m# Assuming all rows are for the same A/B test\u001b[39;00m\n\u001b[1;32m 10\u001b[0m last_update \u001b[38;5;241m=\u001b[39m df[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlast_update\u001b[39m\u001b[38;5;124m'\u001b[39m]\u001b[38;5;241m.\u001b[39mmax()\n\u001b[1;32m 12\u001b[0m \u001b[38;5;66;03m# Create a pie chart using Seaborn styling\u001b[39;00m\n",
"File \u001b[0;32m~/Workspace/data-jupyter-notebooks/venv/lib/python3.12/site-packages/pandas/core/indexing.py:1191\u001b[0m, in \u001b[0;36m_LocationIndexer.__getitem__\u001b[0;34m(self, key)\u001b[0m\n\u001b[1;32m 1189\u001b[0m maybe_callable \u001b[38;5;241m=\u001b[39m com\u001b[38;5;241m.\u001b[39mapply_if_callable(key, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mobj)\n\u001b[1;32m 1190\u001b[0m maybe_callable \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_deprecated_callable_usage(key, maybe_callable)\n\u001b[0;32m-> 1191\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_getitem_axis\u001b[49m\u001b[43m(\u001b[49m\u001b[43mmaybe_callable\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43maxis\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43maxis\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[0;32m~/Workspace/data-jupyter-notebooks/venv/lib/python3.12/site-packages/pandas/core/indexing.py:1752\u001b[0m, in \u001b[0;36m_iLocIndexer._getitem_axis\u001b[0;34m(self, key, axis)\u001b[0m\n\u001b[1;32m 1749\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCannot index by location index with a non-integer key\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 1751\u001b[0m \u001b[38;5;66;03m# validate the location\u001b[39;00m\n\u001b[0;32m-> 1752\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_validate_integer\u001b[49m\u001b[43m(\u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43maxis\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1754\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mobj\u001b[38;5;241m.\u001b[39m_ixs(key, axis\u001b[38;5;241m=\u001b[39maxis)\n",
"File \u001b[0;32m~/Workspace/data-jupyter-notebooks/venv/lib/python3.12/site-packages/pandas/core/indexing.py:1685\u001b[0m, in \u001b[0;36m_iLocIndexer._validate_integer\u001b[0;34m(self, key, axis)\u001b[0m\n\u001b[1;32m 1683\u001b[0m len_axis \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mlen\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mobj\u001b[38;5;241m.\u001b[39m_get_axis(axis))\n\u001b[1;32m 1684\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m key \u001b[38;5;241m>\u001b[39m\u001b[38;5;241m=\u001b[39m len_axis \u001b[38;5;129;01mor\u001b[39;00m key \u001b[38;5;241m<\u001b[39m \u001b[38;5;241m-\u001b[39mlen_axis:\n\u001b[0;32m-> 1685\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mIndexError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124msingle positional indexer is out-of-bounds\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
"\u001b[0;31mIndexError\u001b[0m: single positional indexer is out-of-bounds"
]
}
],
"outputs": [],
"source": [
"# Ensure Seaborn styling\n",
"sns.set_theme(style=\"whitegrid\")\n",
@ -531,25 +454,7 @@
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" metric relative_difference p_value\n",
"0 conversion_rate -0.022089 0.732507\n",
"1 payment_rate -0.019231 0.843783\n",
"2 waiver_payment_rate -0.109637 0.344132\n",
"3 deposit_payment_rate 0.358974 0.297872\n",
"4 CIH_payment_rate -0.235577 0.722020\n",
"5 avg_guest_revenue_per_gj -0.087267 0.434288\n",
"6 avg_waiver_revenue_per_gj -0.104328 0.391617\n",
"7 avg_deposit_revenue_per_gj 0.264787 0.459148\n",
"8 avg_CIH_revenue_per_gj -0.191473 0.779274\n",
"9 avg_csat_per_gj_with_response 0.133721 0.051334\n"
]
}
],
"outputs": [],
"source": [
"# Call the function to calculate the Z-test for each metric and aggregate the results\n",
"z_test_results_df = run_z_tests(df, z_stat_metric_definition=z_stat_metric_definition, variations=variations)\n",
@ -579,36 +484,7 @@
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"WelcomePageDestinationContext results (last updated at 2025-05-27)\n",
"\n",
"Total Guest Journeys affected by this A/B test: 420 - Total Guest Revenue: 5280 GBP.\n",
" Variation GenericImageAndCopy: Guest Journeys 212 (50.5%) - Guest Revenue: 2786 GBP (52.8%).\n",
" Variation ContextSpecificImageAndCopy: Guest Journeys 208 (49.5%) - Guest Revenue: 2494 GBP (47.2%).\n",
"\n",
"Main Metrics - Comparing ContextSpecificImageAndCopy vs. GenericImageAndCopy.\n",
"\n",
"CONVERSION RATE (not significant): 68.3% vs. 69.8% (-1.5% ppts.| -2.2%).\n",
"PAYMENT RATE (not significant): 49.0% vs. 50.0% (-1.0% ppts.| -1.9%).\n",
"AVG GUEST REVENUE PER GJ (not significant): 11.99 vs. 13.14 (-1.15 ppts.| -8.7%).\n",
"\n",
"Other Metrics\n",
"\n",
"WAIVER PAYMENT RATE (not significant): 36.5% vs. 41.0% (-4.5% ppts.| -11.0%).\n",
"DEPOSIT PAYMENT RATE (not significant): 11.5% vs. 8.5% (3.0% ppts.| 35.9%).\n",
"CIH PAYMENT RATE (not significant): 1.4% vs. 1.9% (-0.4% ppts.| -23.6%).\n",
"AVG WAIVER REVENUE PER GJ (not significant): 11.05 vs. 12.34 (-1.29 ppts.| -10.4%).\n",
"AVG DEPOSIT REVENUE PER GJ (not significant): 0.82 vs. 0.65 (0.17 ppts.| 26.5%).\n",
"AVG CIH REVENUE PER GJ (not significant): 0.13 vs. 0.16 (-0.03 ppts.| -19.1%).\n",
"AVG CSAT PER GJ WITH RESPONSE (not significant): 3.75 vs. 3.31 (0.44 ppts.| 13.4%).\n"
]
}
],
"outputs": [],
"source": [
"print('\\n{} results (last updated at {})\\n'.format(ab_test_name, last_update))\n",
"\n",