finance web server
  • Zig 99.9%
  • Dockerfile 0.1%
Find a file
Emil Lerch 525447ae25
All checks were successful
Generic zig build / build (push) Successful in 5m51s
Generic zig build / deploy (push) Successful in 10s
optional admin refresh endpoint
2026-11-23 14:38:05 -08:00
.forgejo/workflows zig 0.17.1 upgrade 2026-11-23 13:42:55 -08:00
docker mutual fund logic in zfin proper now 2026-03-11 11:47:29 -07:00
src optional admin refresh endpoint 2026-11-23 14:38:05 -08:00
.gitignore upgrade to zig 0.16.0 and latest zfin lib, add /splits 2026-05-20 16:34:16 -07:00
.mise.toml zig 0.17.1 upgrade 2026-11-23 13:42:55 -08:00
.pre-commit-config.yaml add basic structure 2026-03-10 17:29:14 -07:00
build.zig zig 0.17.1 upgrade 2026-11-23 13:42:55 -08:00
build.zig.zon zig 0.17.1 upgrade 2026-11-23 13:42:55 -08:00
GitVersion.zig zig 0.17.1 upgrade 2026-11-23 13:42:55 -08:00
LICENSE add basic structure 2026-03-10 17:29:14 -07:00
README.md optional admin refresh endpoint 2026-11-23 14:38:05 -08:00

zfin-server

HTTP data service backed by zfin's financial data providers. Serves cached market data over HTTP for two consumers:

  1. LibreCalc spreadsheets — trailing returns via WEBSERVICE/FILTERXML
  2. zfin CLI/TUI — raw SRF cache files as an L1 data cache

Quick start

# Set API keys (same as zfin)
export TWELVEDATA_API_KEY=...
export POLYGON_API_KEY=...

# Start the server
zig build run -- serve --port=8080

# In another terminal
curl http://localhost:8080/AAPL/returns
curl http://localhost:8080/AAPL/returns?fmt=xml

Endpoints

Route Content-Type Description
GET / text/html Landing page
GET /help text/plain Endpoint documentation
GET /symbols application/json List of tracked symbols
GET /:symbol/returns application/json Trailing 1/3/5/10yr returns + volatility
GET /:symbol/returns?fmt=xml application/xml Same, XML for LibreCalc
GET /:symbol/watch application/json Add the symbol to the watchlist (authenticated)
GET /:symbol/quote application/json Latest quote
GET /:symbol/candles application/x-srf Raw SRF cache file
PUT /:symbol/candles application/json Publish an external series (publish key)
GET /:symbol/dividends application/x-srf Raw SRF cache file
GET /:symbol/earnings application/x-srf Raw SRF cache file
GET /:symbol/options application/x-srf Raw SRF cache file
GET /:symbol/classification application/x-srf Wikidata classification (SRF)
GET /:symbol/etf_metrics application/x-srf EDGAR NPORT-P fund metrics; 404 for non-funds
GET /:cik/entity_facts application/x-srf EDGAR XBRL entity facts (CIK-keyed)
GET /_edgar/tickers_funds application/x-srf EDGAR mutual-fund ticker map (~3 MB)
GET /_edgar/tickers_companies application/x-srf EDGAR company ticker map (~5 MB)
POST <prefix>/refresh text/plain Streamed full refresh (details)

The SRF endpoints behave as an L2 cache. A present cache file is served as-is (even if stale -- the refresh cron is the freshness authority). On a miss the server fetches once from the upstream provider, fills the cache, and serves the result; it returns 404 only if that fetch also fails. A miss never adds the symbol to the tracked set, so an ad-hoc lookup doesn't create recurring refresh load.

Authentication

/, /help, and /:symbol/returns (the LibreCalc endpoint) are always public. Every other endpoint -- the raw SRF cache files, /quote, /symbols, and the EDGAR ticker maps -- is gated behind a shared key when ZFIN_SERVER_API_KEY is set:

export ZFIN_SERVER_API_KEY=your-secret

# Supply the key as a header (preferred)...
curl -H "X-API-Key: your-secret" http://localhost:8080/AAPL/candles
# ...or as a query parameter (curl convenience)
curl "http://localhost:8080/AAPL/candles?api_key=your-secret"

If ZFIN_SERVER_API_KEY is unset or empty, the server is fully open -- a soft cutover so the key can roll out to clients before enforcement is switched on.

The one exception is PUT /:symbol/candles, which answers to a separate publish key and never to the API key. See below.

Publishing

