# Build a custom scoring model (/score-model/custom-scoring-models)



The [scoring endpoints](/score-api) score common decisions out of the box. For a decision of your own, create a **scoring model**: you describe the decision, calibrate it with past records labeled with how they turned out, and it scores new records from 0 to 1000 on your own fraud rates. Custom scoring models come with the Starter plan and above ([Pricing](/pricing#plans)); creating and calibrating them is free.

You need an API key in `FINIC_API_KEY`; see the [Quickstart](/quickstart#get-an-api-key). For the ideas behind it, see [Scoring models](/score-model) and [Calibration](/score-model/calibration).

<Steps>
  <Step>
    ### Create a scoring model [#create-a-scoring-model]

    Name it and describe the decision: what it is, and what a bad outcome means.

    ```bash
    curl https://api.finic.ai/v1/score/models \
      -H "Authorization: Bearer $FINIC_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"name": "Card-not-present payment fraud", "criteria": "Card-not-present payments at an online store. Bad: the payment was charged back as fraud within 90 days."}'
    ```

    ```json title="201"
    { "model_id": "scm_01M4XRC000RT2GZSKYPD8J86G9", "request_id": "req_01M4Y7FASG9DB7MMWCS672J0JD" }
    ```

    Creating is free, and it's ready at once, with no questions yet. You can also create it from labeled records in one step; see [Creating a scoring model](/score-model#creating-a-scoring-model).
  </Step>

  <Step>
    ### Calibrate it [#calibrate-it]

    Gather 100+ past records of the decision, 20+ of each outcome, with the fields you send when you score, plus `is_bad` (`true` when the outcome was bad). To try it out, use [sample-payments.csv](/examples/sample-payments.csv), 300 synthetic card payments:

    ```csv title="sample-payments.csv"
    amount_usd,merchant_category,account_age_days,new_device,billing_country,ip_country,is_bad
    2400.00,electronics,19,true,US,NG,true
    58.12,grocery,1260,false,US,US,false
    310.00,gift_cards,3,true,US,US,true
    ```

    ```bash
    curl https://api.finic.ai/v1/calibrate \
      -H "Authorization: Bearer $FINIC_API_KEY" \
      -F model_id=scm_01M4XRC000RT2GZSKYPD8J86G9 \
      -F file=@sample-payments.csv
    ```

    ```json title="202"
    { "job_id": "job_01M4XZXNCRZBPXV30MSF7RN5H3", "rows": 300, "request_id": "req_01M4YPJNK0SZGEQS0A76EEND4N" }
    ```

    Finic writes the scoring model's questions from the records and fits them to your outcomes, for free. Rows can also go in as a JSON array in `data`. See [Labeled records](/score-model#labeled-records) for what to include.
  </Step>

  <Step>
    ### Wait for the job [#wait-for-the-job]

    Calibrating takes about two minutes. Check every 10 seconds or so until `complete` is `true`:

    ```bash
    curl https://api.finic.ai/v1/jobs/job_01M4XZXNCRZBPXV30MSF7RN5H3 -H "Authorization: Bearer $FINIC_API_KEY"
    ```

    ```json title="200"
    { "job_id": "job_01M4XZXNCRZBPXV30MSF7RN5H3", "complete": true }
    ```

    An `error` in the response says what went wrong; see [Get a job](/reference/score/get-job-status).
  </Step>

  <Step>
    ### Score a record [#score-a-record]

    Send a record with the same fields, and your own unique `score_id` for it:

    ```bash
    curl https://api.finic.ai/v1/score \
      -H "Authorization: Bearer $FINIC_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"model_id": "scm_01M4XRC000RT2GZSKYPD8J86G9", "score_id": "pay_88213", "data": {"amount_usd": 1850.0, "merchant_category": "electronics", "account_age_days": 6, "new_device": true, "billing_country": "US", "ip_country": "RO"}}'
    ```

    ```json title="200"
    { "model_id": "scm_01M4XRC000RT2GZSKYPD8J86G9", "score_id": "pay_88213", "score": 874, "request_id": "req_01M4YF1068X8B4C458ENPD4JHT" }
    ```

    874 means about an 87% chance of a bad outcome: the scoring model is calibrated, so its scores are about the chance of a bad outcome, and you can choose thresholds on them. [`GET /v1/score/models/{model_id}`](/reference/score/get-scoring-model) shows its questions, and [`add_questions`](/reference/score/add-questions) adds your own. Records you score must have the fields of the calibration's records; see [Schema](/score-model#schema).

    Want to score before you have labeled records? [Add your own questions](/reference/score/add-questions) to the new scoring model: it scores with them right away, weighed by Finic's estimates, until you calibrate it.
  </Step>

  <Step>
    ### Keep it calibrated [#keep-it-calibrated]

    As you learn how more records turned out, calibrate again with a fresh set of labeled records, the same way. Each calibration is free and chooses again which questions to use. See [Calibration](/score-model/calibration#calibrate-a-scoring-model).
  </Step>
</Steps>

Log the `X-Request-Id` header of every response; support asks for it.

## The whole flow in Python [#the-whole-flow-in-python]

```python
import os
import time

import requests

API = "https://api.finic.ai"
HEADERS = {"Authorization": f"Bearer {os.environ['FINIC_API_KEY']}"}


def check(r: requests.Response) -> dict:
    if not r.ok:
        e = r.json()["error"]
        raise RuntimeError(f"{r.status_code} {e['type']}: {e['message']} (request {r.headers.get('X-Request-Id')})")
    return r.json()


def wait_for(job_id: str) -> None:
    while not (job := check(requests.get(f"{API}/v1/jobs/{job_id}", headers=HEADERS, timeout=30)))["complete"]:
        time.sleep(30)
    if "error" in job:
        raise RuntimeError(f"{job['error']['type']}: {job['error']['message']}")


created = check(requests.post(f"{API}/v1/score/models", headers=HEADERS, timeout=60,
                              json={"name": "Card-not-present payment fraud",
                                    "criteria": "Card-not-present payments. Bad: charged back as fraud within 90 days."}))

# Fit it to your data with labeled records:
with open("sample-payments.csv", "rb") as f:
    calibration = check(requests.post(f"{API}/v1/calibrate", headers=HEADERS, timeout=60,
                                      data={"model_id": created["model_id"]}, files={"file": f}))
wait_for(calibration["job_id"])

record = {"amount_usd": 1850.0, "merchant_category": "electronics", "account_age_days": 6,
          "new_device": True, "billing_country": "US", "ip_country": "RO"}
scored = check(requests.post(f"{API}/v1/score", headers=HEADERS, timeout=60,
                             json={"model_id": created["model_id"], "score_id": "pay_88213", "data": record}))
print(scored["score"])
```

Every endpoint in the [API reference](/reference) has a playground that sends requests from the docs.
