Skip to content

Guide

Historical Exchange Rates in Python

Get historical exchange rates in Python with requests: one day with /v1/historical, a date range with /v1/timeseries, multi-year backfills and pandas.

Updated

Backtests, financial reports, invoices in foreign currencies and analytics dashboards all need past exchange rates, not just today's. This guide fetches historical rates in Python with the requests library: a single day, a date range, a multi-year backfill, and a pandas DataFrame at the end. Every call is plain HTTP, documented in the API reference.

Rates for one day

The historical endpoint takes a UTC calendar day in the path, as YYYY-MM-DD. Like the latest rates, it accepts a base (default USD) and an optional comma-separated symbols list of up to 200 codes. Try it with cURL first:

cURL
curl "https://api.fxbase.dev/v1/historical/2026-11-11?base=USD&symbols=EUR,INR" \
  -H "Authorization: Bearer $FXBASE_API_KEY"
Response
{
  "base": "USD",
  "date": "2026-11-11",
  "timestamp": "2026-11-11T16:00:03Z",
  "source": "daily",
  "rates": {
    "EUR": 0.90874,
    "INR": 88.4102
  }
}

rates holds units of each code per one unit of base. date is the day you asked for, and timestamp is when those rates were fetched. In Python, a requests.Session keeps the connection and the Authorization header for every call:

history.py
import os

import requests

API = "https://api.fxbase.dev"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['FXBASE_API_KEY']}"


def historical(day, base="USD", symbols="EUR,INR"):
    """The rates of one UTC day, YYYY-MM-DD."""
    res = session.get(
        f"{API}/v1/historical/{day}",
        params={"base": base, "symbols": symbols},
        timeout=10,
    )
    res.raise_for_status()
    return res.json()


day = historical("2026-11-11")
print(day["date"], day["rates"]["EUR"], day["source"])

Read the key from the environment, never from source code or a notebook cell you might share. Always pass a timeout: without one, requests can wait forever on a dead connection.

A date range with the time series endpoint

For a chart or a report you want every day in a range, not one call per day. The time series endpoint returns them in one answer. start and symbols are required, end defaults to today, and symbols takes 1 to 10 codes:

A range of days
def timeseries(start, end, symbols="EUR,INR", base="USD"):
    """Daily rates from start to end, both YYYY-MM-DD, at most 366 days apart."""
    res = session.get(
        f"{API}/v1/timeseries",
        params={"base": base, "symbols": symbols, "start": start, "end": end},
        timeout=10,
    )
    res.raise_for_status()
    return res.json()


series = timeseries("2026-11-02", "2026-11-04")
for day, rates in series["rates"].items():  # oldest first
    print(day, rates["EUR"], rates["INR"])
Response
{
  "base": "USD",
  "start": "2026-11-02",
  "end": "2026-11-04",
  "rates": {
    "2026-11-02": {
      "EUR": 0.90519,
      "INR": 88.2954
    },
    "2026-11-03": {
      "EUR": 0.90642,
      "INR": 88.3317
    },
    "2026-11-04": {
      "EUR": 0.90711,
      "INR": 88.3876
    }
  }
}

Days are keyed by date and come oldest first. A day with no quote is simply absent, so do not assume one entry per calendar day: iterate over the keys you get, or reindex in pandas and decide how to fill the gaps.

Backfill more than a year

One time series request covers at most 366 days after start; a longer range is a 400 with invalid_range. For a longer backfill, walk the range in windows and merge the results:

Longer than a year: one request per window
from datetime import date, timedelta

WINDOW = timedelta(days=366)  # the most end may be after start


def timeseries_range(start: date, end: date, symbols="EUR,INR", base="USD"):
    rates = {}
    while start <= end:
        stop = min(start + WINDOW, end)
        part = timeseries(start.isoformat(), stop.isoformat(), symbols, base)
        rates.update(part["rates"])
        start = stop + timedelta(days=1)
    return rates


# Three years needs a plan with five years of history.
end = date.today() - timedelta(days=1)
rates = timeseries_range(end - timedelta(days=3 * 365), end)

Three years takes three requests, not a thousand, so a backfill fits comfortably inside any plan's per-minute limit. Store what you fetch: a past day's rates do not change, so your own table is the cheapest cache there is, and you only need to fetch the new days on each run.

Load the rates into pandas

The rates mapping is already shaped like a table: dates down, currencies across. One call turns it into a DataFrame with a proper date index:

Into pandas
import pandas as pd

frame = pd.DataFrame.from_dict(rates, orient="index").sort_index()
frame.index = pd.to_datetime(frame.index)

print(frame["EUR"].describe())  # min, max, mean over the range
print(frame["EUR"].pct_change().abs().max())  # the largest day-to-day move
print(frame["EUR"].rolling(30).mean().tail())  # a 30-day moving average

From here, resampling to weekly or monthly averages, joining against your transactions by date, or plotting a pair are all one-liners. If you need a rate for a day the series skipped, decide explicitly between the previous day's rate (ffill) and leaving it blank, and document the choice in your report.

Handle the errors that matter

Historical requests fail for a few predictable reasons, each with its own problem code:

  • invalid_date (400): a day in the future.
  • invalid_range (400): end before start, or more than 366 days after it.
  • plan_required (403): your plan has no history, or not that far back.
  • no_rates (404): there are no rates for that request.
Errors worth handling
def get(path, **params):
    res = session.get(f"{API}{path}", params=params, timeout=10)
    if res.ok:
        return res.json()
    problem = res.json()  # application/problem+json
    if problem["code"] == "plan_required":
        raise SystemExit(f"Your plan cannot read this far back: {problem['detail']}")
    if problem["code"] in ("invalid_date", "invalid_range"):
        raise ValueError(problem["detail"])
    raise RuntimeError(f"{problem['status']} {problem['code']} ({problem['requestId']})")


leap_day = get("/v1/historical/2024-02-29", symbols="EUR")

Every error body carries a requestId; log it, because it is the fastest way for support to find your request. Over your limits you get a 429, covered in the rate limits guide.

How far back each plan reaches

The free Developer plan has latest rates and conversion only; historical and time series calls on it return plan_required. Startup ($12 a month) reads 1 year of history, Growth ($49 a month) reads 5 years of history, and Enterprise reads 5 years of history; Enterprise pricing is through sales. The limit is measured from today back to the day you ask for, or to start for a time series.

Requests count the same whichever endpoint you call, so a three-year backfill costs three of your 250,000 monthly Growth requests. A Python SDK is coming Coming soon; the requests above will keep working alongside it. To convert amounts at today's rates in JavaScript instead, see Convert currency in JavaScript.

Try it with a free key

The Developer plan is free and includes latest rates and conversion. Every request in this guide is in the API reference. Get a free API key.