Some series have no market-data provider at all (a 529 plan's unitized portfolio, say), so the server cannot fetch them. An external publisher hands them over with PUT /:symbol/candles:

export ZFIN_SERVER_PUBLISH_KEY=publisher-secret   # on the server

curl -X PUT -H "X-Publish-Key: publisher-secret" --data-binary @series.srf \
  http://localhost:8080/ORC42/candles

The body is an SRF document with one record per bar, ascending by date, and a required #!expires= directive -- when the series next changes is the publisher's knowledge, so the server does not guess:

#!srfv1
#!expires=1787922000
date::2026-08-26,close:num:16.743025
date::2026-08-27,close:num:16.808106

Each publish replaces the whole series. The server writes candles_daily.srf and candles_meta.srf itself, with open/high/low/adj_close equal to close, volume 0, and provider::external, then reads the result back.

Status Meaning
200 Written; JSON summary (bars, dates, last close)
400 Bad symbol or body; the message names the bar and the problem
401 Missing or wrong X-Publish-Key
403 Publishing not enabled, or the symbol is provider-managed
500 The write could not be read back

A symbol is provider-managed when its cached candles came from a provider. A publisher can never overwrite those.

Unlike the API key there is no soft cutover: with ZFIN_SERVER_PUBLISH_KEY unset, every publish is refused.

Watchlist

Adding a symbol to the watchlist enrolls it in the refresh cron, so it gets fetched on every run from then on -- the one operation that creates recurring provider load. There are two ways in, gated to fit each consumer:

  • GET /:symbol/watch -- authenticated (API key), for your own tooling deliberately growing the tracked set.
  • GET /:symbol/returns?watch=true -- public, but the add only happens when the request carries LibreOffice's WEBSERVICE User-Agent. This lets the non-technical user add symbols from a spreadsheet while keeping random callers from growing the cron set. (Obscurity-grade: a User-Agent is trivially spoofable, which is acceptable under the casual-traffic threat model.)

Adds are serialized and written atomically, and implausible symbols are rejected, so a stray request can't corrupt or balloon portfolio.srf.

LibreCalc usage

=FILTERXML(WEBSERVICE("http://localhost:8080/AAPL/returns?fmt=xml"), "//trailing1YearReturn")

XML response format:

<returns>
  <ticker>AAPL</ticker>
  <returnDate>2026-03-07</returnDate>
  <trailing1YearReturn>12.34000</trailing1YearReturn>
  <trailing3YearReturn>8.56000</trailing3YearReturn>
  <trailing5YearReturn>15.78000</trailing5YearReturn>
  <trailing10YearReturn>22.10000</trailing10YearReturn>
  <volatility>18.50000</volatility>
</returns>

Cache refresh

Use cron to keep the cache warm for all symbols in your portfolio:

# Refresh all portfolio symbols daily at 5pm ET (after market close)
0 17 * * 1-5 cd /path/to/workdir && ZFIN_PORTFOLIO=portfolio.srf zfin-server refresh

The candle cache TTL is 23h45m (not a full 24h), providing a 15-minute jitter buffer so daily cron runs at the same time always see stale data and trigger a fresh fetch. Dividend and earnings TTLs are 14 and 30 days respectively.

The refresh command reads the portfolio SRF file (defaults to portfolio.srf in the current directory if ZFIN_PORTFOLIO is not set), extracts all stock and watch symbols, and fetches candles, dividends, and earnings for each.

Over HTTP

Setting ZFIN_SERVER_ADMIN_PREFIX (e.g. /admin) adds POST <prefix>/refresh, which runs the same refresh as the command above, in the server process, and streams its report as it goes:

curl -N -X POST https://gateway.example/admin/refresh

The server does not authenticate this route. It is meant to sit behind a gateway that authorizes the prefix, which is why it only exists when the variable is set. Only that exact path skips the API key. The prefix must start with /, must not end with one, and cannot be / alone; a bad value stops the server at startup.

  • The response is text/plain, streamed in chunks (curl -N shows it live; a gateway that buffers responses will deliver it all at the end).
  • Streaming commits the status with the first line, so a run that starts is a 200 whatever its outcome. The outcome is the last line: Refresh complete in Ns (exit N: reason) with the same exit codes as the command, or refresh failed: <error> if it stopped partway.
  • 500 if the run fails before printing anything (an unreadable portfolio).
  • 409 if a refresh is already running, including a POST /refresh. A cron-started run is a separate process and is not seen.
  • It uses the server's own provider rate limiter, shared with every other fetch the server makes.
  • If the client disconnects, the run still finishes; only its output is dropped.

Building

Requires Zig 0.17.1.

zig build        # build
zig build test   # run tests
zig build run -- serve --port=8080

Configuration

All configuration is via environment variables:

Variable Required Description
TWELVEDATA_API_KEY Yes TwelveData API key
POLYGON_API_KEY No Polygon API key
FINNHUB_API_KEY No Finnhub API key
ZFIN_USER_EMAIL Yes Contact email for SEC EDGAR User-Agent header
ZFIN_PORTFOLIO No Path to portfolio SRF (default: portfolio.srf)
ZFIN_CACHE_DIR No Cache directory (default: ~/.cache/zfin)
ZFIN_SERVER_API_KEY No If set, gates all but the public endpoints and publishing
ZFIN_SERVER_PUBLISH_KEY No Enables publishing; see Publishing
ZFIN_SERVER_ADMIN_PREFIX No Adds POST <prefix>/refresh; see Over HTTP

License

MIT