Skip to content

Add an SEC index download/update API corresponding to era_py #35

Open

Description

@iangow

Motivation

Provide a supported farr API for downloading and updating SEC quarterly company indexes, corresponding to the functionality in era_py/src/era_pl/sec.py. This would let the R and Python books use the same Parquet format and vintage convention.

farr currently has an unexported preparation script, but no exported SEC-index API. The R book implements downloads and a separate modification-time log in glms.qmd. Its ordinary Parquet writes do not attach vintage metadata, and its update sequence can advance the log despite a failed download.

Related: iangow/far_book#77. This issue proposes package functionality, not a general refresh of the book's data.

Existing Python interface

The current era_pl.sec module provides:

  • sec_get_index(year, quarter, overwrite=False, data_dir=None, schema="edgar", user_agent=None, last_modified=None): reuse an existing file unless overwrite is requested; otherwise download, parse and write it. Returns a Polars LazyFrame, or None for a non-200 download response.
  • sec_index_available_update(year, quarter, user_agent=None): obtain the timestamp of company.gz from the SEC directory listing.
  • sec_parquet_last_modified(path): read the embedded timestamp.
  • sec_index_local(data_dir=None, schema="edgar"): list local year/quarter/timestamp values.
  • sec_index_targets(): enumerate quarters from 1993 Q1 through the quarter containing yesterday.
  • sec_index_update(year, quarter, data_dir=None, schema="edgar", user_agent=None, last_modified=None, report="all").
  • sec_index_update_all(data_dir=None, schema="edgar", user_agent=None, report="update").

The updater redownloads if the file or its timestamp is missing, or if the SEC timestamp is newer. It does not merely stamp an old file with the current remote timestamp. Existing-file reuse by sec_get_index(overwrite=False) is intentionally different from this update check.

Possible R interface

Use the same names and principal arguments, with R defaults/conventions:

sec_get_index(year, quarter, overwrite = FALSE,
              data_dir = Sys.getenv("DATA_DIR"), schema = "edgar",
              user_agent = NULL, last_modified = NULL)

sec_index_available_update(year, quarter, user_agent = NULL)
sec_parquet_last_modified(path)
sec_index_local(data_dir = Sys.getenv("DATA_DIR"), schema = "edgar")
sec_index_targets()

sec_index_update(year, quarter,
                 data_dir = Sys.getenv("DATA_DIR"), schema = "edgar",
                 user_agent = NULL, last_modified = NULL,
                 report = "all")

sec_index_update_all(data_dir = Sys.getenv("DATA_DIR"), schema = "edgar",
                     user_agent = NULL, report = "update")

Resolve an explicit user-agent first, then documented R configuration (e.g., getOption("HTTPUserAgent") and/or USER_AGENT); fail clearly if absent. Do not hard-code personal contact details.

An R-friendly return design would separate acquisition from database connection management: download/update functions return a status record including the file path, while the existing farr::load_parquet() supplies a lazy dbplyr table. This is a proposed adaptation, not literal return-type parity with Python:

result <- farr::sec_get_index(2022, 2)
index <- farr::load_parquet(
  conn, "sec_index_2022q2", schema = "edgar"
)

local <- farr::sec_index_local()
result <- farr::sec_index_update(2022, 2, report = "update")

Alternatively, a convenience reader could return a lazy table given an explicit connection. Decide the return contract before implementation; avoid creating an implicit persistent DuckDB connection.

Data and vintage interoperability

  • Source: https://www.sec.gov/Archives/edgar/full-index/{year}/QTR{quarter}/company.gz.
  • Location: data_dir/schema/sec_index_{year}q{quarter}.parquet.
  • Columns: company_name, form_type, cik (32-bit integer), date_filed (date), and file_name.
  • Store the timezone-aware SEC source timestamp as UTF-8 ISO-8601 text under Parquet schema metadata key last_modified, readable by both implementations. Preserve other metadata.
  • Interpret SEC directory-listing times in America/New_York; compare instants correctly across daylight-saving changes. Do not substitute filesystem mtime or download time for source vintage.
  • Preserve compatibility with existing files lacking metadata and with both Arrow string representations. A checksum identifies an exact file but does not establish its vintage.

Safety improvements to consider

These go beyond the current Python implementation and could subsequently be shared back to era_py:

  • Download and parse into a staging file, validate schema/content and metadata, then replace atomically where supported.
  • Preserve the prior file using the existing db2pq archive facilities, with collision protection and an explicit policy for unknown vintage.
  • Distinguish unchanged, downloaded/updated, and failed in results. Python currently returns a Boolean from sec_index_update(), so failure and no update can both be false.
  • Never advance provenance on failure or damage the last valid file. Detect a source timestamp change during retrieval rather than attaching an unverified timestamp.
  • Validate year/quarter and destination paths; use bounded retries and SEC-compliant request pacing.
  • Keep update operations explicit, rather than refreshing a research snapshot as a side effect of rendering a chapter.

Tests and adoption

Use small offline gzip/HTML/Parquet fixtures and mocked HTTP responses for routine tests:

  • R/Python parser parity, including fixed-width boundaries, both date formats, non-ASCII names and blank lines.
  • Bidirectional metadata round trips and missing/malformed metadata.
  • Existing-file reuse, equal/newer/older timestamps, missing files and missing vintage.
  • HTTP, parsing and write failures preserve original data; archive collisions cannot overwrite prior history.
  • Batch status reporting, target-quarter boundaries and no accidental recursive reading of archives.
  • Read resulting files with farr::load_parquet() and the Python reader.

After the API is settled, replace duplicated R-book maintenance code with calls to it while retaining instructional parsing examples where useful. Treat the separate Python preparation script's metadata-free writes as a related consistency task, not as behavior to copy.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions