API reference¶
The public modules, from their docstrings. The transaction models themselves
(x12sdk.v5010.*) mirror the implementation guides loop by loop and are
best explored from a parsed file, or with x12sdk -m -p file.
Tables¶
- x12sdk.tables.spreadsheet_safe(value)[source]¶
value, made safe to open in a spreadsheet.A text value starting with
=,+,-,@, a tab or a carriage return is prefixed with an apostrophe, so Excel, LibreOffice and Google Sheets show it as text instead of running it as a formula. Numbers, and text that is a plain number such as-12.50, are returned unchanged.
- x12sdk.tables.REMITTANCE_COLUMNS: Sequence[str] = ('transaction_set', 'transaction_control_number', 'payer_name', 'payer_id', 'payee_name', 'payee_npi', 'payment_trace_number', 'payment_method', 'payment_amount', 'payment_date', 'patient_control_number', 'payer_claim_control_number', 'claim_status_code', 'claim_filing_indicator', 'claim_charge', 'claim_paid', 'claim_patient_responsibility', 'claim_adjustment_codes', 'patient_last_name', 'patient_first_name', 'member_id', 'line_number', 'procedure_qualifier', 'procedure_code', 'modifiers', 'revenue_code', 'units_paid', 'line_charge', 'line_paid', 'service_date', 'co_amount', 'pr_amount', 'oa_amount', 'pi_amount', 'cr_amount', 'adjustment_codes', 'remark_codes')¶
The columns of an 835 row, one row per paid service line, in order.
- x12sdk.tables.CLAIM_COLUMNS: Sequence[str] = ('transaction_set', 'transaction_control_number', 'implementation', 'billing_provider_name', 'billing_provider_npi', 'payer_name', 'subscriber_last_name', 'subscriber_first_name', 'member_id', 'patient_last_name', 'patient_first_name', 'is_dependent', 'relationship_code', 'patient_control_number', 'claim_charge', 'facility_code', 'claim_frequency_code', 'principal_diagnosis', 'diagnosis_codes', 'claim_service_date', 'line_number', 'procedure_qualifier', 'procedure_code', 'modifiers', 'revenue_code', 'units', 'line_charge', 'line_service_date', 'tooth_number', 'tooth_surfaces')¶
The columns of an 837 row, one row per billed service line, in order.
- x12sdk.tables.remittance_lines(transaction)[source]¶
One row per service line of an 835, in file order.
A claim paid without line detail (no 2110 loops) still gets one row, with the line columns empty, so no payment is lost from the table.
- x12sdk.tables.claim_lines(transaction)[source]¶
One row per service line of an 837 (P, I or D), in file order, from both the subscriber and the dependent branch of the hierarchy.
- x12sdk.tables.iter_lines(source, *, allow_paths=True)[source]¶
Rows for every 835 and 837 transaction in
source, one per service line.Other transaction sets in the same interchange are skipped. Rows from an 835 have
REMITTANCE_COLUMNS; rows from an 837 haveCLAIM_COLUMNS. A file normally holds one kind; to split a mixed one, filter ontransaction_set.
- x12sdk.tables.read_lines(source, *, allow_paths=True)[source]¶
iter_lines()as a list.
- x12sdk.tables.to_dataframe(source, *, allow_paths=True)[source]¶
The service-line rows of
sourceas a pandasDataFrame.Requires the optional pandas dependency:
pip install 'x12sdk[pandas]'.- Parameters:
allow_paths (bool)
- x12sdk.tables.write_csv(source, out, escape_formulas=True, *, allow_paths=True)[source]¶
Writes the service-line rows of
sourceas CSV toout.- Parameters:
escape_formulas (bool) – Prefix text that a spreadsheet would run as a formula with an apostrophe (see
spreadsheet_safe()). Leave it on for any file you did not create yourself; turn it off only when the CSV goes to a program, not a spreadsheet.allow_paths (bool) – Treat a string naming an X12 file as that file. Pass
Falsefor input from someone else, so it is only read as X12 text.out (TextIO)
- Returns:
The number of rows written, not counting the header.
- Return type:
Validation¶
- x12sdk.validation.READ_ERRORS = (<class 'pydantic_core._pydantic_core.ValidationError'>, <class 'ValueError'>, <class 'KeyError'>, <class 'IndexError'>)¶
The exceptions reading a file can raise for bad input, as opposed to bugs.
- class x12sdk.validation.Transaction(transaction_set: 'str', control_number: 'Optional[str]', implementation: 'Optional[str]', claims: 'Optional[int]')[source]¶
- Parameters:
- class x12sdk.validation.CheckResult(valid, transactions=<factory>, problems=<factory>)[source]¶
The outcome of checking one source.
- Parameters:
valid (bool)
transactions (List[Transaction])
- transactions: List[Transaction]¶
- x12sdk.validation.problems(error)[source]¶
The problems behind a failed read, in words, without the file content.
Matching¶
- x12sdk.matching.OUTCOMES = ('paid', 'denied', 'no remittance', 'no claim')¶
The outcomes
Match.outcomecan take.
- x12sdk.matching.MATCH_COLUMNS: Sequence[str] = ('patient_control_number', 'outcome', 'billed', 'paid', 'patient_responsibility', 'payment_count', 'claim_status_codes', 'payer_claim_control_numbers', 'claim_count')¶
The columns of a
match_rows()row, in order.
- class x12sdk.matching.Match(patient_control_number, claims, payments)[source]¶
One patient control number, with every claim and payment that carries it.
claimsis usually one claim; more than one means the same number was submitted again.paymentsholds every CLP for the number, in the order the remittances were given.- Parameters:
patient_control_number (str)
claims (Tuple[SubmittedClaim, ...])
- claims: Tuple[SubmittedClaim, ...]¶
- x12sdk.matching.match_claims(claims, remittances, *, allow_paths=True)[source]¶
Pairs every claim with every payment that answers it.
- Parameters:
claims – 837 files, text or models (one or an iterable).
remittances – 835 files, text or models (one or an iterable).
allow_paths (bool) – Treat a string naming an X12 file as that file. Pass
Falsefor input from someone else, so it is only read as X12 text.
- Returns:
One
Matchper patient control number: the claims’ numbers in file order, then numbers only the remittances carry.- Return type:
- x12sdk.matching.match_rows(claims, remittances, *, allow_paths=True)[source]¶
match_claims()as flat rows withMATCH_COLUMNS, ready for a CSV or a DataFrame.
Reading and writing¶
- x12sdk.io.FUNCTIONAL_IDENTIFIER_CODES: Dict[str, str] = {'270': 'HS', '271': 'HB', '276': 'HR', '277': 'HN', '834': 'BE', '835': 'HP', '837': 'HC'}¶
Transaction set code -> GS01 functional identifier code.
- class x12sdk.io.X12SegmentReader(x12_input, *, allow_paths=True)[source]¶
Streams segments from a X12 message or file.
- with X12Reader(x12_data) as r:
- for segment_name, segment_fields in r.segments():
# do something interesting
Segments are streamed in order received using a buffered generator function. Buffer size is configured using the config/env variable X12_READER_BUFFER_SIZE (default = 1MB).
- class x12sdk.io.X12ModelReader(x12_input, output_delimiters=False, *, allow_paths=True)[source]¶
The X12ModelReader parses X12 segments into transactional models. Data is buffered using a X12SegmentReader.
- with X12ModelReader(x12_data) as r:
- for model in r.model():
# do something interesting
- x12sdk.io.write_transactions(transactions, *, sender_id, receiver_id, sender_qualifier='30', receiver_qualifier='30', interchange_control_number='000000001', group_control_number='1', created=None, usage_indicator='T', path=None)[source]¶
Writes transaction models as a complete X12 interchange.
Transaction models cover ST through SE; this adds the ISA/IEA interchange and GS/GE functional group envelopes around them. Consecutive transactions of the same type share a functional group, so a mixed list produces one group per run of like transactions.
Control numbers are kept consistent for you: IEA02 matches ISA13 and GE02 matches GS06, and both counts reflect what was actually written.
- Parameters:
transactions (Iterable[X12SegmentGroup]) – Transaction set models, e.g. from
X12ModelReader.sender_id (str) – ISA06 interchange sender id, padded to 15 characters.
receiver_id (str) – ISA08 interchange receiver id, padded to 15 characters.
sender_qualifier (str) – ISA05, defaults to
30(US federal tax id).receiver_qualifier (str) – ISA07, defaults to
30.interchange_control_number (str) – ISA13/IEA02, padded to 9 digits.
group_control_number (str) – GS06/GE02 for the first group; later groups increment.
created (datetime | None) – Timestamp for ISA09/10 and GS04/05. Defaults to now.
usage_indicator (str) – ISA15,
Tfor test orPfor production.path (str | None) – Optional file to write to. The interchange is returned either way.
- Returns:
The complete X12 interchange.
- Raises:
ValueError – if a transaction’s type cannot be determined, or an interchange id is not 2 to 15 characters.
- Return type:
- class x12sdk.io.X12ModelWriter(destination=None, *, sender_id, receiver_id, sender_qualifier='30', receiver_qualifier='30', interchange_control_number='000000001', group_control_number='1', created=None, usage_indicator='T')[source]¶
Collects transaction models and writes them out as one X12 interchange.
The mirror image of
X12ModelReader: where the reader yields models from a file, the writer takes models and produces a file.- with X12ModelReader(“in.835”) as reader, X12ModelWriter(
“out.835”, sender_id=”SENDERID”, receiver_id=”RECEIVERID”
- ) as writer:
- for model in reader.models():
writer.write(model)
The interchange is assembled and written when the
withblock exits normally, throughwrite_transactions(), so the envelopes and control numbers follow the same rules. If the block raises, nothing is written: a half-built interchange never reaches disk. The result is also kept oninterchangeafter closing.- Parameters:
- write(transaction)[source]¶
Adds a transaction set model to the interchange.
- Parameters:
transaction (X12SegmentGroup) – A transaction model, e.g. from
X12ModelReaderorx12sdk.generate.- Raises:
ValueError – if the model is not a transaction set, so the error points at the offending
writerather than at the close.- Return type:
None
- write_all(transactions)[source]¶
Adds each transaction in turn.
- Parameters:
transactions (Iterable[X12SegmentGroup]) – Transaction set models.
- Return type:
None
- close()[source]¶
Assembles the interchange and writes it to the destination.
Called for you when a
withblock exits normally; call it yourself when not usingwith.- Returns:
The complete X12 interchange.
- Raises:
ValueError – if nothing was written, or an interchange id is not 2 to 15 characters.
- Return type:
Accessors¶
- class x12sdk.access.ClaimStatusAccess[source]¶
claims()for the 276 and 277 transaction models.The inquiry and the response have identical loop names at every level this walks, so one traversal serves both.
- class x12sdk.access.ClaimSubmissionAccess[source]¶
claims()andsubscribers()for the 837 transaction models.The professional, institutional and dental implementations have identical loop names down every level this walks, so one traversal serves all three.
- class x12sdk.access.EligibilityAccess[source]¶
members()for the 270 and 271 transaction models.The inquiry and the response have identical loop names at every level this walks, so one traversal serves both.
- class x12sdk.access.EligibilityMember(member, subscriber, payer, provider, benefits, is_dependent)[source]¶
One person an eligibility transaction is about, with its context.
memberis the loop describing whoever the question is about: loop 2100D when they are a dependent, and the subscriber’s own loop 2100C when they are not. Reading it does not require knowing which.- Parameters:
- class x12sdk.access.PaidClaim(claim, payer, payee, header_number)[source]¶
One claim on an 835, with the payer and payee that settled it.
- class x12sdk.access.SubmittedClaim(claim, billing_provider, subscriber, payer, patient, is_dependent, relationship)[source]¶
One claim on an 837, with the loops that give it meaning.
patientis the loop describing whoever was treated: loop 2010CA when the patient is a dependent, and the subscriber’s own loop 2010BA when they are not. Reading it does not require knowing which, which is the point.- Parameters:
- class x12sdk.access.Subscriber(subscriber, billing_provider, payer, dependents)[source]¶
One subscriber on an 837, and the dependents filed beneath them.
- class x12sdk.access.TrackedClaim(status, patient, subscriber, payer, requester, provider, is_dependent)[source]¶
One claim being asked about on a 276 or reported on a 277.
patientis loop 2100E when the patient is a dependent and the subscriber’s own loop 2100D when they are not.- Parameters:
- property statuses: Tuple[Any, ...]¶
The STC segments. Empty on a 276, which asks rather than answers.
Generating¶
- class x12sdk.generate.AdjustmentSpec(group, reason, amount, quantity=None)[source]¶
One CAS adjustment: why an amount was not paid.
- class x12sdk.generate.BenefitSpec(service_type='30', status='1', coverage_level=None, plan_description=None)[source]¶
One line of coverage: a question on a 270, an answer on a 271.
The same description serves both, so an inquiry and the response to it can be generated as a matched pair from one specification.
- Parameters:
- class x12sdk.generate.ClaimPair(claim, remittance)[source]¶
A claim submission and the remittance that answers it, as two complete interchanges. Unpacks as
claim, remittance = generate_claim_pair(...).
- class x12sdk.generate.ClaimSpec(charge, adjustments=<factory>, lines=<factory>, status='1', patient_control_number=None)[source]¶
One claim on a remittance.
Give the charge and the adjustments; the payment is derived. Claim-level adjustments and service-line adjustments both count toward the balance, which is what the 835 requires.
- Parameters:
charge (Decimal)
adjustments (Sequence[AdjustmentSpec])
lines (Sequence[ServiceLineSpec])
status (str)
patient_control_number (str | None)
- adjustments: Sequence[AdjustmentSpec]¶
- lines: Sequence[ServiceLineSpec]¶
- class x12sdk.generate.ClaimStatusSpec(patients, payer_name=None, requester_name=None, provider_name=None)[source]¶
A whole 276 or 277: one payer, one requester, one provider, its patients.
- Parameters:
patients (Sequence[StatusPatientSpec])
payer_name (str | None)
requester_name (str | None)
provider_name (str | None)
- patients: Sequence[StatusPatientSpec]¶
- class x12sdk.generate.CoverageSpec(insurance_line='HLT', maintenance_type='021', coverage_level=None, plan_description=None)[source]¶
One HD coverage line on an enrollment: what the member is enrolled in.
- Parameters:
- class x12sdk.generate.DisabilitySpec(type='2', begins=None, ends=None, diagnosis=None)[source]¶
One disability period on a member (loop 2200: a DSB with its dates).
A member can carry several, and they repeat as separate loops; code that keeps only the last one is a bug this generator exists to expose.
- class x12sdk.generate.EligibilitySpec(members, payer_name=None, provider_name=None)[source]¶
A whole 270 or 271: one payer, one provider, a set of members.
- Parameters:
members (Sequence[MemberSpec])
payer_name (str | None)
provider_name (str | None)
- members: Sequence[MemberSpec]¶
- class x12sdk.generate.EmployerSpec(name, identifier=None)[source]¶
One employer of a member (loop 2100D). Up to three per member.
- class x12sdk.generate.EnrolleeSpec(coverages=<factory>, dependent=False, relationship='19', member_id=None, benefit_status='A', maintenance_type='021', employers=<factory>, disabilities=<factory>)[source]¶
One member on an 834.
The 834 has no HL hierarchy. A dependent is a separate member record marked by INS01 rather than a loop nested under the subscriber, so
dependentchanges the record rather than where it sits.- Parameters:
coverages (Sequence[CoverageSpec])
dependent (bool)
relationship (str)
member_id (str | None)
benefit_status (str)
maintenance_type (str)
employers (Sequence[EmployerSpec])
disabilities (Sequence[DisabilitySpec])
- coverages: Sequence[CoverageSpec]¶
- employers: Sequence[EmployerSpec]¶
- disabilities: Sequence[DisabilitySpec]¶
- class x12sdk.generate.EnrollmentSpec(enrollees, sponsor_name=None, payer_name=None)[source]¶
A whole 834: one sponsor, one payer, a roster of members.
- Parameters:
enrollees (Sequence[EnrolleeSpec])
sponsor_name (str | None)
payer_name (str | None)
- enrollees: Sequence[EnrolleeSpec]¶
- class x12sdk.generate.MemberSpec(benefits=<factory>, dependent=False, relationship='19', member_id=None)[source]¶
One person an eligibility transaction is about.
As on an 837, the person is either the subscriber or a dependent of one, and the two sit at different depths of the hierarchy. Unlike an 837 the payload is coverage rather than claims, so this is a separate type from
PatientSpec.- Parameters:
benefits (Sequence[BenefitSpec])
dependent (bool)
relationship (str)
member_id (str | None)
- benefits: Sequence[BenefitSpec]¶
- class x12sdk.generate.PatientSpec(claims, dependent=False, relationship='19')[source]¶
One patient on a claim submission, with the claims filed for them.
In an 837 a patient is either the subscriber themselves or a dependent of one, and the two sit at different depths in the hierarchy. Saying which here is what puts the claim on the right branch.
- class x12sdk.generate.ProviderAdjustmentSpec(reason, amount, identifier=None)[source]¶
One provider-level adjustment: money moved at the payee level, outside any claim, carried in the PLB segment. A positive amount is taken out of the payment (an overpayment recovery, a withholding); a negative amount is added to it (interest owed to the provider).
- class x12sdk.generate.RemittanceSpec(claims, payer_name=None, payee_name=None, provider_adjustments=<factory>)[source]¶
A whole 835: one payer paying one payee for a set of claims.
The check amount in BPR02 is derived: every claim’s payment, less the provider-level adjustments. A remittance whose adjustments exceed what the claims pay would need a negative check, which the 835 does not allow, so it cannot be written down.
- Parameters:
- provider_adjustments: Sequence[ProviderAdjustmentSpec]¶
- class x12sdk.generate.ServiceLineSpec(charge, procedure=None, adjustments=<factory>, units=1, tooth=None, surfaces=<factory>)[source]¶
One service line on a claim.
toothandsurfacesdescribe a dental line (the 837D’s TOO segment) and are refused on a professional or institutional claim, which has nowhere to put them. An 835 paying a dental claim does not repeat them.- Parameters:
- adjustments: Sequence[AdjustmentSpec]¶
- class x12sdk.generate.StatusPatientSpec(claims, dependent=False, relationship='19', member_id=None)[source]¶
A patient on a 276 or 277, and the claims being tracked for them.
- Parameters:
claims (Sequence[TrackedClaimSpec])
dependent (bool)
relationship (str)
member_id (str | None)
- claims: Sequence[TrackedClaimSpec]¶
- class x12sdk.generate.SubmissionSpec(patients, billing_provider_name=None, payer_name=None, submitter_name=None)[source]¶
A whole 837: one billing provider filing claims with one payer.
- Parameters:
patients (Sequence[PatientSpec])
billing_provider_name (str | None)
payer_name (str | None)
submitter_name (str | None)
- patients: Sequence[PatientSpec]¶
- class x12sdk.generate.TrackedClaimSpec(charge, patient_control_number=None, payer_claim_control_number=None, paid=None, status_category='F1', status_code='1')[source]¶
One claim whose status is asked about on a 276 or reported on a 277.
paidand the status codes are only rendered on the response; an inquiry carries the identifying detail and nothing else, so the same specification builds a 276 and the 277 answering it.- Parameters:
- class x12sdk.generate.ValueFactory(seed)[source]¶
Produces plausible, obviously synthetic values from a seeded RNG.
- Parameters:
seed (int)
- dental_procedure()[source]¶
Returns
(code, tooth, surfaces)for a dental service line.toothisNonefor a procedure not done to one tooth (an exam, a cleaning), andsurfacesis empty unless the procedure is a filling, whose code says how many surfaces it covers.- Return type:
- dental_fee(code)[source]¶
A fee in the usual range for a code from
dental_procedure().
- diagnosis()[source]¶
An ICD-10-CM code with the decimal point removed, as X12 carries it.
- Return type:
- birth_date(youngest=1, oldest=90)[source]¶
A date of birth, relative to the same fixed epoch as service dates.
- x12sdk.generate.adjudicate(claim, values, *, denial_rate=0.15)[source]¶
Decides an invented outcome for a submitted claim.
A share
denial_rateof claims is denied outright (CLP02 4, every line adjusted to nothing). The rest are processed as primary: most with a contractual write-off on each line (CO 45, the usual gap between charge and fee schedule), some also leaving a deductible or coinsurance to the patient (PR), and some paid in full. Outcomes are made of adjustments, so the payment is derived and the 835 balances by construction.- Parameters:
claim (ClaimSpec)
values (ValueFactory)
denial_rate (float)
- Return type:
- x12sdk.generate.build_270(spec, *, seed=0, control_number='0001')[source]¶
Builds a validated 270 eligibility inquiry from a specification.
- Parameters:
spec (EligibilitySpec) – Who is asking, of whom, and about which members.
seed (int) – Seeds the values the specification leaves unstated.
control_number (str) – ST02/SE02. At least 4 characters.
- Return type:
EligibilityInquiry
Every benefit in the specification is rendered. EQ repeats within loop 2110, so an inquiry can ask about several service types at once.
- x12sdk.generate.build_271(spec, *, seed=0, control_number='0001')[source]¶
Builds a validated 271 eligibility response from a specification.
The 271 carries a list of EB segments per member, so every benefit in the specification appears. This is the asymmetry that makes the 270 raise.
- Parameters:
spec (EligibilitySpec)
seed (int)
control_number (str)
- Return type:
EligibilityBenefit
- x12sdk.generate.build_276(spec, *, seed=0, control_number='0001')[source]¶
Builds a validated 276 claim status inquiry from a specification.
- Parameters:
spec (ClaimStatusSpec)
seed (int)
control_number (str)
- Return type:
HealthCareClaimsStatusRequest
- x12sdk.generate.build_277(spec, *, seed=0, control_number='0001')[source]¶
Builds a validated 277 claim status response from a specification.
Takes the same specification as
build_276(), so an inquiry and the response to it can be built as a matched pair.- Parameters:
spec (ClaimStatusSpec)
seed (int)
control_number (str)
- Return type:
HealthCareClaimsStatusResponse
- x12sdk.generate.build_834(spec, *, seed=0, control_number='0001')[source]¶
Builds a validated 834 enrollment transaction from a specification.
- Parameters:
spec (EnrollmentSpec) – The sponsor, the payer, and the roster of members.
seed (int) – Seeds the values the specification leaves unstated.
control_number (str) – ST02/SE02. At least 4 characters.
- Return type:
BenefitEnrollmentAndMaintenance
- x12sdk.generate.build_835(spec, *, seed=0, control_number='0001', procedure_qualifier='HC', patients=None, payee_npi=None)[source]¶
Builds a validated 835 transaction model from a specification.
The last three parameters let the remittance answer a particular claim submission, which is how
generate_claim_pair()keeps the two in step.- Parameters:
spec (RemittanceSpec) – What the remittance should contain.
seed (int) – Seeds the values that the specification leaves unstated.
control_number (str) – ST02/SE02. At least 4 characters, per the standard.
procedure_qualifier (str) – SVC01-1.
HCfor HCPCS/CPT,ADfor dental (CDT) codes.patients (Sequence[Tuple[str, str, str]] | None) –
(last, first, member id)for each claim, in order, for the NM1*QC patient name. Invented when not given.payee_npi (str | None) – The payee’s NPI. Invented when not given.
- Returns:
A validated
HealthCareClaimPayment.- Return type:
HealthCareClaimPayment
- x12sdk.generate.build_837d(spec, *, seed=0, control_number='0001')[source]¶
Builds a validated 837D transaction model from a specification.
- Parameters:
spec (SubmissionSpec) – What the submission should contain. A line’s
toothandsurfacesbecome its TOO segment.seed (int) – Seeds the values that the specification leaves unstated.
control_number (str) – ST02/SE02. At least 4 characters, per the standard.
- Returns:
A validated
HealthCareClaimDental.- Return type:
HealthCareClaimDental
- x12sdk.generate.build_837i(spec, *, seed=0, control_number='0001')[source]¶
Builds a validated 837I transaction model from a specification.
- Parameters:
spec (SubmissionSpec) – What the submission should contain.
seed (int) – Seeds the values that the specification leaves unstated.
control_number (str) – ST02/SE02. At least 4 characters, per the standard.
- Return type:
HealthCareClaimInstitutional
- x12sdk.generate.build_837p(spec, *, seed=0, control_number='0001')[source]¶
Builds a validated 837P transaction model from a specification.
- Parameters:
spec (SubmissionSpec) – What the submission should contain.
seed (int) – Seeds the values that the specification leaves unstated.
control_number (str) – ST02/SE02. At least 4 characters, per the standard.
- Returns:
A validated
HealthCareClaimProfessional.- Return type:
HealthCareClaimProfessional
- x12sdk.generate.build_claim_pair(claims, *, claim_type='837p', seed=0, dependent_rate=0.3, billing_provider_name=None, payer_name=None, control_number='0001')[source]¶
Builds a claim submission model and the remittance model that answers it.
- Parameters:
- Returns:
(submission, remittance)models, both validated.- Return type:
- x12sdk.generate.claim_pair_specs(count, values, *, claim_type='837p', denial_rate=0.15)[source]¶
Invents
countclaims of a type, each with an invented outcome.
- x12sdk.generate.claim_specs_to_patients(claims, values, *, dependent_rate=0.3)[source]¶
Puts one claim on each patient, splitting them across both branches.
- Parameters:
values (ValueFactory)
dependent_rate (float)
- Return type:
- x12sdk.generate.denial(group, reason, amount)[source]¶
Shorthand for a payer-side adjustment.
>>> denial("CO", "45", "30.00").amount Decimal('30.00')
- Parameters:
- Return type:
- x12sdk.generate.generate_270(*, seed=0, members=5, dependent_rate=0.3, payer_name=None, provider_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]¶
Generates a complete 270 eligibility inquiry.
- Parameters:
seed (int) – Reproduces the same file when unchanged.
members (int | Sequence[MemberSpec] | EligibilitySpec) – A number of members to invent, specifications to follow, or a whole
EligibilitySpec.dependent_rate (float) – The share of members who are a dependent of the subscriber rather than the subscriber themselves, so generated files exercise both branches. Ignored when an
EligibilitySpecis given.payer_name (str | None) – Defaults to a synthetic plan name.
provider_name (str | None) – Defaults to a synthetic provider name.
sender_id (str) – ISA06 / GS02.
receiver_id (str) – ISA08 / GS03.
control_number (str) – ST02 / SE02, at least 4 characters.
- Returns:
The interchange, ISA through IEA.
- Return type:
- x12sdk.generate.generate_271(*, seed=0, members=5, dependent_rate=0.3, payer_name=None, provider_name=None, sender_id='SYNTHETICPAYER', receiver_id='SYNTHETICPROV', control_number='0001')[source]¶
Generates a complete 271 eligibility response.
Takes the same specification as
generate_270(), so an inquiry and the response to it can be generated as a matched pair from one spec.
- x12sdk.generate.generate_276(*, seed=0, patients=5, dependent_rate=0.3, payer_name=None, requester_name=None, provider_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]¶
Generates a complete 276 claim status inquiry.
- Parameters:
seed (int) – Reproduces the same file when unchanged.
patients (int | Sequence[StatusPatientSpec] | ClaimStatusSpec) – A number of patients to invent, specifications to follow, or a whole
ClaimStatusSpec.dependent_rate (float) – The share of patients who are a dependent of the subscriber rather than the subscriber themselves, so generated files exercise both branches. Ignored when a
ClaimStatusSpecis given.payer_name (str | None) – Defaults to a synthetic plan name.
requester_name (str | None) – The information receiver asking. Defaults to a synthetic name.
provider_name (str | None) – The service provider the claims belong to.
sender_id (str) – ISA06 / GS02.
receiver_id (str) – ISA08 / GS03.
control_number (str) – ST02 / SE02, at least 4 characters.
- Returns:
The interchange, ISA through IEA.
- Return type:
- x12sdk.generate.generate_277(*, seed=0, patients=5, dependent_rate=0.3, payer_name=None, requester_name=None, provider_name=None, sender_id='SYNTHETICPAYER', receiver_id='SYNTHETICPROV', control_number='0001')[source]¶
Generates a complete 277 claim status response.
Takes the same specification as
generate_276()and stays in step with it on the same seed, so an inquiry and the response to it describe the same people and the same claims.- Returns:
The interchange, ISA through IEA.
- Parameters:
- Return type:
- x12sdk.generate.generate_834(*, seed=0, enrollees=5, dependent_rate=0.3, sponsor_name=None, payer_name=None, sender_id='SYNTHSPONSOR', receiver_id='SYNTHETICPAYER', control_number='0001')[source]¶
Generates a complete 834 benefit enrollment and maintenance transaction.
The 834 has no HL hierarchy: a dependent is a separate member record told apart by INS01 and INS02, not a loop nested under the subscriber. Both kinds of record appear by default so code reading an 834 can be tested on each.
- Parameters:
seed (int) – Reproduces the same file when unchanged.
enrollees (int | Sequence[EnrolleeSpec] | EnrollmentSpec) – A number of members to invent, specifications to follow, or a whole
EnrollmentSpec.dependent_rate (float) – The share of records marked as a dependent. Ignored when an
EnrollmentSpecis given.sponsor_name (str | None) – The plan sponsor. Defaults to a synthetic name.
payer_name (str | None) – Defaults to a synthetic plan name.
sender_id (str) – ISA06 / GS02.
receiver_id (str) – ISA08 / GS03.
control_number (str) – ST02 / SE02, at least 4 characters.
- Returns:
The interchange, ISA through IEA.
- Return type:
- x12sdk.generate.generate_835(*, seed=0, claims=5, provider_adjustments=None, payer_name=None, payee_name=None, sender_id='SYNTHETICPAYER', receiver_id='SYNTHETICPROV', control_number='0001')[source]¶
Generates a complete 835 remittance advice.
- Parameters:
seed (int) – Reproduces the same file when unchanged.
claims (int | Sequence[ClaimSpec]) – A number of claims to invent, or specifications to follow.
provider_adjustments (int | Sequence[ProviderAdjustmentSpec] | None) – Provider-level (PLB) adjustments: a number to invent, specifications to follow, or
Nonefor the default, which is one invented adjustment when the claims are invented and none when they are specified, so a described scenario contains only what it describes. At most six fit on a remittance.payer_name (str | None) – Defaults to a synthetic plan name.
payee_name (str | None) – Defaults to a synthetic provider name.
sender_id (str) – ISA06 / GS02.
receiver_id (str) – ISA08 / GS03.
control_number (str) – ST02 / SE02, at least 4 characters.
- Returns:
The interchange, ISA through IEA.
- Return type:
- x12sdk.generate.generate_837d(*, seed=0, claims=5, dependent_rate=0.3, billing_provider_name=None, payer_name=None, submitter_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]¶
Generates a complete 837D dental claim submission.
Takes the same specification as
generate_837p(). AServiceLineSpec’s procedure is a CDT code, billed under theADqualifier, and itstoothandsurfacesbecome the line’s TOO segment. Invented lines mix procedures done to a tooth (with surfaces for a filling) and procedures that are not (an exam, a cleaning), and both patient branches appear by default.
- x12sdk.generate.generate_837i(*, seed=0, claims=5, dependent_rate=0.3, billing_provider_name=None, payer_name=None, submitter_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]¶
Generates a complete 837I institutional claim submission.
Takes the same specification as
generate_837p(); a ServiceLineSpec’s procedure becomes the SV2 procedure composite, billed under a revenue code. The subscriber/dependent branch is the same, and both appear by default.
- x12sdk.generate.generate_837p(*, seed=0, claims=5, dependent_rate=0.3, billing_provider_name=None, payer_name=None, submitter_name=None, sender_id='SYNTHETICPROV', receiver_id='SYNTHETICPAYER', control_number='0001')[source]¶
Generates a complete 837P professional claim submission.
- Parameters:
seed (int) – Reproduces the same file when unchanged.
claims (int | Sequence[ClaimSpec] | SubmissionSpec) – A number of claims to invent, specifications to follow, or a whole
SubmissionSpecwhen you want to place each claim on a particular patient.dependent_rate (float) – The share of patients who are a dependent of the subscriber rather than the subscriber themselves, so generated files exercise both branches of the hierarchy. Ignored when a
SubmissionSpecis given, which says where each claim goes.billing_provider_name (str | None) – Defaults to a synthetic provider name.
payer_name (str | None) – Defaults to a synthetic plan name.
submitter_name (str | None) – Defaults to the billing provider.
sender_id (str) – ISA06 / GS02.
receiver_id (str) – ISA08 / GS03.
control_number (str) – ST02 / SE02, at least 4 characters.
- Returns:
The interchange, ISA through IEA.
- Return type:
- x12sdk.generate.generate_claim_pair(*, seed=0, claims=5, claim_type='837p', denial_rate=0.15, dependent_rate=0.3, billing_provider_name=None, payer_name=None, provider_id='SYNTHETICPROV', payer_id='SYNTHETICPAYER', control_number='0001')[source]¶
Generates a claim submission and the remittance that answers it.
Every claim on the 837 is paid, reduced or denied by exactly one claim payment on the 835, linked by CLM01 = CLP01, with the same charge, the same procedure on each line, and the same patient, payer and payee.
- Parameters:
seed (int) – Reproduces the same pair when unchanged.
claims (int | Sequence[ClaimSpec]) – A number of claims to invent, outcomes included, or
ClaimSpec``s to follow: a spec's lines and charges are what was submitted, its adjustments and ``statuswhat the payer decided.claim_type (str) –
"837p","837i"or"837d".denial_rate (float) – The share of invented claims denied outright. The rest are paid, most less a contractual write-off, some also leaving a share to the patient. Ignored when the claims are specified.
dependent_rate (float) – The share of patients who are a dependent of the subscriber, as for
generate_837p().billing_provider_name (str | None) – The provider billing, and so the payee.
payer_name (str | None) – The payer billed, and so the payer paying.
provider_id (str) – The provider’s interchange id: the 837’s sender and the 835’s receiver.
payer_id (str) – The payer’s interchange id, the other way round.
control_number (str) – ST02 / SE02 on both, at least 4 characters.
- Returns:
ClaimPair(claim, remittance), two complete interchanges.- Return type:
- x12sdk.generate.patient_responsibility(reason, amount)[source]¶
Shorthand for a
PRadjustment: deductible, coinsurance or copay.- Parameters:
reason (str)
- Return type:
- x12sdk.generate.provider_adjustment(reason, amount, identifier=None)[source]¶
Shorthand for a PLB provider-level adjustment.
>>> provider_adjustment("WO", "25.00", "PCN000001").amount Decimal('25.00')
- Parameters:
- Return type:
- x12sdk.generate.random_claims(count, values, *, denial_rate=0.4)[source]¶
Builds plausible claims with a mix of paid, adjusted and denied outcomes.
Used when a caller asks for a number of claims rather than describing each one.
denial_rateis the share of claims carrying a payer-side adjustment; the rest are paid in full or carry only patient cost share.- Parameters:
count (int)
values (ValueFactory)
denial_rate (float)
- Return type:
- x12sdk.generate.random_dental_lines(values, count)[source]¶
Invents
countdental lines, each with its procedure, and the tooth and surfaces that procedure implies, already decided.- Parameters:
values (ValueFactory)
count (int)
- Return type:
- x12sdk.generate.random_dental_patients(count, values, *, dependent_rate=0.3)[source]¶
Builds plausible dental patients carrying one claim each.
A visit is one to four lines, so files mix lines with a tooth, lines with a tooth and surfaces, and lines with neither.
dependent_rateis the share of patients who are a dependent rather than the subscriber.- Parameters:
count (int)
values (ValueFactory)
dependent_rate (float)
- Return type:
- x12sdk.generate.random_enrollees(count, values, *, dependent_rate=0.3)[source]¶
Builds a roster mixing subscribers and dependents.
dependent_rateis the share of records marked as a dependent, so both kinds of INS record appear by default. Every subscriber carries an employer, a quarter of them a second one, and a fifth of all members a disability period, so the repeating 2100D and 2200 loops, where a reader that keeps only the last record goes wrong, are exercised by default.- Parameters:
count (int)
values (ValueFactory)
dependent_rate (float)
- Return type:
- x12sdk.generate.random_members(count, values, *, dependent_rate=0.3)[source]¶
Builds members asking about whole-plan coverage.
dependent_rateis the share who are a dependent of the subscriber rather than the subscriber themselves, so both branches appear by default.- Parameters:
count (int)
values (ValueFactory)
dependent_rate (float)
- Return type:
- x12sdk.generate.random_patients(count, values, *, dependent_rate=0.3)[source]¶
Builds plausible patients carrying one claim each.
dependent_rateis the share of patients who are a dependent of the subscriber rather than the subscriber themselves. Both branches appear by default, because code that walks an 837 tends to handle only one of them.- Parameters:
count (int)
values (ValueFactory)
dependent_rate (float)
- Return type:
- x12sdk.generate.random_provider_adjustments(count, values, claims)[source]¶
Invents provider-level adjustments small enough to leave the check positive.
Two kinds appear: an overpayment recovery (
WO) naming the claim it recovers, taken out of the payment, and interest owed to the provider (L6), added to it as a negative amount. Each is at most a few percent of what the claims pay, so BPR02 stays non-negative however many are asked for (up to the six a PLB holds).- Parameters:
count (int)
values (ValueFactory)
- Return type:
- x12sdk.generate.random_status_patients(count, values, *, dependent_rate=0.3)[source]¶
Builds patients each tracking one claim, across both branches.
dependent_rateis the share who are a dependent of the subscriber rather than the subscriber themselves.- Parameters:
count (int)
values (ValueFactory)
dependent_rate (float)
- Return type:
Denial analytics¶
- class x12sdk.denials.Adjustment(payer_name, payer_id, patient_control_number, payer_claim_control_number, claim_status_code, claim_charge_amount, claim_payment_amount, patient_responsibility_amount, level, group_code, reason_code, amount, quantity, category, procedure=None, revenue_code=None, line_charge_amount=None, line_payment_amount=None, remark_codes=<factory>)[source]¶
One CAS reason code, with the claim and line it came from.
Amounts are the values as adjudicated:
amountis the adjustment, not the charge. A positive amount reduces what the payer pays.- Parameters:
payer_name (str | None)
payer_id (str | None)
patient_control_number (str | None)
payer_claim_control_number (str | None)
claim_status_code (str | None)
claim_charge_amount (Decimal | None)
claim_payment_amount (Decimal | None)
patient_responsibility_amount (Decimal | None)
level (str)
group_code (str | None)
reason_code (str | None)
amount (Decimal)
quantity (Decimal | None)
category (str)
procedure (str | None)
revenue_code (str | None)
line_charge_amount (Decimal | None)
line_payment_amount (Decimal | None)
- class x12sdk.denials.DenialSummaryRow(payer_name, group_code, reason_code, category, adjustment_count, claim_count, total_amount)[source]¶
One payer/group/reason combination, with its volume and value.
- Parameters:
- x12sdk.denials.categorize(reason_code)[source]¶
Returns the analysis category for a CARC, or
otherwhen unmapped.>>> categorize("45") 'contractual' >>> categorize("A2") 'other'
- x12sdk.denials.denial_summary(adjustments, *, denial_groups=frozenset({'CO', 'OA', 'PI'}), include_patient_responsibility=False)[source]¶
Aggregates adjustments by payer, adjustment group and reason code.
By default only payer-side groups are counted (
CO,OA,PI); patient cost share (PR) and corrections (CR) are excluded, because a deductible is not a denial. Setinclude_patient_responsibilityto keep every group.claim_countcounts distinct claims, so a reason appearing on three lines of one claim counts once.adjustment_countcounts every occurrence.- Returns:
Rows sorted by
total_amountdescending.- Parameters:
adjustments (Iterable[Adjustment])
denial_groups (frozenset)
include_patient_responsibility (bool)
- Return type:
- x12sdk.denials.describe(rows, descriptions)[source]¶
Attaches descriptions from a code list you loaded.
x12sdk ships no CARC/RARC text; see
x12sdk.denials.load_code_descriptions().- Parameters:
rows (Sequence[DenialSummaryRow]) – Output of
denial_summary().descriptions (dict) – Mapping of code to description.
- Returns:
One dict per row with a
descriptionkey added.- Return type:
- x12sdk.denials.iter_adjustments(transaction)[source]¶
Flattens every CAS adjustment in an 835 into
Adjustmentrecords.- Parameters:
transaction – A
HealthCareClaimPaymentmodel, as returned byx12sdk.io.X12ModelReader.- Returns:
One record per populated CAS reason code, claim level first then each service line, in transaction order.
- Return type:
Claims are reached through
x12sdk.access.RemittanceAccess.claims()rather than by walking loops here.>>> from x12sdk.io import X12ModelReader >>> from x12sdk.denials import iter_adjustments >>> with X12ModelReader(remittance) as reader: ... for txn in reader.models(): ... rows = list(iter_adjustments(txn))
- x12sdk.denials.load_code_descriptions(source, *, code_field='code', text_field='text')[source]¶
Loads CARC/RARC descriptions from a file you supply.
x12sdk ships no code-list text. Obtain the official list from <https://x12.org/codes> (or a CMS publication of it) under the licence that applies to you, then load it here.
Accepts either a JSON object of
{code: text}or a CSV with a code column and a text column, whose names default tocodeandtext.
- x12sdk.denials.to_dataframe(adjustments)[source]¶
Returns the adjustments as a pandas
DataFrame.Requires the optional pandas dependency:
pip install 'x12sdk[pandas]'. Amounts stay asDecimalso totals are exact; cast them yourself if you need float maths.- Parameters:
adjustments (Iterable[Adjustment])