Skip to main content

courtpy logo

courtpy

Version PyPI Latest Release GitHub Latest Release
Status Build Status Code Coverage Development Status Project Stability
Documentation Hosted By
Tools Documentation Linter Type Checker Dependency Manager Pre-commit CI Editor Settings Repository Template Dependency Maintainer
Compatibility Compatible Python Versions Linux MacOS Windows
Stats PyPI Download Rate (per month) GitHub Stars GitHub Contributors GitHub Issues GitHub Forks

What is courtpy?

courtpy collects court opinions, turns them into data, and analyzes them. It is designed for empirical legal research, where the data has to be explained and the results reproduced. You don't need to know how to code to use courtpy. Everything is described in a simple settings files and parsing instructions are located in CSV files (of which many are included out of the box). But if you do code, courtpy is highly extensible to allow easy data munging, creation of new fields, and wrapping custom tools.

  • Collect opinions from CourtListener, from its free bulk data or its API, or use opinions you downloaded from Lexis-Nexis.
  • Parse them into a table, one row for each case, with rules written in spreadsheets (CSV files) that anyone can read and change: the parties and their roles, the court, the judges, the disposition, the issues discussed, the citations, and more.
  • Study the judges on each case, with integration of the Federal Judicial Center's biographical data and Judicial Common Space Scores (from fjc-biographies and judicial-common-space). Data about the overall political and judicial context can also be easily added, including Martin-Quinn scores, NOMINATE scores of Congress, the Supreme Court Database, and the Federal Judicial Center's Integrated Database of appeals.
  • Analyze the data with amos (which is built into courtpy), which compares models, preprocessing, and statistical methods, and records everything needed to reproduce the results.

Why use courtpy?

  • Transparent. What courtpy finds in an opinion comes from rules in CSV files, not from code, so a study's methods can be read, reported, and changed by anyone who can use a spreadsheet. The rules are part of the study, so others can check them.
  • Reproducible. A whole study (which cases, how they were parsed and coded, and how they were analyzed) fits in one settings file, and amos records every step and the version of every package.

Techniques and datasets

courtpy is built on amos. A study is an amos project, described in one settings file that names techniques in steps of the project's workers. courtpy adds these techniques to those of amos, and a settings file can name them like any other:

StageStepsTechniques
wranglerLoadersdownload_biographies, download_idb, download_jcs, download_politics, download_scdb, load_cases, load_court_listener, load_idb, load_lexis_nexis, load_politics, load_roster, load_scdb
Parsersparse_agencies, parse_all, parse_citations, parse_civil, parse_constitutional, parse_criminal, parse_federal, parse_general, parse_header, parse_lexis_nexis, parse_review
Cleanersdrop_text_columns
Mungerscode_case_type, code_outcome, code_panels, code_parties, split_values, tidy_cases
Mergersadd_biography, add_circuit, add_court_scores, add_executive, add_high_court, add_idb, add_jcs, add_judge_scores, add_legislature, add_scdb
Shaperscases_to_case_types, cases_to_courts, cases_to_dockets, cases_to_judges, cases_to_party_types, cases_to_votes, dockets_to_cases, dockets_to_votes, votes_to_cases
explorerDescriberscompare_with_idb
artistPlotscases_over_time, court_rates, idb_confusion_matrices, idb_missing_differences, issues_over_time, judge_network, lower_court_rates, panel_composition, trends_by_administration
criticEvaluatorsaudit_coverage, audit_parsing, audit_random_assignment, validate_coding
Infererspanel_effects

Each of courtpy's datasets is an amos.Dataset whose rows are one kind of thing. The loaders make Cases, and the shapers turn one kind into another:

Dataset One row for each Made by
Cases Case, with its information and the text of its sections. the loaders, votes_to_cases, dockets_to_cases
Dockets Docket number of each case (a case that consolidated several appeals has a row for each), with the case's columns. cases_to_dockets
Votes Judge on each case (or on each docket), with the case's columns and the judge's vote. cases_to_votes, dockets_to_votes
Judges Judge, with what is known about the judge and summaries of the judge's votes. cases_to_judges
Courts Court, with summaries of its cases and judges. cases_to_courts
CaseTypes Case type (such as criminal, civil, tort, or contract), with summaries of its cases. cases_to_case_types
PartyTypes Party type, with summaries of the cases of parties of that type. cases_to_party_types

Cases, Dockets, and Votes can be made from each other. The others summarize many cases and keep nothing about any one of them (such as its docket number or date), so a researcher can see, for example, the mix of case types that each court decides, but there is no going back. Every dataset can be saved and loaded whole (with save and load), as amos's save_data saves it.

