Skip to content
shaikn6Public

About

One fintech API that routes cheap-to-expensive for sentiment, explains every credit score, and can sign its answers.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

finarena

One fintech API that routes cheap-to-expensive for sentiment, explains every credit score, and detects signatures in document images.

CI License: MIT Python 3.10+

One authenticated API in front of several fintech models, each chosen for the job it is best at, with routing between a cheap model and an accurate one so most requests never pay for the expensive model.

Endpoint What it does Models
POST /v1/sentiment Bearish / Bullish / Neutral for financial news text TF-IDF + logistic regression (fast) and Qwen2.5-0.5B + LoRA (accurate), with a confidence cascade
POST /v1/credit/score Probability of default and approve / decline Gradient boosting (accurate) or logistic regression with plain-language reason codes (explainable)
POST /v1/signature/detect Finds signatures in document images YOLO11n (optional extra, see Licensing)
POST /v1/analyze One entry point for mixed workloads: send sentiment and credit items together, each is routed to its specialist; items of one kind share a single model call and a failure affects only its own items all of the above
GET /v1/models Model cards with measured metrics
GET /metrics Prometheus metrics: requests by route and status, latency histogram, rate-limited, model-busy and escalation counters
GET /health, GET /ready Liveness and readiness

A browser interface is served at / (try the sentiment router, score a credit account, and drag the routing slider over the measured benchmark results); API reference at /docs.

FinArena UI

Why this exists

Calling one large model for every request is expensive, and a single cheap model is wrong on the hard cases. This repository shows the engineering around that choice: each task is served by the model family that measured best for it, a confidence cascade sends only uncertain sentiment requests to the LLM, and the API around the models (keys, rate limits, metrics, degraded modes) reports which model answered every item.

What this is, and how it differs from my other repos

FinArena is a serving layer, not a model and not a generic proxy. Three fintech specialists sit behind one authenticated API with shared operational concerns: keys, rate limits, size caps, Prometheus metrics, degraded modes and a per-item router. It is deliberately distinct from its two neighbours:

  • fin-lora trains and benchmarks the sentiment model. FinArena only serves it, and adds the TF-IDF fast tier and the confidence cascade around it.
  • llm-gateway is a general OpenAI-compatible chat proxy (any provider, response caching, A/B routing, cost tracking). FinArena is the opposite: a small, fixed set of purpose-built, non-chat fintech endpoints, each served by the model family that measured best for it.

So fin-lora is a model, llm-gateway is a generic gateway, and FinArena is the fintech-specific API that combines a cost-routed sentiment cascade, explainable credit scoring with reason codes, and signature detection in one deployable service.

Architecture

flowchart TD
    C["Client or browser UI"] --> API["FastAPI app<br/>src/finarena/main.py<br/>API key, rate limit, size cap, metrics"]
    API --> D["dispatch.py<br/>sentiment, credit, analyze"]
    D --> S["SentimentService<br/>models/sentiment.py"]
    S --> F["Fast model<br/>TF-IDF + logistic regression"]
    S -- "auto: top probability below 0.8" --> L["LLM model<br/>Qwen2.5-0.5B + LoRA<br/>optional llm extra"]
    D --> CR["CreditScorer<br/>models/credit.py<br/>gradient boosting, or logistic regression + reason codes"]
    API --> SG["SignatureDetector<br/>models/signature.py<br/>optional YOLO11n"]
    LD["loader.py<br/>reads artifacts/"] -.-> S
    LD -.-> CR
    LD -.-> SG
Loading

A missing optional model (LLM, signature weights) turns its endpoint into a 503 or, for auto sentiment, a fast-model answer; by default it does not stop the service (FINARENA_REQUIRE_LLM=1 makes a missing LLM fatal at startup).

Quickstart

The trained models are committed, so a fresh clone needs no training step:

make install                # creates .venv and installs the package with the dev tools
FINARENA_ENV=dev make run   # http://localhost:8000, auth disabled for local use only

In a second terminal:

curl localhost:8000/health
curl localhost:8000/ready
curl -H "content-type: application/json" localhost:8000/v1/sentiment \
  -d '{"texts": ["$TSLA beats earnings, stock jumps"], "strategy": "auto"}'
curl -H "content-type: application/json" localhost:8000/v1/credit/score \
  -d '{"applications": [{"limit_bal": 50000, "education": 2, "marriage": 1, "age": 35, "pay_status": [3, 3, 2, 2, 2, 2], "bill_amt": [48000, 48000, 48000, 48000, 48000, 48000], "pay_amt": [0, 0, 0, 0, 0, 0]}]}'

Optional steps:

