Claims¶
The claims module provides lower-level access to claims data for custom analysis beyond what the cohort module offers.
When to Use¶
Use the claims module when you need to:
- Fetch raw claims data with custom filters
- Build custom SQL queries with configuration-driven column names
- Get index dates from diagnosis claims
- Add demographics to an existing patient list
- Work with claims data outside the cohort workflow
Use Cohort Module First
For most use cases, start with get_cohort() which handles claims, demographics, and enrollment in one call. Use this module for custom analysis pipelines.
Quick Example¶
from alx_heor.database import RedshiftConnection
from alx_heor.claims import get_claims, get_index_dates, add_demographics
conn = RedshiftConnection().connect()
# Get all gMG diagnosis claims
df_claims = get_claims(
conn,
source="iqvia",
schema="iqvia_pharmetrics_2024q3",
diagnosis_codes=["G700", "G7000", "G7001"],
start_year=2015,
end_year=2024,
)
# Get first diagnosis date per patient
df_index = get_index_dates(
df_claims,
source="iqvia",
min_count=2,
days_apart=30,
)
# Add demographics
df_with_demo = add_demographics(
conn,
df_index,
source="iqvia",
schema="iqvia_pharmetrics_2024q3",
)
Common Patterns¶
Custom Column Selection¶
df = get_claims(
conn,
source="iqvia",
schema="iqvia_pharmetrics_2024q3",
diagnosis_codes=["G700"],
columns=["pat_id", "from_dt", "diag1", "pos", "prov_spec"],
start_year=2020,
end_year=2024,
)
Building SQL Manually¶
from alx_heor.claims import build_claims_sql
sql = build_claims_sql(
source="iqvia",
schema="iqvia_pharmetrics_2024q3",
diagnosis_codes=["G700", "G7000"],
columns=["pat_id", "from_dt"],
start_year=2020,
end_year=2024,
)
# Modify SQL as needed
sql += " AND pos IN ('21', '22')"
df = conn.query(sql)
Related Modules¶
cohort- High-level cohort building (uses claims internally)config- Column name mappingsdatabase- Database connection
claims ¶
Claims data processing utilities for Real-World Evidence (RWE) studies.
This module provides the foundation for cohort identification in retrospective healthcare database studies. Claims data represents healthcare encounters (diagnoses, procedures, prescriptions) captured during routine clinical care, making it essential for identifying patients with specific conditions.
Core Functions:
- get_claims: Retrieve claims filtered by diagnosis codes (ICD-9/ICD-10)
- build_claims_sql: Preview the SQL query before execution
- get_index_dates: Identify index dates (study entry) for a patient cohort
- add_demographics: Add patient age and sex from claims or enrollment data
- filter_demographics: Apply age/sex inclusion criteria
Typical Workflow:
- get_claims() - Query claims matching your target diagnosis codes
- get_index_dates() - Determine each patient's index date (first/second Dx)
- add_demographics() - Add age at index and sex
- filter_demographics() - Apply age/sex inclusion criteria
- Continue to enrollment module for continuous enrollment requirements
For a fully automated workflow, use cohort.get_cohort() which combines
all these steps with comprehensive attrition tracking.
Example
Basic workflow for identifying gMG (generalized Myasthenia Gravis) patients:
from alx_heor import RedshiftConnection from alx_heor.claims import get_claims, get_index_dates, add_demographics
conn = RedshiftConnection().connect() df_claims = get_claims( ... conn, ... source='iqvia', ... schema='iqvia_pharmetrics_2024q3', ... diagnosis_codes=['G700', 'G7000', 'G7001'], # gMG ICD-10 codes ... start_year=2015, ... end_year=2024, ... ) print(f"Total claims: {len(df_claims):,}") Total claims: 1,234,567 df_index = get_index_dates( ... df_claims, ... source='iqvia', ... min_diagnosis_count=2, ... days_apart=30, ... ) print(f"Patients with 2+ Dx: {len(df_index):,}") Patients with 2+ Dx: 45,678 df_cohort = add_demographics(df_index, df_claims=df_claims, source='iqvia') df_adults = df_cohort[df_cohort['age_at_index'] >= 18] print(f"Adult patients: {len(df_adults):,}") Adult patients: 42,103
See Also
cohort.get_cohort : High-level function that automates this entire workflow enrollment.get_enrollment : Next step after claims-based identification config.get_source_config : View column mappings for each data source
Notes
- ICD-9 codes (e.g., '3410') were used before Oct 2015; ICD-10 (e.g., 'G700') after
- Always include BOTH ICD-9 and ICD-10 codes for studies spanning the transition
- The 2+ diagnoses 30 days apart criterion reduces false positives from rule-out testing
- IQVIA uses
pat_id, Optum usespatid- thesourceparameter handles this
get_claims ¶
get_claims(conn: RedshiftConnection, source: str, schema: str, diagnosis_codes: list[str], start_year: int, end_year: int, table_pattern: str | None = None, columns: list[str] | None = None, diagnosis_columns: list[str] | None = None, include_demographics: bool = False) -> pd.DataFrame
Retrieve claims data filtered by diagnosis codes from yearly claims tables.
This is typically the first step in cohort identification. Claims are stored in yearly tables (e.g., claims_2020, claims_2021) and this function builds a UNION ALL query across all specified years, filtering to records where any diagnosis column contains one of the target ICD codes.
Workflow:
- get_claims() <-- you are here
- get_index_dates() - Identify index dates from the claims
- add_demographics() - Add age/sex to the cohort
- filter_demographics() - Apply inclusion criteria
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
RedshiftConnection
|
Active database connection. Must be connected before calling. |
required |
source
|
str
|
Data source name: 'iqvia', 'optum', 'komodo'. Determines default column names and table patterns via config. |
required |
schema
|
str
|
Database schema name (e.g., 'iqvia_pharmetrics_2024q3').
Use |
required |
diagnosis_codes
|
list[str]
|
ICD-9 or ICD-10 codes to filter claims. Include both versions for studies spanning Oct 2015 (ICD-10 transition date in US). Examples: ['G700', 'G7000', 'G7001'] for gMG, ['G35'] for MS. |
required |
start_year
|
int
|
First year of claims data to include (e.g., 2015). |
required |
end_year
|
int
|
Last year of claims data to include (e.g., 2024). |
required |
table_pattern
|
str
|
Override table name pattern (e.g., 'claims_{year}'). Uses source
default if not specified. The |
None
|
columns
|
list[str]
|
Override columns to select. Uses source default if not specified. Diagnosis columns are automatically added if not included. |
None
|
diagnosis_columns
|
list[str]
|
Override which diagnosis columns to check (e.g., ['diag1', 'diag2']). Uses source default if not specified. IQVIA has 12 diagnosis columns plus diag_admit; Optum has 5. |
None
|
include_demographics
|
bool
|
If True, include demographics (year_of_birth, sex) by querying
the enrollment table. For IQVIA, demographics are in |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Claims data filtered by diagnosis codes. One row per claim, not per patient. Contains all columns from the SELECT clause. |
See Also
build_claims_sql : Preview the generated SQL without executing it get_index_dates : Next step - identify index dates from claims cohort.get_cohort : High-level function that automates the full workflow config.get_source_config : View column mappings for each data source
Notes
- An empty
diagnosis_codeslist will return ALL claims (expensive!) - Claims can be very large (millions of rows). Consider memory limits.
- IQVIA claims tables: claims_2006 through claims_2025
- The function checks ALL diagnosis columns (diag1-diag12, diag_admit for IQVIA)
- Codes are matched exactly - 'G70' will NOT match 'G700'
Examples:
Identify patients with gMG (both ICD-9 and ICD-10):
>>> conn = RedshiftConnection().connect()
>>> df_claims = get_claims(
... conn,
... source='iqvia',
... schema='iqvia_pharmetrics_2024q3',
... diagnosis_codes=['3589', 'G700', 'G7000', 'G7001'], # MG codes
... start_year=2015,
... end_year=2024,
... )
>>> print(f"Claims: {len(df_claims):,}, Patients: {df_claims['pat_id'].nunique():,}")
Claims: 2,456,789, Patients: 89,123
Preview the SQL before running (useful for debugging):
>>> sql = build_claims_sql(
... source='iqvia',
... schema='iqvia_pharmetrics_2024q3',
... diagnosis_codes=['G700'],
... start_year=2023, end_year=2024,
... )
>>> print(sql[:200]) # Preview first 200 chars
Source code in alx_heor\claims\__init__.py
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 | |
build_claims_sql ¶
build_claims_sql(source: str, schema: str, diagnosis_codes: list[str], start_year: int, end_year: int, table_pattern: str | None = None, columns: list[str] | None = None, diagnosis_columns: list[str] | None = None) -> str
Build SQL query for claims data without executing it.
This function generates the UNION ALL SQL query that get_claims() would
execute. Use this to inspect, debug, or modify the query before running it.
Particularly useful for understanding the query structure or for running
modified versions directly via conn.query().
Workflow:
- build_claims_sql() - Preview SQL (optional, for debugging)
- get_claims() - Execute the query
- get_index_dates() - Identify index dates from claims
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Data source name: 'iqvia', 'optum', 'komodo'. |
required |
schema
|
str
|
Database schema name. |
required |
diagnosis_codes
|
list[str]
|
ICD codes to filter claims. |
required |
start_year
|
int
|
Start year for claims data. |
required |
end_year
|
int
|
End year for claims data. |
required |
table_pattern
|
str
|
Override table name pattern. |
None
|
columns
|
list[str]
|
Override columns to select. |
None
|
diagnosis_columns
|
list[str]
|
Override diagnosis columns to check. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
SQL query string ready for execution. |
See Also
get_claims : Execute the query and return results config.get_source_config : View column mappings and table patterns
Notes
- The generated SQL uses UNION ALL across yearly tables (claims_2020, etc.)
- Diagnosis filtering uses OR across all diagnosis columns
- SELECT clause excludes SELECT * to avoid pulling unnecessary data
Examples:
Preview SQL for debugging:
>>> sql = build_claims_sql(
... source='iqvia',
... schema='iqvia_pharmetrics_2024q3',
... diagnosis_codes=['G700', 'G7000'],
... start_year=2023,
... end_year=2024,
... )
>>> print(sql)
SELECT pat_id, from_dt, to_dt, ...
FROM (
SELECT ... FROM iqvia_pharmetrics_2024q3.claims_2024
UNION ALL
SELECT ... FROM iqvia_pharmetrics_2024q3.claims_2023
) claims
WHERE diag1 IN ('G700', 'G7000') OR diag2 IN ('G700', 'G7000') ...
Modify and execute directly:
>>> sql = build_claims_sql(source='iqvia', ...)
>>> sql_with_limit = sql + " LIMIT 1000" # Add limit for testing
>>> df_sample = conn.query(sql_with_limit)
Source code in alx_heor\claims\__init__.py
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 | |
get_index_dates ¶
get_index_dates(df_claims: DataFrame, source: str | None = None, patient_id_col: str | None = None, date_col: str | None = None, min_diagnosis_count: int = 1, days_apart: int = 30) -> pd.DataFrame
Identify index dates for patients based on diagnosis claims.
The index date is the anchor point for a retrospective cohort study. It defines when each patient "enters" the study, and all baseline/follow-up periods are calculated relative to this date. In RWE studies, the index date is typically the first (or second) qualifying diagnosis date.
The "2+ diagnoses 30 days apart" criterion is a standard RWE approach to reduce false positives. A single diagnosis may represent rule-out testing (e.g., patient presents with symptoms, gets tested, but doesn't have the condition). Requiring two diagnoses separated by time increases confidence that the patient truly has the condition.
Workflow:
- get_claims() - Query raw claims data
- get_index_dates() <-- you are here
- add_demographics() - Add age/sex to cohort
- filter_demographics() - Apply inclusion criteria
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_claims
|
DataFrame
|
Claims data from get_claims(). Must contain patient ID and date columns. |
required |
source
|
str
|
Data source name: 'iqvia', 'optum', 'komodo'. If provided, uses source-specific column defaults. |
None
|
patient_id_col
|
str
|
Name of the patient ID column. If not provided, uses source default or falls back to 'pat_id'. |
None
|
date_col
|
str
|
Name of the service date column. If not provided, uses source default or falls back to 'from_dt'. |
None
|
min_diagnosis_count
|
int
|
Minimum number of diagnoses required: - 1: Any single diagnosis qualifies (more inclusive, more false positives) - 2: Requires 2 diagnoses (standard RWE criterion, fewer false positives) - 3+: Very restrictive (use for conditions with high testing frequency) |
1
|
days_apart
|
int
|
Minimum days between first and last diagnosis when min_diagnosis_count >= 2. Common values: 30 (standard), 60 (more restrictive), 7 (less restrictive). |
30
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: - patient_id: Patient identifier (renamed from source-specific column) - index_date: First qualifying diagnosis date (datetime64) |
See Also
get_claims : Previous step - retrieve raw claims add_demographics : Next step - add age/sex cohort.get_cohort : High-level function that handles all steps cohort.DiagnosisCriteria : More advanced diagnosis criteria options
Notes
- The index date is always the FIRST diagnosis date, even with min_count=2
- Dates are converted to datetime64 format automatically
- Patients not meeting criteria are excluded from output
- For second diagnosis as index date, use
cohort.CohortCriteria(index_date_method="second_dx") - Consider your study's sensitivity/specificity tradeoff when choosing min_count
Examples:
Standard RWE approach: 2+ diagnoses 30 days apart for gMG:
>>> df_index = get_index_dates(
... df_claims,
... source='iqvia',
... min_diagnosis_count=2,
... days_apart=30,
... )
>>> print(f"Patients meeting 2+ Dx criterion: {len(df_index):,}")
Patients meeting 2+ Dx criterion: 12,847
Any single diagnosis (more inclusive, use for rare conditions):
>>> df_index_any = get_index_dates(
... df_claims,
... source='iqvia',
... min_diagnosis_count=1,
... )
>>> print(f"Patients with any Dx: {len(df_index_any):,}")
Patients with any Dx: 25,123
Compare sensitivity vs specificity:
>>> # More specific (fewer false positives)
>>> df_strict = get_index_dates(df_claims, source='iqvia', min_diagnosis_count=2, days_apart=60)
>>> # More sensitive (fewer false negatives)
>>> df_lenient = get_index_dates(df_claims, source='iqvia', min_diagnosis_count=1)
>>> print(f"Strict: {len(df_strict):,}, Lenient: {len(df_lenient):,}")
Source code in alx_heor\claims\__init__.py
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 | |
add_demographics ¶
add_demographics(df_index: DataFrame, df_claims: DataFrame | None = None, df_demographics: DataFrame | None = None, source: str | None = None, patient_id_col: str | None = None, yob_col: str | None = None, sex_col: str | None = None) -> pd.DataFrame
Add demographics (age, sex) to an index dates DataFrame.
In RWE studies, age and sex are essential demographic variables. Age is calculated at the index date (age_at_index), which accounts for patients aging over the study period. Sex is typically coded as 'M'/'F' in claims databases, with 'U' (unknown) indicating missing or ambiguous data.
For IQVIA, demographics (der_yob, der_sex) are in the enroll table,
not in claims. Use get_claims(..., include_demographics=True) to
include them automatically.
Workflow:
- get_claims(include_demographics=True) - Query claims with demographics
- get_index_dates() - Identify index dates
- add_demographics() <-- you are here
- filter_demographics() - Apply age/sex criteria
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_index
|
DataFrame
|
Index dates DataFrame with patient_id and index_date columns. Output from get_index_dates(). |
required |
df_claims
|
DataFrame
|
Claims data containing demographic columns. For IQVIA, use
|
None
|
df_demographics
|
DataFrame
|
Separate demographics table. Takes precedence over df_claims. |
None
|
source
|
str
|
Data source name for column defaults: 'iqvia', 'optum', 'komodo'. |
None
|
patient_id_col
|
str
|
Patient ID column name. Defaults to source-specific column. |
None
|
yob_col
|
str
|
Year of birth column name. Defaults to source-specific column. |
None
|
sex_col
|
str
|
Sex column name. Defaults to source-specific column. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Index DataFrame with added columns: - year_of_birth: Patient's year of birth - sex: Patient's sex ('M', 'F', or 'U') - age_at_index: Age at index date (index_year - year_of_birth) |
See Also
get_claims : Use include_demographics=True for IQVIA filter_demographics : Next step - apply age/sex criteria get_index_dates : Previous step - identify index dates cohort.get_cohort : High-level function that handles all steps
Notes
- IQVIA: Use
get_claims(..., include_demographics=True)to include der_yob and der_sex from the enrollment table - Optum: Demographics (yrdob, gdr_cd) are in claims, no special handling needed
- Age is calculated as index_year - year_of_birth (approximate, not exact)
Examples:
Recommended approach (IQVIA):
>>> df_claims = get_claims(conn, source='iqvia', ..., include_demographics=True)
>>> df_index = get_index_dates(df_claims, source='iqvia', min_diagnosis_count=2)
>>> df_cohort = add_demographics(df_index, df_claims=df_claims, source='iqvia')
Alternative - provide demographics separately:
>>> df_enroll = conn.query('SELECT pat_id, der_yob, der_sex FROM schema.enroll')
>>> df_cohort = add_demographics(df_index, df_demographics=df_enroll, source='iqvia')
Source code in alx_heor\claims\__init__.py
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 | |
filter_demographics ¶
filter_demographics(df: DataFrame, min_age: int | None = None, max_age: int | None = None, valid_sex_only: bool = True, age_col: str = 'age_at_index', sex_col: str = 'sex') -> pd.DataFrame
Filter DataFrame by age and sex inclusion/exclusion criteria.
Demographic filtering is a standard step in RWE cohort identification. Most studies restrict to adults (≥18), and many require known sex for subgroup analyses. This function applies these filters while preserving a copy of the original data (non-destructive).
Common age restrictions: - Adults only: min_age=18 - Working age: min_age=18, max_age=65 - Elderly: min_age=65 - Pediatric: max_age=17
Workflow:
- get_claims() - Query raw claims data
- get_index_dates() - Identify index dates
- add_demographics() - Add age/sex to cohort
- filter_demographics() <-- you are here
- Continue to enrollment module or use cohort.get_cohort()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with age and sex columns (from add_demographics). |
required |
min_age
|
int
|
Minimum age (inclusive). None means no lower bound. |
None
|
max_age
|
int
|
Maximum age (inclusive). None means no upper bound. |
None
|
valid_sex_only
|
bool
|
If True, keep only rows where sex is 'M' or 'F'. Removes 'U' (unknown) and any other values. |
True
|
age_col
|
str
|
Name of age column to filter on. |
'age_at_index'
|
sex_col
|
str
|
Name of sex column to filter on. |
'sex'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Copy of input DataFrame with rows filtered by criteria. |
See Also
add_demographics : Previous step - add age/sex columns enrollment.analyze_enrollment : Next step - enrollment requirements cohort.get_cohort : High-level function that handles all steps
Notes
- Returns a COPY, does not modify the input DataFrame
- If age_col doesn't exist, age filters are skipped (no error)
- If sex_col doesn't exist, sex filter is skipped (no error)
- Sex values 'U', '', NaN are removed when valid_sex_only=True
Examples:
Filter to adults only (most common for non-pediatric studies):
>>> df_adults = filter_demographics(df_cohort, min_age=18)
>>> print(f"Adults: {len(df_adults):,} of {len(df_cohort):,}")
Adults: 42,103 of 45,678
Filter to working-age adults:
>>> df_working = filter_demographics(df_cohort, min_age=18, max_age=64)
>>> print(f"Working age: {len(df_working):,}")
Working age: 28,456
Filter to elderly patients:
>>> df_elderly = filter_demographics(df_cohort, min_age=65)
>>> print(f"Elderly (65+): {len(df_elderly):,}")
Elderly (65+): 13,647
Keep patients with unknown sex (useful for sensitivity analysis):
>>> df_all_sex = filter_demographics(df_cohort, min_age=18, valid_sex_only=False)
>>> print(f"Including unknown sex: {len(df_all_sex):,}")
Check attrition from demographic filters:
>>> n_before = len(df_cohort)
>>> df_filtered = filter_demographics(df_cohort, min_age=18)
>>> n_after = len(df_filtered)
>>> print(f"Excluded by age filter: {n_before - n_after:,} ({(n_before-n_after)/n_before*100:.1f}%)")
Source code in alx_heor\claims\__init__.py
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 | |