Statistics API¶
Outlier Detection¶
fraud_detection.statistics.outliers
¶
Statistical outlier detection for insurance fraud analysis.
This module provides multiple statistical methods to identify anomalous claim amounts that deviate significantly from expected patterns. Outlier detection is fundamental to fraud detection because fraudulent claims often involve:
- Inflated charges: Billing significantly more than the typical rate for a procedure.
- Unusual patterns: Providers consistently charging above or below market rates.
- Temporal anomalies: Sudden unexplained spikes in billing amounts.
Two primary statistical methods are implemented:
-
Z-score method: Measures how many standard deviations a value is from the mean. Best for normally distributed data.
-
IQR method: Uses quartiles to define outlier boundaries. More robust to extreme values and non-normal distributions.
Classes¶
OutlierDetector
¶
Detect statistical outliers in insurance claims data.
Provides multiple outlier detection methods optimized for fraud analysis, supporting both global analysis and group-based detection (e.g., by procedure code). All methods add boolean flag columns indicating outlier status.
Parameters¶
spark : SparkSession Active Spark session for distributed processing. config : DetectionConfig Configuration object containing detection thresholds:
- ``outlier_zscore_threshold``: Number of standard deviations for Z-score method.
- ``outlier_iqr_multiplier``: IQR multiplier (typically 1.5 for outliers, 3.0 for extreme).
Examples¶
detector = OutlierDetector(spark, config) claims = detector.detect_zscore_outliers(claims, "charge_amount", "is_outlier") claims = detector.detect_procedure_outliers(claims) outliers = claims.filter(claims.is_outlier)
Source code in packages/fraud_detection/src/fraud_detection/statistics/outliers.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
Functions¶
detect_iqr_outliers(df, column, output_column, group_by=None)
¶
Identify outliers using the Interquartile Range (IQR) method.
IQR-based detection is more robust than Z-score for skewed distributions
and is less sensitive to extreme outliers when calculating bounds. Values
below Q1 - k*IQR or above Q3 + k*IQR are flagged as outliers.
Parameters¶
df : DataFrame Input DataFrame containing the column to analyze. column : str Name of the numeric column to check for outliers. output_column : str Name for the boolean flag column to be added. group_by : list[str], optional Columns to partition by for group-wise quartile calculation.
Returns¶
DataFrame
Input DataFrame with added boolean column output_column where
True indicates the value is an outlier.
Notes¶
IQR = Q3 - Q1 (interquartile range)
- Lower bound: Q1 - (multiplier * IQR)
- Upper bound: Q3 + (multiplier * IQR)
Common multiplier values:
- 1.5: Standard outliers (Tukey's method)
- 3.0: Extreme outliers only
Source code in packages/fraud_detection/src/fraud_detection/statistics/outliers.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | |
detect_procedure_outliers(df, charge_column='charge_amount', procedure_column='procedure_code')
¶
Detect charge outliers within each procedure code.
Charges for the same procedure should fall within a predictable range. A charge that is an outlier globally might be normal for a complex procedure, while a seemingly normal charge might be fraudulent for a simple procedure. This method contextualizes outlier detection by procedure type.
Parameters¶
df : DataFrame Input claims DataFrame. charge_column : str, default "charge_amount" Column containing charge amounts. procedure_column : str, default "procedure_code" Column containing procedure codes for grouping.
Returns¶
DataFrame Claims with added column:
- ``procedure_charge_outlier`` : bool - True if charge is an outlier for this procedure.
Source code in packages/fraud_detection/src/fraud_detection/statistics/outliers.py
detect_provider_outliers(df, charge_column='charge_amount', provider_column='provider_id', procedure_column='procedure_code')
¶
Identify providers with systematically unusual billing patterns.
Compares each provider's average charges per procedure against market averages. Providers consistently billing significantly above or below market rates may be engaged in upcoding, unbundling, or other schemes.
Parameters¶
df : DataFrame Input claims DataFrame. charge_column : str, default "charge_amount" Column containing charge amounts. provider_column : str, default "provider_id" Column containing provider identifiers. procedure_column : str, default "procedure_code" Column containing procedure codes.
Returns¶
DataFrame Claims with added columns:
- ``provider_avg_charge`` : float - Provider's average charge for this procedure.
- ``charge_deviation_ratio`` : float - Ratio of provider avg to market avg.
- ``provider_billing_outlier`` : bool - True if ratio >2.0 or <0.5.
Source code in packages/fraud_detection/src/fraud_detection/statistics/outliers.py
detect_temporal_outliers(df, charge_column='charge_amount', date_column='service_date')
¶
Detect sudden spikes in provider billing patterns over time.
Identifies claims where the charge amount significantly exceeds the provider's recent historical average. Sudden unexplained billing increases may indicate the start of a fraud scheme.
Uses a 4-week rolling average as the baseline and flags charges exceeding 3x this average.
Parameters¶
df : DataFrame Input claims DataFrame. charge_column : str, default "charge_amount" Column containing charge amounts. date_column : str, default "service_date" Column containing service dates.
Returns¶
DataFrame Claims with added column:
- ``temporal_spike_flag`` : bool - True if charge >3x rolling average.
Notes¶
The rolling window looks at the previous 4 weeks of data for each provider. Claims in the first 4 weeks of a provider's history will not have a baseline for comparison and will not be flagged.
Source code in packages/fraud_detection/src/fraud_detection/statistics/outliers.py
detect_zscore_outliers(df, column, output_column, group_by=None)
¶
Identify outliers using the Z-score (standard score) method.
The Z-score measures how many standard deviations a value is from the mean. Values with absolute Z-scores exceeding the configured threshold are flagged as outliers.
Z-score is most effective when data is approximately normally distributed. For skewed distributions (common with financial data), consider using the IQR method instead.
Parameters¶
df : DataFrame
Input DataFrame containing the column to analyze.
column : str
Name of the numeric column to check for outliers.
output_column : str
Name for the boolean flag column to be added.
group_by : list[str], optional
Columns to partition by for group-wise statistics. For example,
passing ["procedure_code"] calculates separate means and
standard deviations for each procedure, making the detection
context-aware.
Returns¶
DataFrame
Input DataFrame with added boolean column output_column where
True indicates the value is an outlier.
Notes¶
The formula used is: z = (x - μ) / σ
A claim is flagged if |z| > threshold. When standard deviation is
zero (all values identical), Z-score is set to 0 to avoid division errors.
Source code in packages/fraud_detection/src/fraud_detection/statistics/outliers.py
Benford's Law Analysis¶
fraud_detection.statistics.benfords
¶
Benford's Law analysis for insurance fraud detection.
Benford's Law (also known as the First-Digit Law) is a mathematical observation that in many naturally occurring datasets, the leading digit is more likely to be small. Specifically:
- Digit 1 appears as the leading digit ~30.1% of the time
- Digit 9 appears as the leading digit ~4.6% of the time
This counterintuitive distribution applies to data spanning multiple orders of magnitude, such as financial transactions, population figures, and physical constants.
Fraud Detection Application
Financial fraud often violates Benford's Law because:
-
Fabricated numbers: Fraudsters tend to create numbers with more uniform digit distributions, or subconsciously favor certain digits.
-
Round number bias: Fraudulent amounts often cluster around round numbers (e.g., $100, $500, $1000), distorting the natural distribution.
-
Threshold avoidance: Fraudsters may manipulate amounts to stay below review thresholds, creating artificial spikes at certain values.
A significant deviation from Benford's expected distribution in claim amounts is a strong indicator that warrants further investigation.
Classes¶
BenfordsLawAnalyzer
¶
Analyze claim data for conformity to Benford's Law.
Compares the observed first-digit distribution of numeric data against the expected Benford's distribution. Significant deviations may indicate fabricated or manipulated data.
Parameters¶
spark : SparkSession Active Spark session for distributed processing.
Examples¶
analyzer = BenfordsLawAnalyzer(spark) claims = analyzer.analyze(claims, "charge_amount", group_by="provider_id") anomalies = claims.filter(claims.benfords_anomaly)
Generate detailed report for visualization¶
report = analyzer.get_distribution_report(claims, "charge_amount") report.show()
Notes¶
Benford's Law works best with data that:
- Spans multiple orders of magnitude
- Is not artificially constrained (e.g., not limited to a narrow range)
- Has a sufficient sample size (typically 100+ values)
For small datasets or data with limited range, results may be unreliable.
Source code in packages/fraud_detection/src/fraud_detection/statistics/benfords.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
Attributes¶
BENFORDS_EXPECTED = {1: 0.301, 2: 0.176, 3: 0.125, 4: 0.097, 5: 0.079, 6: 0.067, 7: 0.058, 8: 0.051, 9: 0.046}
class-attribute
instance-attribute
¶
Expected first-digit frequencies according to Benford's Law.
Derived from the formula: P(d) = log10(1 + 1/d) for d = 1, 2, ..., 9
Functions¶
analyze(df, column, group_by=None, threshold=0.15)
¶
Analyze a numeric column for Benford's Law conformity.
Extracts the first digit from each value, calculates the observed distribution, and compares it to the expected Benford's distribution. Values whose first digit appears more frequently than expected (by more than the threshold) are flagged.
Parameters¶
df : DataFrame Input DataFrame containing the column to analyze. column : str Name of the numeric column to analyze (e.g., "charge_amount"). group_by : str, optional Column to group by for per-group analysis (e.g., "provider_id"). When provided, calculates separate distributions for each group, allowing detection of providers with anomalous digit patterns. threshold : float, default 0.15 Maximum allowed deviation from expected frequency before flagging. A value of 0.15 means a digit appearing 45% of the time when expected to appear 30% would be flagged (0.45 - 0.30 = 0.15).
Returns¶
DataFrame Input DataFrame with added column:
- ``benfords_anomaly`` : bool - True if the value's first digit
is over-represented in the dataset, suggesting possible fabrication.
Source code in packages/fraud_detection/src/fraud_detection/statistics/benfords.py
get_distribution_report(df, column, group_by=None)
¶
Generate a detailed Benford's Law distribution report.
Creates a summary table comparing observed vs. expected digit frequencies, useful for visualization, auditing, and deeper analysis of potential anomalies.
Parameters¶
df : DataFrame Input DataFrame containing the column to analyze. column : str Name of the numeric column to analyze. group_by : str, optional Column to group by for per-group reports.
Returns¶
DataFrame Report with columns:
- ``first_digit`` : int - The leading digit (1-9).
- ``count`` : int - Number of occurrences.
- ``total`` : int - Total values in group/dataset.
- ``observed_frequency`` : float - Actual proportion.
- ``expected_frequency`` : float - Benford's expected proportion.
- ``deviation`` : float - Difference (observed - expected).
- ``deviation_percentage`` : float - Deviation as % of expected.
If ``group_by`` is provided, includes that column as well.
Examples¶
report = analyzer.get_distribution_report(claims, "charge_amount") report.show() +-----------+-----+-----+------------------+------------------+---------+--------------------+ |first_digit|count|total|observed_frequency|expected_frequency|deviation|deviation_percentage| +-----------+-----+-----+------------------+------------------+---------+--------------------+ | 1| 3021|10000| 0.3021| 0.301| 0.0011| 0.37| | 2| 1755|10000| 0.1755| 0.176| -0.0005| -0.28| ...
Source code in packages/fraud_detection/src/fraud_detection/statistics/benfords.py
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |