Here's a step-by-step guide with code to pull all event counts from GA4 data and determine outlier status:
Step 1: Connect to BigQuery and Set Up Environment
from google.cloud import bigquery
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
# Initialize BigQuery client
client = bigquery.Client(project='your-project-id')
# Set your GA4 dataset
dataset_id = 'your-project-id.analytics_123456789' # Replace with your GA4 dataset
Step 2: Query GA4 Data for Event Counts
# Query to get event counts by various dimensions
query = """
WITH event_counts AS (
SELECT
event_date,
event_name,
user_pseudo_id,
COUNT(*) as event_count,
-- Additional metrics
COUNT(DISTINCT user_pseudo_id) as unique_users,
AVG(CAST(event_value_in_usd AS FLOAT64)) as avg_event_value
FROM
`{dataset_id}.events_*`
WHERE
_TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY))
AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
AND event_name NOT IN ('session_start', 'first_visit') -- Exclude system events if needed
GROUP BY
event_date,
event_name,
user_pseudo_id
),
daily_aggregates AS (
SELECT
event_date,
event_name,
SUM(event_count) as total_daily_events,
COUNT(DISTINCT user_pseudo_id) as daily_unique_users,
AVG(event_count) as avg_events_per_user,
STDDEV(event_count) as stddev_events_per_user
FROM
event_counts
GROUP BY
event_date,
event_name
)
SELECT
ec.*,
da.total_daily_events,
da.avg_events_per_user,
da.stddev_events_per_user
FROM
event_counts ec
JOIN
daily_aggregates da
ON
ec.event_date = da.event_date
AND ec.event_name = da.event_name
ORDER BY
event_date DESC,
event_name,
event_count DESC
""".format(dataset_id=dataset_id)
# Execute query
df = client.query(query).to_dataframe()
print(f"Retrieved {len(df)} rows of event data")
Step 3: Calculate Statistical Thresholds for Outliers
def calculate_outlier_thresholds(df, column, method='iqr'):
"""
Calculate outlier thresholds using different methods
"""
if method == 'iqr':
# Interquartile Range method
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
elif method == 'zscore':
# Z-score method (3 standard deviations)
mean = df[column].mean()
std = df[column].std()
lower_bound = mean - 3 * std
upper_bound = mean + 3 * std
elif method == 'mad':
# Median Absolute Deviation method
median = df[column].median()
mad = np.median(np.abs(df[column] - median))
modified_z_score = 0.6745 * (df[column] - median) / mad
lower_bound = median - 3.5 * mad / 0.6745
upper_bound = median + 3.5 * mad / 0.6745
return lower_bound, upper_bound
# Calculate thresholds for each event type
outlier_thresholds = {}
for event_name in df['event_name'].unique():
event_df = df[df['event_name'] == event_name]
# Calculate thresholds using multiple methods
iqr_bounds = calculate_outlier_thresholds(event_df, 'event_count', 'iqr')
zscore_bounds = calculate_outlier_thresholds(event_df, 'event_count', 'zscore')
outlier_thresholds[event_name] = {
'iqr_lower': iqr_bounds[0],
'iqr_upper': iqr_bounds[1],
'zscore_lower': zscore_bounds[0],
'zscore_upper': zscore_bounds[1],
'mean': event_df['event_count'].mean(),
'median': event_df['event_count'].median(),
'std': event_df['event_count'].std()
}
Step 4: Identify Outliers
def identify_outliers(row, thresholds):
"""
Identify if a row is an outlier based on multiple criteria
"""
event_name = row['event_name']
event_count = row['event_count']
if event_name not in thresholds:
return False, 'Unknown event'
thresh = thresholds[event_name]
outlier_reasons = []
# Check IQR method
if event_count < thresh['iqr_lower'] or event_count > thresh['iqr_upper']:
outlier_reasons.append('IQR')
# Check Z-score method
if event_count < thresh['zscore_lower'] or event_count > thresh['zscore_upper']:
outlier_reasons.append('Z-score')
# Check if extremely high (>5x median)
if event_count > 5 * thresh['median']:
outlier_reasons.append('Extreme high')
# Check user-level anomaly (>3x their average)
if row['event_count'] > 3 * row['avg_events_per_user']:
outlier_reasons.append('User anomaly')
is_outlier = len(outlier_reasons) > 0
reason = ', '.join(outlier_reasons) if is_outlier else 'Normal'
return is_outlier, reason
# Apply outlier detection
df['is_outlier'], df['outlier_reason'] = zip(*df.apply(
lambda row: identify_outliers(row, outlier_thresholds), axis=1
))
# Calculate outlier score (number of methods that flagged it)
df['outlier_score'] = df['outlier_reason'].apply(
lambda x: len(x.split(', ')) if x != 'Normal' else 0
)
Step 5: Create Summary Statistics
# Create outlier summary
outlier_summary = df.groupby(['event_name', 'is_outlier']).agg({
'event_count': ['count', 'mean', 'std', 'min', 'max'],
'user_pseudo_id': 'nunique'
}).round(2)
print("\nOutlier Summary by Event Type:")
print(outlier_summary)
# Calculate outlier percentage by event
outlier_percentage = df.groupby('event_name')['is_outlier'].agg([
'sum',
'count',
lambda x: (x.sum() / len(x) * 100).round(2)
]).rename(columns={'<lambda_0>': 'outlier_percentage'})
print("\nOutlier Percentage by Event:")
print(outlier_percentage)
Step 6: Create Outlier Detection Table
# Create the final outlier detection table
outlier_table_query = """
CREATE OR REPLACE TABLE `{dataset_id}.outlier_detection` AS
WITH event_stats AS (
SELECT
event_date,
event_name,
user_pseudo_id,
COUNT(*) as event_count,
AVG(CAST(event_value_in_usd AS FLOAT64)) as avg_event_value,
STRING_AGG(DISTINCT event_params.key, ', ' LIMIT 10) as event_params_keys
FROM
`{dataset_id}.events_*`
WHERE
_TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY))
AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
GROUP BY
event_date,
event_name,
user_pseudo_id
),
percentile_stats AS (
SELECT
event_name,
APPROX_QUANTILES(event_count, 100)[OFFSET(25)] as p25,
APPROX_QUANTILES(event_count, 100)[OFFSET(50)] as p50,
APPROX_QUANTILES(event_count, 100)[OFFSET(75)] as p75,
AVG(event_count) as mean_count,
STDDEV(event_count) as std_count
FROM
event_stats
GROUP BY
event_name
)
SELECT
es.*,
ps.p25,
ps.p50,
ps.p75,
ps.mean_count,
ps.std_count,
-- IQR outlier detection
CASE
WHEN es.event_count < (ps.p25 - 1.5 * (ps.p75 - ps.p25))
OR es.event_count > (ps.p75 + 1.5 * (ps.p75 - ps.p25))
THEN TRUE
ELSE FALSE
END as is_iqr_outlier,
-- Z-score outlier detection
CASE
WHEN ABS((es.event_count - ps.mean_count) / NULLIF(ps.std_count, 0)) > 3
THEN TRUE
ELSE FALSE
END as is_zscore_outlier,
-- Extreme value detection
CASE
WHEN es.event_count > ps.p50 * 5
THEN TRUE
ELSE FALSE
END as is_extreme_outlier,
-- Combined outlier flag
CASE
WHEN es.event_count < (ps.p25 - 1.5 * (ps.p75 - ps.p25))
OR es.event_count > (ps.p75 + 1.5 * (ps.p75 - ps.p25))
OR ABS((es.event_count - ps.mean_count) / NULLIF(ps.std_count, 0)) > 3
OR es.event_count > ps.p50 * 5
THEN TRUE
ELSE FALSE
END as is_outlier,
CURRENT_TIMESTAMP() as detection_timestamp
FROM
event_stats es
JOIN
percentile_stats ps
ON
es.event_name = ps.event_name
""".format(dataset_id=dataset_id)
# Execute table creation
client.query(outlier_table_query)
print("Outlier detection table created successfully")
Step 7: Visualize Outliers
# Visualization function
def visualize_outliers(df, event_name):
"""
Create visualizations for outlier analysis
"""
event_df = df[df['event_name'] == event_name].copy()
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
fig.suptitle(f'Outlier Analysis for {event_name}', fontsize=16)
# 1. Distribution with outliers highlighted
ax1 = axes[0, 0]
normal_data = event_df[~event_df['is_outlier']]['event_count']
outlier_data = event_df[event_df['is_outlier']]['event_count']
ax1.hist(normal_data, bins=30, alpha=0.7, label='Normal', color='blue')
ax1.hist(outlier_data, bins=30, alpha=0.7, label='Outliers', color='red')
ax1.set_xlabel('Event Count')
ax1.set_ylabel('Frequency')
ax1.set_title('Event Count Distribution')
ax1.legend()
# 2. Box plot
ax2 = axes[0, 1]
event_df.boxplot(column='event_count', ax=ax2)
ax2.set_title('Box Plot of Event Counts')
ax2.set_ylabel('Event Count')
# 3. Time series with outliers
ax3 = axes[1, 0]
event_df['event_date'] = pd.to_datetime(event_df['event_date'])
daily_stats = event_df.groupby(['event_date', 'is_outlier'])['event_count'].sum().unstack(fill_value=0)
if True in daily_stats.columns:
daily_stats[True].plot(ax=ax3, color='red', marker='o', label='Outlier Events')
if False in daily_stats.columns:
daily_stats[False].plot(ax=ax3, color='blue', alpha=0.5, label='Normal Events')
ax3.set_xlabel('Date')
ax3.set_ylabel('Total Event Count')
ax3.set_title('Daily Event Counts')
ax3.legend()
ax3.tick_params(axis='x', rotation=45)
# 4. Outlier score distribution
ax4 = axes[1, 1]
outlier_scores = event_df[event_df['is_outlier']]['outlier_score'].value_counts().sort_index()
outlier_scores.plot(kind='bar', ax=ax4, color='orange')
ax4.set_xlabel('Outlier Score')
ax4.set_ylabel('Count')
ax4.set_title('Distribution of Outlier Scores')
plt.tight_layout()
plt.show()
# Visualize top events
top_events = df['event_name'].value_counts().head(5).index
for event in top_events:
visualize_outliers(df, event)
Step 8: Export Results and Create Alerts
# Export outliers to CSV
outliers_df = df[df['is_outlier']].sort_values('outlier_score', ascending=False)
outliers_df.to_csv('ga4_outliers.csv', index=False)
print(f"Exported {len(outliers_df)} outliers to ga4_outliers.csv")
# Create alert summary
alert_summary = outliers_df.groupby(['event_date', 'event_name']).agg({
'user_pseudo_id': 'count',
'event_count': ['sum', 'max'],
'outlier_score': 'max'
}).round(2)
print("\nDaily Alert Summary:")
print(alert_summary.head(10))
# Function to check for critical outliers
def check_critical_outliers(df, threshold_multiplier=10):
"""
Identify critical outliers that need immediate attention
"""
critical_outliers = []
for event_name in df['event_name'].unique():
event_df = df[df['event_name'] == event_name]
median_count = event_df['event_count'].median()
critical = event_df[
(event_df['event_count'] > threshold_multiplier * median_count) |
(event_df['outlier_score'] >= 3)
]
if len(critical) > 0:
critical_outliers.append({
'event_name': event_name,
'critical_count': len(critical),
'max_event_count': critical