DEV Community

Cover image for CFTC Commitments of Traders Data in Python: 4 Traps in the Public API
Be4TradingForex Editorial Team
Be4TradingForex Editorial Team

Posted on Fully Autonomous

CFTC Commitments of Traders Data in Python: 4 Traps in the Public API

The CFTC's Commitments of Traders (COT) data shows, every week, how hedge funds and asset managers are positioned in currency futures. It's free, it goes back to 2006, and the CFTC exposes it through a public JSON API, so you don't need any scraping or paid feed.

It's also easy to get subtly wrong. Here are four traps we hit while building a 10-year positioning study in Python, each checked against the live API, and the fetch function we ended up with.

The dataset

We used the Traders in Financial Futures (TFF) report, futures only. It splits positions into dealers, asset managers, leveraged funds (mostly hedge funds and CTAs) and others. The API endpoint is:

https://publicreporting.cftc.gov/resource/gpe5-46if.json
Enter fullscreen mode Exit fullscreen mode

It's a Socrata API, so it accepts SoQL parameters such as $where, $select, $order, $limit and $offset. No key is needed for light use.

Trap 1: the default limit silently cuts your history

Ask for every euro report and you get exactly 1,000 rows. There is no error, no warning and no "more data" flag. The euro has 1,067 weekly reports from June 2006 to November 2026. With $order ascending, the rows you lose are the most recent 67 weeks, the ones you probably care about most.

Fix: always pass $limit, and page with $offset if a page comes back full.

Trap 2: market names change

Markets are identified by a long name like EURO FX - CHICAGO MERCANTILE EXCHANGE. Names are not stable. The pound shows up under two:

Market name First report Last report Rows
BRITISH POUND STERLING - CHICAGO MERCANTILE EXCHANGE 2006-06-13 2022-02-01 817
BRITISH POUND - CHICAGO MERCANTILE EXCHANGE 2022-02-08 still current 250

Query only the current name and your pound history starts in 2022. Query the old name and it stops in 2022.

The tempting shortcut, upper(market_and_exchange_names) like '%POUND%', is worse. It also matches the euro/pound cross futures (EURO FX/BRITISH POUND XRATE), and you end up with two rows for 535 of the weeks, silently mixing two different markets.

Fix: list the exact names, and look them up first with a grouped query:

q = {
    "$select": "market_and_exchange_names, min(report_date_as_yyyy_mm_dd) as first, "
               "max(report_date_as_yyyy_mm_dd) as last, count(*) as n",
    "$where": "upper(market_and_exchange_names) like '%POUND%'",
    "$group": "market_and_exchange_names",
}
Enter fullscreen mode Exit fullscreen mode

Trap 3: every number is a string

The JSON gives you "lev_money_positions_long": "116493". In pandas that's an object column, and long - short raises an error, or worse, + concatenates the strings. Convert explicitly with pd.to_numeric.

Trap 4: the report date is not the day you could know it

report_date_as_yyyy_mm_dd is a Tuesday: the day the positions are measured. The CFTC publishes the report on the following Friday afternoon. If you join positions to Tuesday's closing price in a backtest, you are trading on information three days before anyone had it.

Fix: shift to the release date before joining with prices. Holiday weeks move the schedule slightly (in our data, 22 of the gaps between reports are 6 or 8 days instead of 7), so treat "Tuesday + 3 days" as an approximation, or use the CFTC release calendar if you need it exact.

The fetch function

import json, urllib.request, urllib.parse
import pandas as pd

TFF = "https://publicreporting.cftc.gov/resource/gpe5-46if.json"
MARKETS = {
    "EUR": ["EURO FX - CHICAGO MERCANTILE EXCHANGE"],
    "GBP": ["BRITISH POUND STERLING - CHICAGO MERCANTILE EXCHANGE",  # until 2022-02-01
            "BRITISH POUND - CHICAGO MERCANTILE EXCHANGE"],          # from 2022-02-08
    "JPY": ["JAPANESE YEN - CHICAGO MERCANTILE EXCHANGE"],
}

def fetch_tff(names, page=5000):
    """Weekly leveraged-fund positions for the exact market names given."""
    where = "market_and_exchange_names in (" + ",".join(f"'{n}'" for n in names) + ")"
    rows, offset = [], 0
    while True:
        q = {"$where": where, "$order": "report_date_as_yyyy_mm_dd",
             "$select": "report_date_as_yyyy_mm_dd,lev_money_positions_long,lev_money_positions_short",
             "$limit": page, "$offset": offset}
        batch = json.load(urllib.request.urlopen(TFF + "?" + urllib.parse.urlencode(q), timeout=60))
        rows += batch
        if len(batch) < page:
            break
        offset += page
    df = pd.DataFrame(rows)
    df["report_date"] = pd.to_datetime(df.pop("report_date_as_yyyy_mm_dd"))
    for c in ("lev_money_positions_long", "lev_money_positions_short"):
        df[c] = pd.to_numeric(df[c])
    df = df.drop_duplicates("report_date", keep="last").set_index("report_date").sort_index()
    df["net"] = df.lev_money_positions_long - df.lev_money_positions_short
    # Positions are as of Tuesday; the report is public on Friday afternoon.
    df["available"] = df.index + pd.Timedelta(days=3)
    return df
Enter fullscreen mode Exit fullscreen mode

Run against the live API, it returns 1,067 weekly rows for each of the euro, pound and yen (June 2006 to November 2026), with no duplicate dates, and the pound's history joined across the rename.

Turning positions into a signal: the COT index

Raw net positions aren't comparable across currencies or decades, so a common normalization is the COT index: where this week's net position sits within its range over the last three years (156 weeks), from 0 (most short) to 100 (most long).

def cot_index(net, weeks=156):
    lo, hi = net.rolling(weeks).min(), net.rolling(weeks).max()
    return (net - lo) / (hi - lo) * 100
Enter fullscreen mode Exit fullscreen mode

For the report dated November 17, 2026, leveraged funds were net short 76,587 euro contracts, a COT index of 1.5: close to their most bearish level of the past three years.

Does extreme positioning predict reversals?

Traders often read an extreme COT reading as "the crowd is all in, so it's about to turn." We tested that for the euro, yen, pound and Australian dollar from 2015 to 2026, measuring each currency against the dollar over the 12 weeks after the report was released (Trap 4).

Currency Weeks the currency rose over the next 12 weeks: all weeks When leveraged funds were most short (index 10 or below)
EUR 48% 37%
JPY 42% 36%
GBP 51% 35%
AUD 47% 34%

In all four currencies, crowded shorts were followed by more weakness, not a rebound. In this sample, extreme speculator positioning behaved more like a trend signal than a contrarian one. The samples are small (20 to 33 extreme weeks per currency), so treat it as a description of the past, not a rule.

Code

Our full study code and aggregate results are in our public repo: https://github.com/b4tradingforex/be4-forex-data-studies (folder 07-cftc-positioning). The trader-oriented write-up of the positioning study is at https://www.be4tradingforex.com/forex-market-sentiment/

If you use the CFTC API for other markets (rates, equity index futures), have you hit other renamed markets? I'd like to collect them in one list.

Educational content, not financial advice. Trading leveraged products such as forex carries a high risk of loss.

Top comments (0)