Getting started

Requirements

courtpy requires Python 3.11 or later. It runs on Linux, macOS, and Windows.

Extracting cases from CourtListener's bulk data needs a good connection and room for the bulk files (about 63 GB for the opinions, clusters, and dockets), unless they are streamed. Downloading with the API needs a free CourtListener account.

Installation

To install courtpy, use pip:

pip install courtpy

To install the latest development version from GitHub instead:

pip install git+https://github.com/WithPrecedent/courtpy

To work on courtpy itself, see the contribution guide.

Usage

Collecting opinions from CourtListener

CourtListener offers its opinions in two ways, and courtpy uses both. Both save each case as a JSON file in a folder named for its court (such as courtlistener/ca1/4567890.json), and the parser reads them the same way.

The bulk data is the whole CourtListener database, published as compressed CSV files every three months. It needs no API key and has no limits, so it is the best way to collect many cases. The files are large (the opinions file is more than 50 GB), so extracting cases takes a few hours. The files are kept outside your project so that they can be used again:

import courtpy

courtpy.BulkData().extract(
    courts = "federal_circuits",
    start_date = "2019-01-01",
    end_date = "2019-12-31",
    folder = "courtlistener")

The API is best for small or very recent sets of cases. It needs an API key: sign in to CourtListener and open the "API" page of your profile. A free account can make 5 requests a minute, 50 an hour, and 125 a day (as of 2026). courtpy asks for 20 cases at a time, waits when CourtListener asks it to, and saves its place, so a download stopped by the daily limit resumes where it stopped when it is run again:

courtpy.CourtListener().download("ca1", "2026-09-01", "2026-09-30", "courtlistener")

Courts are named by their CourtListener ids (such as ca1, cadc, cafc, and scotus) or by groups: federal_appellate, federal_circuits, and scotus.

Store your API key once with courtpy key set. See Keeping your API key secret for where it is kept and how courtpy finds it.

Using opinions from Lexis-Nexis

Lexis-Nexis downloads many cases into one text file. Divide such files into one file for each case, and then parse them as the source "lexis_nexis":

courtpy.lexis.split("downloads", folder = "lexis_nexis")
table = courtpy.parse("lexis_nexis", source = "lexis_nexis")

Parsing and coding

courtpy.parse reads a folder of saved cases and returns a pandas.DataFrame, one row for each case, labeled by its id. courtpy.code codes it and makes it Cases:

table = courtpy.parse("courtlistener")
cases = courtpy.code(table)  # parties, case types, and outcomes
cases.save("cases.csv")  # and the whole dataset in "cases.joblib"
cases = courtpy.Cases.load("cases.csv")

The rules are in the CSV files in courtpy's instructions folder, with a guide to writing your own. For example, the rules for federal cases may make more than 250 variables, including:

Variables Meaning
party1, party2 The parties on each side of "v."
party1_appellant, party2_respondent, party1_united_states, ... Each party's role, and whether it is the United States.
court_num, court_name courtpy's number and name for the court in "instructions/federal/courts.csv" (such as 10 and "tenth_circuit"): for a court of appeals, its number is its circuit (1 to 11, 12 for the D.C. Circuit, 13 for the Federal Circuit), and 99 for the Supreme Court.
lower_court_num, lower_court_name The same for the court whose decision is reviewed (such as "district_of_colorado"), from the history (or CourtListener's docket). Missing for a review of an agency.
panel_judges, panel_size, author, concurring, dissenting The judges.
disposition_reverse, decision_reverse, opinion_reverse, ... The disposition: from the header, from the decision that the opinion states ("AFFIRMED."), and from the opinion's words anywhere.
party1_agencies, party2_agencies, history_agencies The federal agencies that each party and the history name, separated by "; " (from "instructions/federal/agencies.csv").
agencies Every federal agency that the case names, separated by "; " (such as "Internal Revenue Service; United States Tax Court").
civil_..., constitutional_..., criminal_..., procedure_..., standard_... Issues discussed in the opinion (such as criminal_firearm, civil_titlevii, and standard_de_novo).
review_district, review_agency, review_immigration, district_judges The kind of review, and the district judge of an appeal from a district court.
citations_case, citations_statute, ... Citations in the opinion.
published, year, date_filed, word_count Other information.

The coders (which are amos techniques) add each party's role in the appeal and in the case (such as party2_criminal_defendant), the case types (type_criminal, type_civil, and one for each other prefix of the civil, criminal, and constitutional rules, such as type_tort and type_contract), and the outcomes: outcome_reversal, outcome_party1_won, outcome_criminal_defendant_won, and others.

Adding the judges and the politics of the day

The rules find the judges' names as an opinion writes them ("LYNCH"). To study the judges, make a roster once from the Federal Judicial Center's biographical directory (three small files, which fjc-biographies downloads and parses), and more coders can use it. jcs = True adds each judge's Judicial Common Space score, computed by judicial-common-space:

courtpy.judges.Roster.from_fjc(jcs = True).save()
votes = courtpy.code(table, [
    "code_parties", "code_case_type", "code_outcome", "code_panels",
    "add_executive", "add_legislature", "add_circuit", "cases_to_votes"])

Cases, judges, years, and other researchers' data are tables whose rows are different things, so these coders are the mergers and shapers of amos: a merger adds the columns of another table to the rows that it matches, without ever adding or losing a row, and records how many rows it matched.

Coder Adds
add_biography What the roster says about each judge. In Cases, the columns are numbered by each judge's seat on the panel (judge_name1, judge_party1, judge_woman1, ..., judge_name2, ...); in Votes, each row has its judge's (judge_party, ...). A function can take the place of the roster.
add_jcs Each judge's Judicial Common Space score, numbered in the same way (judge_jcs1, ...).
code_panels The judges of each panel who were found in the roster (panel_names and panel_found, and each judge's Federal Judicial Center name and number in judge_name1 and judge_nid1, judge_name2 and judge_nid2, and so on) and the panel's composition, such as panel_party (the mean party of the presidents who appointed its judges, from -1 for Democrats to 1 for Republicans), panel_woman, panel_age, and panel_prosecutor.
add_executive The executive (president for federal cases) on the day the case was decided (executive_name) and their political party (executive_ideology, -1 or 1).
add_legislature For federal cases, the median NOMINATE score of each chamber of the Congress then sitting (senate_ideology and house_ideology).
add_high_court For federal cases, Martin-Quinn score of the median justice in the Supreme Court's term then sitting (high_court_ideology).
add_circuit The makeup of the whole circuit on the day the case was decided (for a district court, the circuit that hears its appeals): the median and total of the parties of the presidents who appointed its active judges (circuit_median_party, circuit_total_party) and of their Judicial Common Space scores (circuit_median_jcs, circuit_total_jcs). Senior judges, who do not sit en banc, are left out.
add_judge_scores, add_court_scores Behavioral scores of each judge or court computed from training data (such as a table of Judges or Courts made from the training cases), matched by the judge's or court's number.
cases_to_votes Votes: a table with one row for each judge on each case, with the judge's attributes (judge_party, ...), the other judges' (colleagues_party, ...), and the judge's vote (vote_reversal, the outcome or its opposite for a judge who dissented).
votes_to_cases Undoes cases_to_votes: Votes become Cases again.
cases_to_judges Judges: a table with one row for each judge, with how many cases the judge decided (cases), the judge's attributes, and the shares of the judge's votes (vote_reversal, judge_dissented, ...) and of the judge's cases of each type (type_criminal, ...).
cases_to_courts, cases_to_case_types, cases_to_party_types Courts, CaseTypes, and PartyTypes: a row for each court, case type, or party type, with the number of cases and the means of their columns.
add_scdb For cases of the Supreme Court, the coding of the Supreme Court Database, such as scdb_issueArea, scdb_decisionDirection, and scdb_partyWinning.
cases_to_dockets, dockets_to_cases, dockets_to_votes Dockets: a row for each docket number of each case, as records kept by docket need, and Cases or Votes (a row for each judge on each docket) made from them.
add_idb For cases of the courts of appeals (best added to Dockets, so each docket of a consolidated case gets its own record), the record of the appeal in the Federal Judicial Center's Integrated Database, which fjc-idb reads, such as idb_appeal_type, idb_judgment_date, idb_pro_se_party, and idb_district_judge (and, if asked, the district court's record of the case appealed).

compare_with_idb (an explorer) checks a study against the Integrated Database. It compares the study's cases as Dockets, since the database has a record for each docket. One table shows how often the variables both have (such as whether an appeal is criminal, was reversed, or was published) agree, with the disagreements in each direction and Cohen's kappa. A second table compares the database's appeals that the study lacks with those it has, by circuit or district, with a test of each difference. A study never has every appeal, so what matters is whether the missing ones differ, such as in how often they were reversed. idb_confusion_matrices and idb_missing_differences draw the two tables.

courtpy downloads the scores and the databases from their sources the first time they are needed. To study one of these tables by itself (such as each justice's vote in each case), start with its loader instead: load_roster, load_scdb, load_idb, or load_politics, or their "download_" twins (download_biographies, download_scdb, download_idb, download_politics, and download_jcs), which download the latest files first. See examples/cases_to_votes.ini for a study of judges' votes.

Describing a whole study in one file

A study is an amos project, described in one settings file. courtpy adds loaders to amos: load_court_listener, load_lexis_nexis, and load_cases. Named first in the wrangler, a loader collects the cases (downloading them, if asked), parses them, and codes them, so the project needs no other data. See examples/federal_appeals.ini:

[general]
seed = 43
label = outcome_reversal

[files]
input_folder = data
interim_folder = data

[appeals_project]
appeals_workers = wrangler, analyst, critic

[wrangler]
techniques = load_court_listener, filter_rows, keep_columns, drop_missing

[load_court_listener_parameters]
source = courtlistener
download = bulk
courts = federal_circuits
start_date = 2019-01-01
end_date = 2019-12-31
save = cases.csv
reuse = true

[analyst]
design = experiment
criterion = roc_auc
steps = split, model
split_techniques = stratified
model_techniques = baseline, logit, random_forest

[critic]
techniques = scorecard

The loader finds (and saves) the cases in the input folder ("data") and saves the coded table in the interim folder, with the whole dataset beside it ("cases.joblib"). With reuse = true, later runs load that dataset instead of parsing the cases again.

Run it from a terminal with courtpy run federal_appeals.ini --export, or in Python:

project = courtpy.Project.create("federal_appeals.ini")
print(project.result.tables["scorecard"])
project.export()

courtpy.Project is amos.Project, so everything in the amos documentation works.

Commands

Command Does
courtpy key set, show, delete Manages your CourtListener API key.
courtpy download bulk --courts ca1 --start 2019-01-01 --end 2019-12-31 Extracts cases from the bulk data.
courtpy download api --courts ca1 --start 2026-09-01 Downloads cases with the API.
courtpy download bulk --help Lists the options of one way to download.
courtpy split FILES --folder lexis_nexis Divides Lexis-Nexis files of many cases.
courtpy parse FOLDER --output cases.csv Parses and codes saved cases into a table.
courtpy rules my_rules.csv Checks a file of rules and lists the variables it makes.
courtpy run study.ini --export Runs a whole study.
courtpy judges Makes the roster of judges from the Federal Judicial Center's files.

Add --help to any command for its options. See the documentation for a tutorial, the advanced user guide, a guide to writing rules, a guide to building a study on courtpy, a catalog of its techniques and variables, and recipes.

Contributing

Contributors are always welcome. Feel free to grab an issue to work on or make a suggested improvement. If you wish to contribute, please read the Contribution Guide and Code of Conduct.

Similar Projects

  • CourtListener and the Free Law Project's tools, including eyecite (which finds and resolves legal citations in text) and juriscraper (which collects opinions from court websites).
  • amos, which courtpy uses to analyze the cases it parses.

Citation

If you use courtpy in your research, please cite it. GitHub's "Cite this repository" button reads the same information from CITATION.cff.

@software{yung_courtpy,
  author  = {Yung, Corey Rayburn},
  title   = {courtpy: Accessible tools for collecting, parsing, and analyzing court opinions},
  version = {0.5.0},
  year    = {2026},
  url     = {https://github.com/WithPrecedent/courtpy},
  license = {Apache-2.0}
}

License

Use of this repository is authorized under the Apache Software License 2.0.

Metadata

Release files for courtpy 0.5.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for courtpy 0.5.1
File Size Uploaded Provenance Actions
courtpy-0.5.1.tar.gz 306.9 kB Without provenance Details for courtpy-0.5.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for courtpy 0.5.1
File Interpreter ABI Platform Actions
courtpy-0.5.1-py3-none-any.whl Python 3 none any Details for courtpy-0.5.1-py3-none-any.whl

Total release size: 549.2 kB

Release files / courtpy-0.5.1.tar.gz

Download URL courtpy-0.5.1.tar.gz
Size 306.9 kB
Tags Source
SHA-256 checksum
How to use checksums
c8df3a5580389c93e5b1975b5819d12a59566f3038070940c8e1be926c616cef
BLAKE2b-256 checksum
How to use checksums
719c6e9adc02da54c5cedc01ef563b47fef87eebc91dcddd870e625a5e0b1368
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / courtpy-0.5.1-py3-none-any.whl

Download URL courtpy-0.5.1-py3-none-any.whl
Size 242.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d7d706d2fa32926e5d42e1f0d98a9623bd66be6badee66e0a9c835449c5609ee
BLAKE2b-256 checksum
How to use checksums
28aa017c8fb7e5a020ef86c16dea3eaa20143f39746d7391bdd4787805177e51
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for courtpy 0.5.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page