API and CLI¶
How the REST API and the
manage.pycommands fit together — base paths, auth, async jobs and caching flags — with links to the generated route and command reference.
The route and command tables themselves are generated from the source, so they cannot drift from it:
- reference/api-routes.md — every route: method, path, view, access rule, the parameters the handler reads, and its summary.
- reference/management-commands.md — every management command, grouped by app, with its help text and options.
Regenerate both with python3 tools/gen_reference.py --write after changing a route, a view docstring or a command; tests/test_docs_reference.py fails while they are stale. The summaries come from the view and command docstrings and help strings, so improve those rather than the generated files.
REST API¶
- Base path:
/api/v1/is canonical./api/is a legacy alias that includes the same URLconf (src/api/urls.py); add routes insrc/api/v1/only. - Auth: token and session authentication. Reads are public; writes and every SEC-hitting action need a staff user (
api.permissions.IsAdminOrReadOnly, the DRF default insrc/config/settings.py). - OpenAPI:
drf-spectacularserves the OpenAPI 3 schema at/api/v1/schema/and Swagger UI at/api/v1/docs/. Responses are JSON; the browsable API renderer is added only whenDJANGO_DEBUGis on. - Health probes (UPS-BE-10/11): three root routes outside
/api/, all anonymous, unthrottled and sent withCache-Control: no-store.GET /healthzis liveness and always answers200 {"status":"ok"}without touching a dependency.GET /readyzis readiness: it answers200 {"status":"ok","checks":{"db":"ok","cache":"ok","broker":"ok"}}, or503with"status":"degraded"anderror: <ExceptionClass>under each failed check.brokerpings the Celery Redis broker and reportsskippedwhen tasks run eagerly or the broker is not Redis.GET /versionanswers{"name","version","commit","built_at"}: the version comes from.release-please-manifest.json, and the commit and build time come from theGIT_SHAandBUILT_ATbuild args, orunknownwhen those are not set./api/v1/health/and/api/v1/health/ready/remain aliases of the first two. The imageHEALTHCHECK, the composewebhealthcheck and the UI's readiness dot all poll/readyz, and Vite and nginx proxy all three routes. - Throttling: anonymous and user rates apply everywhere except the health probes (
THROTTLE_ANON,THROTTLE_USER), and the SEC-hitting actions carry the scopedsecrate (THROTTLE_SEC, default20/min). - Async jobs: the sync actions accept
?async=trueand answer202with atask_id; pollGET /api/v1/tasks/{task_id}/for the Celery result (staff only, the same users who can dispatch the job). - SEC caching: reads go DB first and only call SEC when nothing is cached;
?force_refresh=truerefetches on the endpoints whose Params column lists it. See architecture.md. - SEC User-Agent: SEC requires a contact email. The server uses
USER_AGENT_EMAIL; a request may override it with theX-Sec-User-Agent-Emailheader. - Filing text search:
GET /api/v1/filings/search/?q=…searches the text of ingested filing documents (ranked full-text search on Postgres, a case-insensitive substring match elsewhere) and returns at most 50 hits.qmust be at least 2 characters;form_type(for example10-K) andciknarrow the search.ciktakes a bare, zero-padded orCIK-prefixed value (320193,0000320193,CIK0000320193); a value with no digits, or with more than 10 significant digits, is a400with adetailmessage rather than a filter that is quietly dropped. Leavecikout, or empty, to search every company.
The same service functions back the API and the CLI: POST /api/v1/companies/{id}/sync-submissions/ and manage.py sync_submissions both call sync_submissions_for_company.
Company vs macro overlay¶
GET /api/v1/companies/{id}/macro-overlay/ lines a company series up with a stored FRED series over the company's own fiscal periods and reports how the two move together (feature FREDGAR-013, requirement FR-ANL-002). The company page's Macro tab is its UI: a company-series picker, a series picker fed by the series bundles, a dual-axis chart, a correlation badge and CSV export.
- Parameters: exactly one of
metric(a derived-metric key such asgross_margin) orconcept(an XBRL tag, or a comma-separated priority chain such asRevenueFromContractWithCustomerExcludingAssessedTax,Revenues);series(the FRED id, matched case-insensitively);agg=avg|eop(defaultavg);annual=1to keep only full fiscal years;taxonomyandlimitas onanalytics/timeseries/. - Errors: a missing or unknown parameter is a
400whosedetailnames it (an unknownmetricalso lists the known ones). A series with no stored observations is a404. The endpoint is DB-first and never calls FRED or SEC: store the series first withrefresh_series_bundlesorsync_series_bundle. - Response:
rowsof{period_start, period_end, company_value, series_value, series_observations}, oldest first;correlation{method: "pearson", r, n};alignment{window, aggregation, series_step_days, description, dropped}, wheredroppedlists each fiscal period that did not align and why; and thecompany_seriesandseriesmetadata.
How periods are aligned (macro_overlay.py):
- Fiscal windows, not calendar windows. Each company value covers a window. A durational fact covers its own
period_starttoperiod_end. A derived metric takes the window of the longest durational input fact reported for itsperiod_end, the factcompute_derived_metricsresolves. A point-in-time value (an instant fact such asAssets, or a balance-sheet-only metric) covers the span since the previousperiod_endin the series, and the earliest one covers as many days as the window after it. - Observations by date. A series observation belongs to the window its
observation_datefalls in. FRED dates a period by its first day, so a fiscal year from July to June takes the monthly observations dated July 1 through June 1, or the quarterly ones dated July 1 through April 1. A series coarser than the company's periods, such as an annual series against fiscal quarters, aligns only the windows an observation date falls in. - Aggregation.
avgis the mean of the window's observations;eopis the last one. - Partly covered windows are dropped, never padded or interpolated. A window is dropped when an observation dated inside it is missing, wherever it falls. The step is the median spacing of the series' stored observations, and each bound below has three days of slack for weekends, holidays and month lengths. The start bound is a step tighter than the end bound because FRED dates an observation by the first day of its period: a complete series has an observation on the first day of a window that starts on a period boundary, and its last one a period before the end of a window that ends on one.
- At the start: a whole step lies between the window start and its first observation, as when a June fiscal year has no July observation. The reason is
gapwhen the observation stored before the window is more than 1.5 steps before that first one, andseries_starts_latewhen nothing is stored before the window. When the observation before is a normal step away, nothing is missing: the window starts between two observations. - At the end: more than a step lies between the window's last observation and its end. The reason is
gapwhen the observation stored after the window is more than 1.5 steps after it, andseries_ends_earlywhen nothing is stored after the window. - Inside: two consecutive observations in the window are more than 1.5 steps apart, which is a
gap. - Each dropped window is listed in
droppedwith its reason. - Correlation. Pearson r over the aligned pairs;
risnullwhen fewer than three periods align or one side is constant. It correlates levels, so two trending series, such as revenue and nominal GDP, show a high r without moving together period to period.
Management commands¶
Run them from src/ (being there is what puts config and the apps on the path):
cd src
python manage.py <command> [options]
python manage.py help <command> # full argument help, with defaults
The enrichment pipeline (enrich_*) is CLI-only by design: running providers spends SEC and search budget and takes minutes, so it does not belong in a request a browser can retry. The HTTP side only reads its results. See enrichment.md.
publish_static_site is the GitHub Pages build (sync a curated cohort from SEC, then render); see static-site.md. The leadership commands and their caveats are in leadership-methodology.md.
Macro series: FRED transforms and vintages¶
GET /api/v1/series-bundles/{slug}/observations/ and GET /api/v1/public-observations/?series={id} return the stored FRED observations. Four optional query parameters return them transformed the way the FRED API would (FR-MAC-001, transforms.py). Without them, both endpoints answer exactly as before.
| Parameter | Values | Default |
|---|---|---|
units |
lin levels, chg change, ch1 change from a year ago, pch percent change, pc1 percent change from a year ago, pca compounded annual rate of change, cch continuously compounded rate of change, cca continuously compounded annual rate of change, log natural log |
lin |
frequency |
d, w (weekly, ending Friday), m, q, sa, a |
the series' own |
aggregation |
avg, sum, eop (end of period); read only with frequency |
avg |
vintage_date |
YYYY-MM-DD: the series as FRED published it on that day (ALFRED); needs ENABLE_FRED_VINTAGES=true |
none: the stored observations |
- Formulas. The units follow FRED's formulas, where
nis the number of observations per year at the output frequency: daily 260, weekly 52, biweekly 26, monthly 12, quarterly 4, semiannual 2, annual 1. Aggregation runs first, then the units transform. - Lags are by period. x(t-1) is the observation one period earlier at the output frequency: the previous weekday for daily data, or the previous calendar day for a series with weekend observations. When that period is missing, the value is undefined, as FRED's
.is. Undefined values are left out of the response: the first period of a change, a percentage over zero, and the log of a value that is not positive. - Frequency. Aggregation labels each period as FRED does: the first day of the month, quarter, half-year or year, and the Friday that ends the week. A period still in progress aggregates the observations it has so far. FRED's biweekly target (
bw) is not offered, because FRED does not document which Wednesdays anchor its two-week periods. Asking one series for a frequency higher than its own is a400, as in FRED. A bundle mixes frequencies, so there a series of a lower frequency keeps its own, and each entry inseriesreports itsoutput_frequency. - Echo. A transformed response adds
transform, holding the appliedunits,frequency,aggregationandvintage_date. Onpublic-observations,seriesis then required, the rows become{series, observation_date, value}newest first (still paginated), andoutput_frequencysits beside the page. An unknown value is a400with adetail. - Vintages. Off by default. With
ENABLE_FRED_VINTAGES=true, avintage_dateis read fromwarehouse.SeriesVintageObservation, and anyone can read what is stored. When that series and date are not stored yet, a staff user's request fetches them once from FRED, withrealtime_startandrealtime_endset to the vintage date, and stores them: like the SEC sync actions, a FRED call that writes rows needsis_staff. Anyone else gets a403onpublic-observations, and in a bundle that series carries anerrorand no values.python manage.py sync_series_vintage --series GDPC1 --as-of 2020-01-01fetches one ahead of time, which a large bundle wants: the first request for a new date makes one FRED call per series. A series FRED cannot supply is a502onpublic-observations, and anerrorin a bundle. While the flag is off,vintage_dateis a400.
The Macro page offers the same units, frequency and aggregation. Its Index (=100) option rebases the levels in the browser, since the FRED API has no such unit.