.venv/bin/pip install -e ".[dev,llm]"   # adds the LLM tier (torch, transformers, peft); the Qwen2.5-0.5B base model is downloaded on first start
make train                              # retrains the credit model from the public dataset (downloaded from OpenML)

Without the llm extra, /ready reports "sentiment_llm": false, strategy: "auto" serves the fast model only (nothing escalates) and strategy: "accurate" returns 503. The sentiment models are not trained in this repo: they are imported from fin-lora with scripts/import_sentiment.py (see Updating the sentiment model).

Or with Docker Compose (read-only filesystem, non-root, health check): cp .env.example .env, set your keys, then docker compose up -d --build. See docs/DEPLOY.md for sizing, TLS, monitoring and rollback.

Production requires keys, otherwise the service refuses to start:

export FINARENA_API_KEYS=key-one,key-two
docker build -t finarena . && docker run -p 127.0.0.1:8000:8000 -e FINARENA_API_KEYS=$FINARENA_API_KEYS finarena
curl -H "x-api-key: key-one" -H "content-type: application/json" localhost:8000/v1/sentiment \
  -d '{"texts": ["$TSLA beats earnings, stock jumps"], "strategy": "auto"}'

Build with the LLM (about 3.8 GB; the base model is baked in so startup needs no network): docker build --build-arg EXTRAS='[llm]' --build-arg PRELOAD_LLM=1 -t finarena:llm . Set FINARENA_REQUIRE_LLM=1 so the container refuses to start, rather than silently serving only the fast model, if the LLM cannot load. /ready reports sentiment_llm either way. The trained artifacts (artifacts/, 38.5 MB, which du -sh shows as 37M, including the 35.2 MB LoRA adapter) are committed, so a fresh clone builds and runs as-is; scripts/ regenerates them. Only signature.pt (AGPL-linked) is kept out of git: supply it yourself to enable /v1/signature/detect (see Signature endpoint below).

How routing works

strategy: "auto" answers with the fast model and escalates only the requests whose top-class probability is below FINARENA_CASCADE_THRESHOLD (default 0.8) to the LLM. Each result reports which model answered and whether it escalated, so cost is auditable. fast and accurate force a single model.

Engineering

  • Strict request validation (Pydantic), batch / text / image size limits, constant-time API-key check.
  • Request IDs on every response, structured JSON access logs, no stack traces returned to clients.
  • Models load from artifacts/; a missing optional model degrades that endpoint to 503, never a crash.
  • Sex is not an accepted input and not a model feature. Age and marital status are (see the fair-lending disclosure under Limitations). The credit service returns the cost assumption behind its decision threshold with every response.
  • Per-client rate limiting (429 + Retry-After) and a request-size cap that refuses oversized bodies before reading them.
  • Tests cover the API contract, auth, validation, routing, concurrency, rate limiting and credit behaviour on the real model; lint clean (ruff); CI workflow runs tests and a container smoke test.

Measured model behaviour

