Coverage for src/courtpy/references/politics.py: 98%
154 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
1"""Adds the political context of each case: who held power when it was decided.
3Three mergers (`amos.Merger` techniques, which are added to the `amos`
4library as soon as courtpy is imported) add the ideology of the other
5branches and of the Supreme Court on the day each case was decided. Each
6matches the case's date to a table of date ranges with the `merge_ranges`
7technique of `amos`, so another table with the same columns (such as the
8governors of a state) can be its "source":
10| Technique | Adds | Table |
11| --- | --- | --- |
12| `add_executive` | `executive_name` and `executive_ideology` (the president's party: -1 for Democratic and 1 for Republican). | `executives`: each president's term, from "instructions/federal/presidents.csv". |
13| `add_legislature` | `senate_ideology` and `house_ideology`: the median DW-NOMINATE score of the members of each chamber of the Congress then sitting. Higher scores are more conservative. | `legislatures`: each Congress, from the file of members' ideology of https://voteview.com/data. |
14| `add_high_court` | `high_court_ideology`: the Martin-Quinn score of the median justice in the term of the Supreme Court then sitting (from October to September). Higher scores are more conservative. | `high_courts`: each term, from the "justices" file of https://mqscores.wustl.edu/measures.php. |
16Each takes "date" (the column with the date each case was decided, which is
17"date_filed" unless another is set) and the parameters of every merger of
18`amos` ("source", "columns", "prefix", and "indicator").
20The sources' current files are downloaded by the judicial-common-space
21package when they are first needed (see `download`), and kept outside of
22projects (in "politics" in `courtpy.utilities.data_folder()`), where it and
23fjc-biographies look for them too.
25`build_table` makes a table of the political context of each year, with
26the columns of `presidents` ("president_party"), `martin_quinn`
27("supreme_court_median", ...), and `nominate` ("senate_median" and
28"house_median"). `load_politics` and `download_politics` (reference loaders,
29see `courtpy.loaders.ReferenceLoader`) start a study of the years
30themselves with a saved table or one that `build_table` makes.
32Contents:
33 AddExecutive: adds the executive in power when each case was decided.
34 AddHighCourt: adds the ideology of the Supreme Court when each case was
35 decided.
36 AddLegislature: adds the ideology of Congress when each case was
37 decided.
38 ByDate: makes a merger add the row of a table of date ranges that has
39 each case's date.
40 DownloadPolitics: downloads the sources of the political context and
41 loads its table.
42 LoadPolitics: loads a table of the political context of each year.
43 build_table: makes a table of the political context of each year.
44 download: downloads the files of Martin-Quinn and NOMINATE scores with
45 judicial-common-space.
46 executives: returns the term of each president.
47 high_courts: returns the Martin-Quinn score of the median justice in
48 each term of the Supreme Court.
49 justices: returns the Martin-Quinn and Judicial Common Space scores of
50 each justice in each term.
51 legislatures: returns the median NOMINATE scores of each chamber in each
52 Congress.
53 martin_quinn: returns the Martin-Quinn scores of the Supreme Court in
54 each year.
55 nominate: returns the median NOMINATE scores of the Senate and the House
56 in each year.
57 presidents: returns the party of the president in each year.
58 _CHAMBERS: the columns that `nominate` makes, by the name of each chamber
59 of Congress in the file of members.
60 _COURT: the columns that `martin_quinn` makes, by the summary of the
61 justices' scores that each is.
62 _FIRST_JANUARY_CONGRESS: the first Congress that met in January (under
63 the Twentieth Amendment).
64 _PRESIDENTS_FILE: the file of the presidents' terms.
65 _SOURCES: the files that `download` gets, by what judicial-common-space
66 calls each.
68"""
70from __future__ import annotations
72import dataclasses
73import pathlib
74from collections.abc import Sequence
75from typing import Any, ClassVar
77import amos
78import judicial_common_space
79import pandas as pd
81from ..core import cases, utilities
82from ..wrangler import loaders
83from . import jcs
85_CHAMBERS: dict[str, str] = {
86 'Senate': 'senate_median', 'House': 'house_median'}
87_COURT: dict[str, str] = {
88 'median': 'supreme_court_median',
89 'min': 'supreme_court_min',
90 'max': 'supreme_court_max'}
91_FIRST_JANUARY_CONGRESS: int = 74
92_PRESIDENTS_FILE: pathlib.Path = (
93 utilities.instructions_folder() / 'federal' / 'presidents.csv')
94_SOURCES: dict[str, str] = {'justices': 'martin_quinn', 'congress': 'congress'}
97class ByDate:
98 """Makes a merger add the row of a table of date ranges with each date.
100 A merger of courtpy subclasses it before `amos.Merger` (as in
101 `class AddExecutive(ByDate, amos.Merger)`). Each row of its table is a
102 range of dates ("start_date" and "end_date"), and each case gets the
103 columns of the row whose range has the case's date, as the
104 `merge_ranges` technique of `amos` finds it. A date on which one range
105 ends and the next begins (such as the day of an inauguration) gets the
106 later row. It is a mixin rather than a base class so that the merger
107 stays a merger in the `amos` library.
109 Attributes:
110 added: the columns of the table that are added unless "columns" names
111 others.
113 """
115 added: ClassVar[tuple[str, ...]]
117 """ Public Methods """
119 def apply(
120 self,
121 item: amos.Dataset,
122 *,
123 source: Any = None,
124 columns: Sequence[str] | str | None = None,
125 date: str = 'date_filed',
126 **kwargs: Any) -> amos.Dataset:
127 """Adds the columns of the row of the table that has each case's date.
129 Args:
130 item: the dataset of cases (or of votes).
131 source: the table of date ranges: a table, or the path of a data
132 file of one, with "start_date" and "end_date". Defaults to
133 `None`, in which case it is `default_table`.
134 columns: the columns of the table to add. Defaults to `None`, for
135 `added`.
136 date: the column of `item` with the date each case was decided.
137 Defaults to "date_filed".
138 **kwargs: other parameters of the merger, such as "prefix" and
139 "indicator".
141 Raises:
142 KeyError: if `item` lacks `date`, or the table lacks a column.
144 Returns:
145 The dataset, with the new columns.
147 """
148 return super().apply( # type: ignore[misc, no-any-return]
149 item,
150 source = self.default_table() if source is None else source,
151 columns = (
152 list(self.added) if columns is None
153 else utilities.listify(columns)),
154 date = date,
155 **kwargs)
157 def default_table(self) -> pd.DataFrame:
158 """Returns the table of date ranges that is used without a "source".
160 Returns:
161 The table, with "start_date", "end_date", and the columns of
162 `added`.
164 Raises:
165 NotImplementedError: unless a subclass writes it.
167 """
168 raise NotImplementedError
170 def match(
171 self,
172 data: pd.DataFrame,
173 other: pd.DataFrame,
174 *,
175 date: str = 'date_filed',
176 **kwargs: Any) -> Any:
177 """Returns the row of the table whose range has each case's date.
179 Args:
180 data: the cases.
181 other: the table of date ranges.
182 date: the column of `data` with the date each case was decided.
183 Defaults to "date_filed".
184 **kwargs: not used.
186 Raises:
187 KeyError: if `data` lacks `date` or `other` lacks "start_date"
188 or "end_date".
190 Returns:
191 The position of the matching row of `other` for each case, or -1
192 if its date is missing or in no range.
194 """
195 name = repr(getattr(self, 'name', type(self).__name__))
196 cases.require_columns(data, [date], name)
197 cases.require_columns(
198 other, ['start_date', 'end_date'], f'the table of {name}')
199 dates = pd.DataFrame({
200 'date': pd.to_datetime(data[date], errors = 'coerce')})
201 ranges = pd.DataFrame({
202 'start_date': pd.to_datetime(other['start_date']),
203 'end_date': pd.to_datetime(other['end_date'])})
204 return amos.mergers.MergeRanges().match(
205 dates, ranges, column = 'date', start = 'start_date',
206 end = 'end_date', duplicates = 'last')
209@dataclasses.dataclass
210class AddExecutive(ByDate, amos.Merger):
211 """Adds the executive in power when each case was decided.
213 Each case gets "executive_name" (the president, such as "Barack Obama")
214 and "executive_ideology" (the president's party: -1 for Democratic and 1
215 for Republican), from the term of the president on the case's date (see
216 `executives`). A case decided on the day of an inauguration gets the new
217 president. Another table of executives (such as a state's governors)
218 with the same columns can be its "source". See `ByDate` for its
219 parameters.
221 """
223 added: ClassVar[tuple[str, ...]] = (
224 'executive_name', 'executive_ideology')
226 def default_table(self) -> pd.DataFrame:
227 """Returns the term of each president.
229 Returns:
230 The table of `executives`.
232 """
233 return executives()
236@dataclasses.dataclass
237class AddLegislature(ByDate, amos.Merger):
238 """Adds the ideology of Congress when each case was decided.
240 Each case gets "senate_ideology" and "house_ideology": the median
241 DW-NOMINATE score (the first dimension, on which higher scores are more
242 conservative) of the members of each chamber of the Congress that was
243 sitting on the case's date (see `legislatures`). The file of members'
244 ideology is downloaded the first time it is needed. Another table of
245 legislatures (such as a state's) with the same columns can be its
246 "source". See `ByDate` for its parameters.
248 """
250 added: ClassVar[tuple[str, ...]] = ('senate_ideology', 'house_ideology')
252 def default_table(self) -> pd.DataFrame:
253 """Returns the median scores of each chamber in each Congress.
255 Returns:
256 The table of `legislatures`.
258 """
259 return legislatures()
262@dataclasses.dataclass
263class AddHighCourt(ByDate, amos.Merger):
264 """Adds the ideology of the Supreme Court when each case was decided.
266 Each case gets "high_court_ideology": the Martin-Quinn score of the
267 median justice (higher is more conservative) in the term of the Supreme
268 Court that was sitting on the case's date, from October 1 to September
269 30 (see `high_courts`). The file of Martin-Quinn scores is downloaded the
270 first time it is needed. Another table of high courts (such as a state's
271 supreme court) with the same columns can be its "source". See `ByDate`
272 for its parameters.
274 """
276 added: ClassVar[tuple[str, ...]] = ('high_court_ideology',)
278 def default_table(self) -> pd.DataFrame:
279 """Returns the Martin-Quinn score of the median justice in each term.
281 Returns:
282 The table of `high_courts`.
284 """
285 return high_courts()
288@dataclasses.dataclass
289class LoadPolitics(loaders.ReferenceLoader):
290 """Loads a table of the political context of each year.
292 The table starts a study of the years themselves. Its "source" is the
293 path of a saved table of years (in any format that the clerk knows).
294 Without one, the table is made from the sources' current files (see
295 `build_table`), which are downloaded first if they are missing, and
296 "supreme_court", "congress", "score", and "common_space" are passed to
297 `build_table`. To add the political context to parsed cases, use
298 `add_executive`, `add_legislature`, and `add_high_court` instead.
300 """
302 """ Public Methods """
304 def load(
305 self,
306 source: Any,
307 *,
308 supreme_court: bool | pathlib.Path | str | None = None,
309 congress: bool | pathlib.Path | str | None = None,
310 score: str = 'nominate_dim1',
311 common_space: bool | pathlib.Path | str = False,
312 **kwargs: Any) -> Any:
313 """Returns the table of years.
315 Args:
316 source: the path of a saved table of years, or "current" to make
317 the table from the sources' current files.
318 supreme_court: the file of the justices' Martin-Quinn scores, or
319 "false" to leave them out (see `build_table`). Defaults to
320 `None`, for the current file.
321 congress: the file of the ideology of every member of Congress,
322 or "false" to leave it out. Defaults to `None`, for the
323 current file.
324 score: the column of the file of Congress with the score to use.
325 Defaults to "nominate_dim1".
326 common_space: the file of Judicial Common Space medians, or
327 "true" for the current file. Defaults to `False`, which
328 leaves them out.
329 **kwargs: parameters for `read`, for a saved table.
331 Returns:
332 The table, with a "year" column.
334 """
335 path = self._locate(source)
336 if path is not None:
337 return self.read(path, **kwargs)
338 common = self._choose(common_space)
339 return build_table(
340 self._choose(supreme_court),
341 self._choose(congress),
342 score = score,
343 common_space = False if common is None else common)
346@dataclasses.dataclass
347class DownloadPolitics(loaders.ReferenceLoader):
348 """Downloads the sources of the political context and loads its table.
350 The files of Martin-Quinn and NOMINATE scores (and, with "common_space",
351 of Judicial Common Space medians) are downloaded unless they are there
352 already, or "refresh" is true (see `download` and
353 `courtpy.jcs.download`). Then the table of years is made from them (see
354 `build_table`). Its "source" is the data folder whose "politics" (and
355 "jcs") folder keeps the files, which is
356 `courtpy.utilities.data_folder()` unless another is set.
358 """
360 """ Public Methods """
362 def load(
363 self,
364 source: Any,
365 *,
366 supreme_court: bool | str = True,
367 congress: bool | str = True,
368 score: str = 'nominate_dim1',
369 common_space: bool | str = False,
370 refresh: bool | str = False,
371 session: Any = None,
372 **kwargs: Any) -> pd.DataFrame:
373 """Downloads the sources' files and returns the table of years.
375 Args:
376 source: the data folder, or "current" for
377 `utilities.data_folder()`.
378 supreme_court: whether to download and add the Martin-Quinn
379 scores of the Supreme Court. Defaults to `True`.
380 congress: whether to download and add the NOMINATE scores of
381 Congress. Defaults to `True`.
382 score: the column of the file of Congress with the score to use.
383 Defaults to "nominate_dim1".
384 common_space: whether to download and add the Judicial Common
385 Space medians. Defaults to `False`.
386 refresh: whether to download the files even if they are there.
387 Defaults to `False`.
388 session: an object with a `get` method like a
389 `requests.Session`. Defaults to `None`, in which case one is
390 made.
391 **kwargs: not used.
393 Returns:
394 The table, with a "year" column (see `build_table`).
396 """
397 folder = self._locate(source)
398 overwrite = utilities.to_bool(refresh)
399 chosen = {
400 'justices': utilities.to_bool(supreme_court),
401 'congress': utilities.to_bool(congress)}
402 wanted = [kind for kind, use in chosen.items() if use]
403 paths: dict[str, Any] = download(
404 folder, kinds = wanted, overwrite = overwrite,
405 session = session) if wanted else {}
406 medians: pathlib.Path | bool = False
407 if utilities.to_bool(common_space): 407 ↛ 408line 407 didn't jump to line 408 because the condition on line 407 was never true
408 medians = jcs.download(
409 folder, kinds = 'medians', overwrite = overwrite,
410 session = session)['medians']
411 return build_table(
412 paths.get('justices', False),
413 paths.get('congress', False),
414 score = score,
415 common_space = medians)
418def build_table(
419 supreme_court: pd.DataFrame | pathlib.Path | str | bool | None = None,
420 congress: pd.DataFrame | pathlib.Path | str | bool | None = None,
421 *,
422 score: str = 'nominate_dim1',
423 common_space: pd.DataFrame | pathlib.Path | str | bool = False) -> (
424 pd.DataFrame):
425 """Makes a table of the political context of each year.
427 Args:
428 supreme_court: the file of the justices' Martin-Quinn scores in each
429 term (see `martin_quinn`). Defaults to `None`, in which case the
430 current file is used, which is downloaded unless it was before
431 (see `download`). `False` leaves the court's scores out of the
432 table.
433 congress: the file of the ideology of every member of Congress (see
434 `nominate`). Defaults to `None`, in which case the current file
435 is used, which is downloaded unless it was before. `False`
436 leaves the scores of Congress out of the table.
437 score: the column of `congress` with the score to use. Defaults to
438 "nominate_dim1".
439 common_space: the file of Judicial Common Space medians (see
440 `courtpy.jcs.medians`). Defaults to `False`, which leaves them out
441 of the table. `True` uses the current file, which is downloaded
442 unless it was before.
444 Returns:
445 A table with a "year" column and the columns of `presidents`,
446 `martin_quinn`, `nominate`, and (with `common_space`)
447 `courtpy.jcs.medians`, for every year that any of them has. A
448 year that a source lacks has missing values for it.
450 """
451 tables = [presidents()]
452 if supreme_court is not False:
453 tables.append(martin_quinn(
454 None if supreme_court is True else supreme_court))
455 if congress is not False:
456 tables.append(nominate(
457 None if congress is True else congress, score = score))
458 if common_space is not False:
459 tables.append(jcs.medians(
460 None if common_space is True else common_space))
461 years = sorted(set().union(*(table['year'].tolist() for table in tables)))
462 context = amos.Dataset(pd.DataFrame({'year': years}))
463 merger = amos.mergers.MergeKeys()
464 for table in tables:
465 merger.apply(context, source = table, on = 'year')
466 return context.data
469def download(
470 folder: pathlib.Path | str | None = None,
471 *,
472 kinds: Sequence[str] | str | None = None,
473 overwrite: bool = False,
474 session: Any = None) -> dict[str, pathlib.Path]:
475 """Downloads the files of Martin-Quinn and NOMINATE scores.
477 | Kind | File | Source |
478 | --- | --- | --- |
479 | `justices` | "justices.csv": the Martin-Quinn score of each justice in each term. | https://mqscores.wustl.edu/measures.php |
480 | `congress` | "HSall_members.csv": the ideology of every member of every Congress (about 6 megabytes). | https://voteview.com/data (its "Member Ideology" data for both chambers and all Congresses) |
482 `judicial_common_space.sources.download` downloads them, into the
483 "politics" folder of `folder`, where it and fjc-biographies look for the
484 files too, so courtpy and those packages share them. The Martin-Quinn
485 scores are released each year, in a folder named for the year, so their
486 file is found by its link on the page. The page is behind a check for
487 automated browsers, which can refuse the download. Then save
488 "justices.csv" from the page in a browser and put it in the "politics"
489 folder (or pass its path to `justices` and `martin_quinn`).
491 Args:
492 folder: the data folder, whose "politics" folder they are saved in.
493 Defaults to `None`, in which case `utilities.data_folder()` is
494 used.
495 kinds: the files to download: "justices", "congress", or both.
496 Defaults to `None`, for both.
497 overwrite: whether to download a file that is already there. The
498 scores change as justices and members vote. Defaults to `False`.
499 session: an object with a `get` method like a `requests.Session`.
500 Defaults to `None`, in which case a `requests.Session` that
501 identifies courtpy is made.
503 Raises:
504 requests.HTTPError: if a page or a file cannot be downloaded.
505 ValueError: if one of `kinds` is not a file that courtpy knows, or
506 the page of Martin-Quinn scores has no link to its file.
508 Returns:
509 The path of each file, by its kind.
511 """
512 wanted = list(_SOURCES) if kinds is None else utilities.listify(kinds)
513 unknown = [kind for kind in wanted if kind not in _SOURCES]
514 if unknown:
515 message = f'kinds must be among {list(_SOURCES)}, not {unknown}'
516 raise ValueError(message)
517 paths = judicial_common_space.sources.download(
518 [_SOURCES[kind] for kind in wanted],
519 folder or utilities.data_folder(),
520 overwrite = overwrite,
521 session = utilities.open_session(session))
522 return {kind: paths[_SOURCES[kind]] for kind in wanted}
525def justices(
526 source: pd.DataFrame | pathlib.Path | str | None = None) -> pd.DataFrame:
527 """Returns the Martin-Quinn and Common Space scores of each justice.
529 `judicial_common_space.politics.justices` reads the scores and puts each
530 Martin-Quinn score on the scale of the Judicial Common Space. The
531 justices have the numbers that the Supreme Court Database gives them, so
532 the scores can be added to its votes (see `courtpy.scdb.votes`) with the
533 `merge_keys` technique of `amos`, by "term" and "justice".
535 Args:
536 source: the "justices" file of the Martin-Quinn scores (from
537 https://mqscores.wustl.edu/measures.php), as a path or a table.
538 It has a row for each justice in each term, with the columns
539 "term", "justice", "justiceName", and "post_mn". Defaults to
540 `None`, in which case the current file is used, which is
541 downloaded unless it was before (see `download`).
543 Raises:
544 KeyError: if `source` lacks a column that is needed.
546 Returns:
547 A table with "term" (the year in which the term began, in October),
548 "justice" and "justiceName" (the Supreme Court Database's number
549 and name for the justice, such as 117 and "ACBarrett"),
550 "martin_quinn" (the mean of the estimates of the justice's
551 score), and "jcs" (the score on the scale of the Judicial Common
552 Space).
554 """
555 scores: pd.DataFrame = judicial_common_space.politics.justices(
556 _read(source, 'justices'))
557 return scores
560def martin_quinn(
561 source: pd.DataFrame | pathlib.Path | str | None = None) -> pd.DataFrame:
562 """Returns the Martin-Quinn scores of the Supreme Court in each year.
564 The scores are summaries of the scores of the justices who served in
565 each term (see `justices`): their median and the lowest and highest of
566 them. A term in which a justice was replaced (such as 2005, when Samuel
567 Alito replaced Sandra Day O'Connor) has the scores of both.
569 Args:
570 source: the "justices" file of the Martin-Quinn scores (see
571 `justices`), as a path or a table. Defaults to `None`, in which
572 case the current file is used, which is downloaded unless it was
573 before (see `download`).
575 Raises:
576 KeyError: if `source` lacks a column that is needed.
578 Returns:
579 A table with "year" (the year in which the term began, in October),
580 "supreme_court_median", "supreme_court_min", and
581 "supreme_court_max".
583 """
584 scores = justices(source).dropna(subset = ['term', 'martin_quinn'])
585 summaries = scores.groupby('term')['martin_quinn'].agg(list(_COURT))
586 table = summaries.rename(columns = _COURT).rename_axis('year')
587 return table.reset_index().astype({'year': int})
590def nominate(
591 source: pd.DataFrame | pathlib.Path | str | None = None,
592 *,
593 score: str = 'nominate_dim1') -> pd.DataFrame:
594 """Returns the median NOMINATE scores of the Senate and House in each year.
596 Args:
597 source: the file of the ideology of every member of every Congress
598 ("HSall_members.csv", which https://voteview.com/data offers as
599 its "Member Ideology" data), as a path or a table. It has a row
600 for each member of each Congress, with the columns "congress"
601 and "chamber" and a column for each score. Defaults to `None`,
602 in which case the current file is used, which is downloaded
603 unless it was before (see `download`).
604 score: the column with the score to use: "nominate_dim1" (the
605 default, the first dimension of DW-NOMINATE, on which higher
606 scores are more conservative), "nominate_dim2",
607 "nokken_poole_dim1", or "nokken_poole_dim2".
609 Raises:
610 KeyError: if `source` lacks a column that is needed.
612 Returns:
613 A table with "year", "senate_median", and "house_median". A Congress
614 sits for two years (the 97th sat in 1981 and 1982), so both have
615 its medians.
617 """
618 medians = _chamber_medians(source, score)
619 # The first Congress met in 1789, and each sits for two years.
620 first = medians.index.to_numpy() * 2 + 1787
621 years = pd.concat([
622 medians.assign(year = first), medians.assign(year = first + 1)])
623 years = years.sort_values('year').reset_index(drop = True)
624 years.columns.name = None
625 return years[['year', *_CHAMBERS.values()]]
628def presidents(start: int | None = None, end: int | None = None) -> (
629 pd.DataFrame):
630 """Returns the party of the president in each year.
632 The president of a year is the one in office at its end, so a president
633 who takes office in a year (in January) is the president of that year.
634 The terms are in "instructions/federal/presidents.csv" (see
635 `executives`), where a president can be added.
637 Args:
638 start: the first year. Defaults to `None`, in which case it is the
639 first year that courtpy knows the party of (1933).
640 end: the last year. Defaults to `None`, in which case it is the last
641 year that courtpy knows the party of, the last of the latest
642 president's term.
644 Raises:
645 ValueError: if `start` or `end` is a year that courtpy does not know
646 the party of the president in.
648 Returns:
649 A table with "year" and "president_party" (-1 for Democratic and 1
650 for Republican).
652 """
653 terms = executives()
654 starts = pd.to_datetime(terms['start_date'])
655 ends = pd.to_datetime(terms['end_date'])
656 earliest = int(starts.min().year)
657 # The last term ends during its last year, so the year before is the
658 # last that a president is in office at the end of.
659 latest = int(ends.max().year) - 1
660 start = earliest if start is None else start
661 end = latest if end is None else end
662 if start < earliest or end > latest:
663 message = (
664 f'courtpy knows the party of the president from {earliest} to '
665 f'{latest}, not from {start} to {end}'
666 )
667 raise ValueError(message)
668 years = list(range(start, end + 1))
669 last_day = pd.to_datetime([f'{year}-12-31' for year in years])
670 chosen = starts.searchsorted(last_day, side = 'right') - 1
671 parties = terms['executive_ideology'].astype('Int64').to_numpy()[chosen]
672 return pd.DataFrame({
673 'year': years,
674 'president_party': pd.array(parties, dtype = 'Int64')})
677def executives(source: pathlib.Path | str | None = None) -> pd.DataFrame:
678 """Returns the term of each president.
680 Args:
681 source: a CSV file of terms, with "president", "party", "start_date",
682 and "end_date". Defaults to `None`, for
683 "instructions/federal/presidents.csv".
685 Raises:
686 KeyError: if `source` lacks a column that is needed.
688 Returns:
689 A table with "executive_name" (the president), "executive_ideology"
690 (the president's party: -1 for Democratic and 1 for Republican),
691 "start_date", and "end_date" (the days the term began and ended,
692 as dates), sorted by the start of the terms.
694 """
695 terms = utilities.read_csv(source or _PRESIDENTS_FILE)
696 cases.require_columns(
697 terms, ['president', 'party', 'start_date', 'end_date'],
698 'the table of presidents')
699 table = pd.DataFrame({
700 'executive_name': terms['president'].astype(str),
701 'executive_ideology': pd.to_numeric(
702 terms['party'], errors = 'coerce').astype('Int64'),
703 'start_date': pd.to_datetime(terms['start_date']),
704 'end_date': pd.to_datetime(terms['end_date'])})
705 return table.sort_values('start_date').reset_index(drop = True)
708def high_courts(
709 source: pd.DataFrame | pathlib.Path | str | None = None) -> pd.DataFrame:
710 """Returns the Martin-Quinn score of the median justice in each term.
712 Args:
713 source: the "justices" file of the Martin-Quinn scores (see
714 `justices`), as a path or a table. Defaults to `None`, in which
715 case the current file is used, which is downloaded unless it was
716 before (see `download`).
718 Raises:
719 KeyError: if `source` lacks a column that is needed.
721 Returns:
722 A table with "term" (the year in which the term began),
723 "start_date" (October 1 of that year), "end_date" (September 30
724 of the next), and "high_court_ideology" (the score of the median
725 justice; see `martin_quinn`).
727 """
728 terms = martin_quinn(source)
729 years = terms['year'].astype(int)
730 return pd.DataFrame({
731 'term': years,
732 'start_date': pd.to_datetime(years.astype(str) + '-10-01'),
733 'end_date': pd.to_datetime((years + 1).astype(str) + '-09-30'),
734 'high_court_ideology': terms['supreme_court_median'].to_numpy()})
737def legislatures(
738 source: pd.DataFrame | pathlib.Path | str | None = None,
739 *,
740 score: str = 'nominate_dim1') -> pd.DataFrame:
741 """Returns the median NOMINATE scores of each chamber in each Congress.
743 Args:
744 source: the file of the ideology of every member of every Congress
745 (see `nominate`), as a path or a table. Defaults to `None`, in
746 which case the current file is used, which is downloaded unless
747 it was before (see `download`).
748 score: the column with the score to use. Defaults to "nominate_dim1"
749 (see `nominate`).
751 Raises:
752 KeyError: if `source` lacks a column that is needed.
754 Returns:
755 A table with "congress" (its number), "start_date" and "end_date"
756 (the day it first met and the day the next one did: January 3
757 since the 74th, in 1935, and March 4 before), and
758 "senate_ideology" and "house_ideology" (the median score of the
759 members of each chamber).
761 """
762 medians = _chamber_medians(source, score)
763 numbers = medians.index.to_numpy()
764 starts = pd.to_datetime([_first_day(number) for number in numbers])
765 ends = pd.to_datetime([_first_day(number + 1) for number in numbers])
766 return pd.DataFrame({
767 'congress': numbers,
768 'start_date': starts,
769 'end_date': ends,
770 'senate_ideology': medians['senate_median'].to_numpy(),
771 'house_ideology': medians['house_median'].to_numpy()})
774""" Private Functions """
777def _read(
778 source: pd.DataFrame | pathlib.Path | str | None,
779 kind: str) -> pd.DataFrame:
780 """Returns a table from a table or a CSV file, or one of the sources'.
782 Args:
783 source: a table (which is copied), the path of a CSV file, or `None`.
784 kind: the file to use if `source` is `None`: "justices" or
785 "congress". It is downloaded unless it was before (see
786 `download`).
788 Returns:
789 The table.
791 """
792 if isinstance(source, pd.DataFrame):
793 return source.copy()
794 if source is None:
795 source = download(kinds = kind)[kind]
796 return utilities.read_csv(source)
799def _chamber_medians(
800 source: pd.DataFrame | pathlib.Path | str | None,
801 score: str) -> pd.DataFrame:
802 """Returns the median score of each chamber of each Congress.
804 Args:
805 source: the file of the ideology of every member of every Congress,
806 as a path or a table, or `None` for the current file.
807 score: the column with the score to use.
809 Raises:
810 KeyError: if `source` lacks a column that is needed.
812 Returns:
813 A table labeled by the number of each Congress, with
814 "senate_median" and "house_median".
816 """
817 members = _read(source, 'congress')
818 cases.require_columns(
819 members, ['congress', 'chamber', score],
820 'the file of the ideology of members of Congress')
821 members = members[members['chamber'].isin(list(_CHAMBERS))]
822 medians = members.assign(
823 congress = members['congress'].astype(int),
824 score = pd.to_numeric(members[score], errors = 'coerce')).pivot_table(
825 index = 'congress', columns = 'chamber', values = 'score',
826 aggfunc = 'median')
827 medians = medians.reindex(columns = list(_CHAMBERS)).rename(
828 columns = _CHAMBERS)
829 medians.columns.name = None
830 return medians
833def _first_day(congress: int) -> str:
834 """Returns the day a Congress first met, as the Constitution set it.
836 Args:
837 congress: the number of the Congress.
839 Returns:
840 The date, as "YYYY-MM-DD": January 3 of its first year since the
841 74th Congress (under the Twentieth Amendment), and March 4
842 before.
844 """
845 year = congress * 2 + 1787
846 day = '01-03' if congress >= _FIRST_JANUARY_CONGRESS else '03-04'
847 return f'{year}-{day}'