Bulk Currency Conversion: Convert a CSV of Transactions with One Rate per Currency

6 min read

Bulk Currency Conversion: Convert a CSV of Transactions with One Rate per Currency

You have a CSV export with 50,000 transactions in a dozen currencies, and finance wants one column in EUR. The naive approach is one conversion call per row. The better approach for bulk currency conversion is to fetch one rate per distinct currency, then apply that rate to every row locally.

That cuts 50,000 requests down to a dozen, makes the whole file consistent (every USD row uses the same USD rate), and gives you a clean audit trail. This article explains the approach, the decimal and rounding traps, and a complete Python script you can adapt.

Why one rate per currency beats one call per row

Per-row conversion looks simple, but it has three problems:

  • Cost and speed. Every row burns a request unit and a network round trip. You will also hit your per-second rate limit quickly.
  • Inconsistent results. Rates move. If the script runs for ten minutes, two USD rows in the same file can convert at different rates, and nobody can explain why the totals differ from a re-run.
  • No audit trail. If each row silently used a different rate, you can't reproduce the number later.

Fetching the rate once per currency pair fixes all three. The file becomes a single "snapshot": one rate, one timestamp, per currency. Anyone can recompute any row from the rate you stored.

The number of calls is the number of distinct source currencies, not the number of rows. A file with 50,000 rows in 12 currencies needs 12 rate lookups.

Step 1: Collect the distinct currencies

Read the file once and build a set of currency codes. Validate them as you go, because dirty exports often contain lowercase codes, blanks or retired codes. If you need a refresher on validation, see currency code validation for ISO 4217 codes.

Normalize the codes (trim and uppercase), skip the target currency (a EUR row converted to EUR needs no lookup; the rate is exactly 1), and collect the rest.

Step 2: Fetch one rate per pair

For each distinct source currency, request the rate from that currency to your reporting currency. The current rate endpoint returns the rate as a string, plus the metadata you need for an audit trail:

{"base":"USD","quote":"EUR","rate":"0.9213","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}

The numbers here are examples only. Three fields matter for bulk work:

  • rate is a decimal string. Parse it with a decimal type, never a float.
  • as_of is the time of the observation. Store it. For a derived rate it is the oldest input's timestamp.
  • status is fresh or stale. Stale rates are flagged, not withheld, so your job should decide what to do. For a month-end report you may want to abort on stale; for an internal estimate you may accept it with a warning. More on that in how to detect and handle stale exchange rates.

If you have many source currencies, there is also a way to get up to 20 quotes against one base in a single request unit. That is handy when your reporting currency is the base of the calculation; see getting multiple exchange rates in one API call. For bulk files with mixed source currencies, requesting source -> target pairs one at a time is simple and still only costs one unit per currency.

Step 3: Apply the rate with exact decimals

Every row's converted amount is amount * rate. Do this with a decimal type: Python's Decimal, Java's BigDecimal, PHP's BCMath, and so on. Binary floats turn 0.1 + 0.2 into 0.30000000000000004, and across 50,000 rows those errors show up as a total that is off by a cent. The background is covered in currency conversion rounding without floating-point errors.

GetRatesAPI returns rates and amounts as strings and doesn't round the result, so rounding is your decision. Two rules keep bulk jobs sane:

  1. Round once, at the end, to the target currency's minor units. EUR has 2 decimals, JPY has 0, KWD has 3. See currency decimal places and minor units.
  2. Decide how totals are computed. Summing rounded rows and rounding the sum of unrounded rows can differ by a few cents. Pick one rule, document it, and use it everywhere. Per-row rounding is usually right if each row becomes a ledger line; rounding the sum is usually right for a one-off statistic.

The complete Python script

This script reads transactions.csv with columns id, amount and currency, converts everything to EUR, and writes transactions_eur.csv with the rate and timestamp on every row. Rows that can't be converted go to a separate rejects list instead of crashing the job.

import csv
import os
import sys
from decimal import Decimal, InvalidOperation, ROUND_HALF_EVEN

import requests

API = "https://api.getratesapi.com"
TARGET = "EUR"
TARGET_EXPONENT = Decimal("0.01")  # EUR has 2 minor-unit digits
HEADERS = {"Authorization": f"ApiKey {os.environ['GETRATESAPI_KEY']}"}


def fetch_rate(session, base, quote):
    resp = session.get(
        f"{API}/v1/rates/{base}/{quote}",
        headers=HEADERS,
        timeout=10,
    )
    if resp.status_code != 200:
        code = resp.json().get("code", "unknown")
        raise RuntimeError(f"{base}->{quote} failed: {code}")
    data = resp.json()
    return {
        "rate": Decimal(data["rate"]),
        "as_of": data["as_of"],
        "status": data["status"],
        "type": data["type"],
    }


def main(src_path, dst_path):
    with open(src_path, newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))

    # Step 1: distinct, normalized source currencies
    for row in rows:
        row["currency"] = row["currency"].strip().upper()
    currencies = {r["currency"] for r in rows if r["currency"]} - {TARGET}

    # Step 2: one rate per currency
    rates = {}
    failed = {}
    with requests.Session() as session:
        for cur in sorted(currencies):
            try:
                rates[cur] = fetch_rate(session, cur, TARGET)
            except RuntimeError as exc:
                failed[cur] = str(exc)

    # Step 3: apply locally with exact decimals
    fieldnames = ["id", "amount", "currency", "amount_eur",
                  "rate", "rate_as_of", "rate_status"]
    rejects = []
    with open(dst_path, "w", newline="", encoding="utf-8") as out:
        writer = csv.DictWriter(out, fieldnames=fieldnames)
        writer.writeheader()
        for row in rows:
            cur = row["currency"]
            try:
                amount = Decimal(row["amount"].strip())
            except InvalidOperation:
                rejects.append((row["id"], "invalid amount"))
                continue

            if cur == TARGET:
                info = {"rate": Decimal("1"), "as_of": "", "status": "n/a"}
            elif cur in rates:
                info = rates[cur]
            else:
                rejects.append((row["id"], failed.get(cur, "missing currency")))
                continue

            converted = (amount * info["rate"]).quantize(
                TARGET_EXPONENT, rounding=ROUND_HALF_EVEN
            )
            writer.writerow({
                "id": row["id"],
                "amount": row["amount"],
                "currency": cur,
                "amount_eur": str(converted),
                "rate": str(info["rate"]),
                "rate_as_of": info["as_of"],
                "rate_status": info["status"],
            })

    print(f"converted {len(rows) - len(rejects)} rows, rejected {len(rejects)}")
    for row_id, reason in rejects:
        print(f"  row {row_id}: {reason}", file=sys.stderr)


if __name__ == "__main__":
    main("transactions.csv", "transactions_eur.csv")

Set the key in your environment first (export GETRATESAPI_KEY=...) so it never lands in the script or in version control.

Handling the awkward cases

Unsupported or malformed currencies. An unknown code produces an error such as invalid_asset_symbol (400) or unsupported_pair (404). Match on the code field, not the message. Reject only the rows in that currency and report them; don't fail the whole file. The full list is in the error reference.

Rate limits. With a dozen currencies you will not come near your per-second limit, but a file with hundreds of currencies and a free plan at 2 requests per second might. Pace your calls and honor retry_after_seconds on a rate_limit_exceeded response. The rate limits guide covers the details.

Transactions from different dates. A live rate converts at today's value. If each row should convert at the rate on its own transaction date, you need the rate you captured on that date. GetRatesAPI serves current rates only, with no historical or time-series endpoint, so the right pattern is to snapshot and store rates when events happen. For month-end work, see how to snapshot month-end exchange rates. For a bulk job, a live-rate file is best described as "converted at the rates observed at rate_as_of", which is exactly what the output columns say.

Stale rates. Check rate_status before you publish. A simple policy is to fail the job if any rate is stale, wait a minute, and retry.

Re-runs. If you must reproduce a result, don't call the API again. Persist the rates dictionary (for example as a small JSON file next to the output) and feed it into the conversion step. The output CSV already carries the rate and timestamp per row, which is enough to verify any single line by hand.

A quick checklist

  • One lookup per distinct currency, not per row.
  • Parse rate and amount as decimals, never floats.
  • Round once, to the target currency's minor units.
  • Store rate, as_of and status next to every converted value.
  • Reject bad rows individually and report them.
  • Keep the rate snapshot if you may need to reproduce the run.

Try it on your own file

A bulk job like this uses a handful of request units per run, so the free plan with 500 units a month is plenty to test with. Sign up for a free API key, try your currencies in the dashboard playground, then run the script against a sample of your export. If you later schedule it daily across many currencies, compare plan sizes on the pricing page.

All articles →
Bulk Currency Conversion: Convert a CSV with Live Rates — GetRatesAPI