Numbers come from the benchmark projects that produced these models; see artifacts/model_cards.json for the values the running service reports. Provenance: the sentiment accuracies below were re-measured through this API's own code path by scripts/verify_api_accuracy.py (needs the llm extra and dataset downloads; raw results in artifacts/api_verification.json); the credit AUCs are recorded from credit-arena. On CPU, with no network and no LLM, make test reproduces the parts that need neither: the full API contract, the routing/cascade decision logic, and the credit model's behaviour on the committed artifacts/credit.joblib.

  • Credit: gradient boosting test AUC 0.774 vs logistic regression 0.746 (paired bootstrap difference +0.027, 95% CI [0.019, 0.036]) on 30,000 accounts. Adding more models or segment specialists gave no significant gain.

  • Sentiment, accuracy on three held-out sets (full details and code in fin-lora):

    Model Tweets (2,388) Manual headlines (267) News snippets (2,000)
    TF-IDF + logistic regression (fast tier) 75.8% 73.4% 71.7%
    FinBERT, zero-shot 72.5% 71.2% 73.6%
    Qwen2.5-0.5B + LoRA, tweets only (the previous version) 90.7% 61.8% 59.0%
    Qwen2.5-0.5B + LoRA, news + tweets (accurate tier) 86.6% 76.8% 84.7%

    How to read it: the tweets-only model was excellent on tweets and poor on news, which is why the current model was retrained on news. The headline set is the human-labelled test: it is the test split of Jean-Baptiste/financial_news_sentiment, and those 267 headlines were never trained on, but the same dataset's training split is part of the training mix, so it is held out rather than a different source. It has only 267 examples, so the margin of error is about 5 points and the LoRA model's lead there is not statistically proven; it also contains just 12 negative headlines, so negative-class results are unreliable. The snippet labels were produced by an LLM ensemble (NOSIBLE), and the model was trained on the same kind of labels, so its 84.7% there overstates how it would do against human judgement. Part of this was re-measured through this API (artifacts/api_verification.json): on all 267 manual headlines the accurate path scores 76.8%, the fast path 73.4%, and auto 77.2% while escalating 52% of requests; on a 400-tweet sample the accurate path scores 88.0%, the fast path 73.3% and auto 86.5% while escalating 58%. The news snippets were not re-measured through the API. Escalation threshold 0.8 was chosen on dev data only: on the full test sets the cascade lands about 1 point from always using the LLM (0.4 to 1.05) while sending 52% (headlines), 56% (tweets) and 70% (news snippets) of requests to it (fin-lora's cascade_news.json; not re-run here). Latency is batch-size-1 on Apple MPS and will differ elsewhere.

Configuration

All settings are environment variables, read once at startup.

Variable Default Meaning
FINARENA_ENV prod prod refuses to start without API keys; dev disables auth (local use only)
FINARENA_API_KEYS none Comma-separated keys, sent as x-api-key: <key> or Authorization: Bearer <key>
FINARENA_ARTIFACT_DIR artifacts Where model files and results are loaded from
FINARENA_RATE_PER_MINUTE 120 Requests per minute per client (API key, else IP) on /v1/*; bursts up to this size; 0 disables. Over the limit: 429 with Retry-After. Health, readiness and the UI are never limited. Per process.
FINARENA_MAX_BATCH 64 Items per request (413 above)
FINARENA_MAX_TEXT_CHARS 2000 Characters per text (tweet, headline or news snippet). The LLM reads a 256-token window: longer text is trimmed, never the prompt
FINARENA_MAX_IMAGE_BYTES 10485760 Largest image; any request body over this plus 64 KiB is refused with 413 before it is read; POSTs without a Content-Length (chunked uploads) get 411
FINARENA_CASCADE_THRESHOLD 0.8 Confidence below which auto escalates to the LLM
FINARENA_ENABLE_LLM / FINARENA_REQUIRE_LLM 1 / 0 Load the LLM; refuse to start if it cannot load
FINARENA_MODEL_WAIT_SECONDS 20 How long a request waits for a busy model before 503
FINARENA_ENABLE_SIGNATURE 0 Enable the AGPL-linked signature endpoint
FINARENA_SIGNATURE_WEIGHTS <artifact dir>/signature.pt Path to the YOLO11 signature weights. Enabled without weights: a startup warning, and the endpoint answers 503 ("signature model not configured")

Rate limiting keys on the API key when one is sent, otherwise on the client IP. Behind a reverse proxy the IP is the proxy's, so either rely on API keys or start uvicorn with --proxy-headers --forwarded-allow-ips=<proxy address>.

Signature endpoint

The route, image decoding and error handling are in the repo and tested with a stand-in model. The YOLO weights are not committed: they are AGPL-3.0 (trained with ultralytics on an AGPL dataset), and this repo is MIT. To serve real detections:

pip install ".[signature]"
# weights: train with sigdet (https://github.com/shaikn6/sigdet, AGPL-3.0) or use its weights/signature_yolo11n.pt
export FINARENA_ENABLE_SIGNATURE=1 FINARENA_SIGNATURE_WEIGHTS=/path/to/signature_yolo11n.pt
# real-inference tests (skipped otherwise); the sample is any document photo with a signature
FINARENA_SIGNATURE_SAMPLE=/path/to/photo.jpg pytest tests/test_signature.py

Updating the sentiment model

The model, its fast tier and the benchmarks come from fin-lora. To retrain and ship a new version:

# in fin-lora: train, evaluate, then export what the API needs
python train_news.py Qwen/Qwen2.5-0.5B-Instruct news-0.5b && python eval_news.py ... && python export_for_finarena.py
# in finarena: install it (checks everything first, then swaps atomically), refresh the arena data, run the tests
python scripts/import_sentiment.py ~/fin-lora && python scripts/build_arena.py && pytest

The adapter ships with a prompt.json (the exact prompt template and token window it was trained with) and the API reads its prompt from there, so serving cannot drift from training. An adapter without that file refuses to load.

Capacity

Measured on 2026-10-10 on an Apple M2 Pro (14-inch MacBook Pro, 16 GB), one native process with the LLM on the Apple GPU, 8 concurrent clients, 60 requests per path, load average about 3.5. Raw output of both runs: artifacts/load_test.txt; the table is the second, warm run.

FINARENA_ENV=dev FINARENA_RATE_PER_MINUTE=0 .venv/bin/uvicorn finarena.asgi:app   # needs the llm extra
.venv/bin/python scripts/load_test.py http://localhost:8000 60 8                  # in a second terminal
Path Throughput p50 p95 Errors
sentiment fast 644 req/s 8 ms 19 ms 0
sentiment auto (cascade) 23 req/s 504 ms 524 ms 0
sentiment accurate (LLM only) 17 req/s 455 ms 509 ms 0
credit score 51 req/s 139 ms 228 ms 0

The LLM paths depend heavily on what else the machine is doing: the same test on this laptop under heavy load (load average about 15) dropped to 4-6 req/s for auto and accurate.

Inputs mix tweets, headlines and news-length snippets. On this mix auto is only slightly faster than accurate: the fast model is rarely confident about news, so most requests escalate (about 52-70% on the test sets). The cascade saves real work on easy text such as tweets, much less on news.

In the Docker image (an earlier recorded run, not repeated on 2026-10-10; CPU only, 4 concurrent clients, 40 requests each, ~2.6 GB RAM): fast 429 req/s, credit 64 req/s, auto 4.5 req/s (p50 1.3 s), accurate 3.3 req/s (p50 1.3 s), 0 errors, 0 restarts. Reproduce with python scripts/load_test.py http://localhost:8000 40 4 against the container.

The LLM runs one request at a time (torch on Apple's GPU aborts the process if two threads use it at once; this was found by this very load test, which killed the first version of the server). Callers wait up to FINARENA_MODEL_WAIT_SECONDS (default 20) for their turn, then receive 503 with Retry-After: 2. Run more processes or replicas to scale the accurate path; scripts/load_test.py produced these numbers; run the server with FINARENA_RATE_PER_MINUTE=0 when load testing, otherwise the rate limit (below) will answer most of the requests with 429.

Limitations (read before selling or deploying)

  • Not a trading system. Nothing here predicts markets or makes money by itself.
  • The credit model is trained on one public 2005 Taiwanese dataset. Before lending decisions it must be retrained and validated on your own portfolio, with your own fair-lending and model-risk review (e.g. SR 11-7 / ECOA). Outputs are decision support, not adverse-action notices.
  • Fair lending (ECOA / Regulation B): excluding sex is not enough. The credit model does use age (age) and marital status (marriage) as input features, and the explainable model's reason codes can print "Borrower age" or "Marital status" as a decline reason (REASON_TEXT in src/finarena/models/credit.py). Age and marital status are protected bases under ECOA, so this credit model is a demonstration of the API and the reason-code mechanics, not a model to make real credit decisions with. A production model would exclude ECOA-protected bases (and be tested for proxies for them) before use. The reported AUCs include the effect of these two features, and the reason codes are left as the model's real drivers rather than hidden. This model has not been retrained without them.
  • Sentiment is trained on English finance tweets, press-release headlines and news snippets. Other languages are out of distribution, texts are trimmed to fit a 256-token window (the beginning is kept), and the model is weakest on negative news headlines (rare in the only human-labeled test set).
  • Rate limits are per process (see Configuration) and there is no persistence; behind several replicas, also enforce limits at the gateway.

Licensing

The core service (sentiment, credit) depends only on permissively licensed components. The signature detector uses ultralytics and a dataset that are AGPL-3.0. Enabling it in a closed-source commercial product requires either open-sourcing that product under AGPL-3.0 or buying an Ultralytics commercial licence. It is an optional extra (pip install ".[signature]", FINARENA_ENABLE_SIGNATURE=1) and is off by default. The trained weights are not bundled for the same reason: they are derived from the AGPL dataset and library, and bundling them would put AGPL material inside this MIT repository.

Qwen2.5-0.5B-Instruct is Apache-2.0. Datasets: UCI credit default (CC BY 4.0); for sentiment, zeroshot/twitter-financial-news-sentiment (MIT), Jean-Baptiste/financial_news_sentiment (MIT) and NOSIBLE/financial-sentiment (ODC-By: credit to NOSIBLE). Before selling the sentiment model, have counsel review the NOSIBLE data: its labels were generated by LLMs from several vendors (their terms may restrict training on outputs) and its text is scraped from public news sites.

Companion projects

The models FinArena serves were built and benchmarked in their own repos, with data, tests and caveats:

  • fin-lora: LoRA-tuned Qwen2.5-0.5B for finance sentiment versus a TF-IDF baseline, plus the confidence cascade (sentiment endpoint)
  • credit-arena: credit-default model comparison with significance tests and a fair-lending audit (credit endpoint)
  • sigdet: signature detector and robustness study (signature endpoint; see Licensing above)

Related experiments the API does not use:

  • trade-arena: walk-forward backtest of trading models, net of costs
  • exec-rl: PPO trade-execution agent (simulation only)

Part of Nagizaaz Shaik's open-source work · all repositories

About

One fintech API that routes cheap-to-expensive for sentiment, explains every credit score, and can sign its answers.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages