Coverage for data_pipeline/cftc_cot.py: 100%
87 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""CFTC Commitments of Traders positioning (V6.5.0, free, no account): speculators' net position as a share of open interest.
3The report is dated Tuesday and published Friday afternoon, after the equity close, so a row is first usable on the next
4session after `publication_date` (report date + 3 days); keying on the report date would read three days ahead.
6 python -m data_pipeline.cftc_cot --apply --start-year 2005
7"""
9from __future__ import annotations
11import argparse
12import csv
13import io
14import zipfile
15from collections.abc import Callable, Iterable
16from datetime import date, timedelta
17from pathlib import Path
19import numpy as np
20import pandas as pd
22OUTPUT = Path(__file__).resolve().parent.parent / "data" / "reference" / "cot_positioning.csv"
23URL = "https://www.cftc.gov/files/dea/history/deacot{year}.zip"
24PUBLICATION_LAG_DAYS = 3
25CHANGE_WEEKS = 13
27# market key -> the CFTC market names it has appeared under
28MARKETS = {
29 "EUR": ("EURO FX - CHICAGO MERCANTILE EXCHANGE",),
30 "JPY": ("JAPANESE YEN - CHICAGO MERCANTILE EXCHANGE",),
31 "GBP": ("BRITISH POUND STERLING - CHICAGO MERCANTILE EXCHANGE", "BRITISH POUND - CHICAGO MERCANTILE EXCHANGE"),
32 "AUD": ("AUSTRALIAN DOLLAR - CHICAGO MERCANTILE EXCHANGE",),
33 "CAD": ("CANADIAN DOLLAR - CHICAGO MERCANTILE EXCHANGE",),
34 "CHF": ("SWISS FRANC - CHICAGO MERCANTILE EXCHANGE",),
35 "NZD": ("NEW ZEALAND DOLLAR - CHICAGO MERCANTILE EXCHANGE", "NZ DOLLAR - CHICAGO MERCANTILE EXCHANGE"),
36 "UST10": ("10-YEAR U.S. TREASURY NOTES - CHICAGO BOARD OF TRADE", "UST 10Y NOTE - CHICAGO BOARD OF TRADE"),
37 "SPX": ("E-MINI S&P 500 STOCK INDEX - CHICAGO MERCANTILE EXCHANGE", "E-MINI S&P 500 - CHICAGO MERCANTILE EXCHANGE"),
38}
39_KEY_BY_NAME = {name: key for key, names in MARKETS.items() for name in names}
42def parse_annual_text(text: str) -> list[dict]:
43 """Rows of one `annual.txt`, for the markets above: {report_date, publication_date, market, net_pct_oi}. A row with a
44 missing or zero open interest is dropped."""
45 rows: list[dict] = []
46 for row in csv.DictReader(io.StringIO(text)):
47 key = _KEY_BY_NAME.get(str(row.get("Market and Exchange Names", "")).strip())
48 if key is None:
49 continue
50 try:
51 open_interest = float(row["Open Interest (All)"])
52 long_positions = float(row["Noncommercial Positions-Long (All)"])
53 short_positions = float(row["Noncommercial Positions-Short (All)"])
54 report = date.fromisoformat(str(row["As of Date in Form YYYY-MM-DD"]).strip())
55 except (KeyError, TypeError, ValueError):
56 continue
57 if open_interest <= 0.0:
58 continue
59 rows.append({
60 "report_date": report.isoformat(),
61 "publication_date": (report + timedelta(days=PUBLICATION_LAG_DAYS)).isoformat(),
62 "market": key,
63 "net_pct_oi": (long_positions - short_positions) / open_interest,
64 })
65 return rows
68def parse_zip_bytes(payload: bytes) -> list[dict]:
69 """Rows of the first text file in a CFTC Commitments of Traders zip, or [] when it holds none."""
70 with zipfile.ZipFile(io.BytesIO(payload)) as archive:
71 name = next((item for item in archive.namelist() if item.lower().endswith(".txt")), None)
72 return parse_annual_text(archive.read(name).decode("latin-1")) if name else []
75def _download(url: str) -> bytes:
76 import requests
78 response = requests.get(url, timeout=120, headers={"User-Agent": "AetherQuantResearch/6.5 (github.com/leon1706-lol/Aether-quant)"})
79 response.raise_for_status()
80 return response.content
83def fetch_years(years: Iterable[int], fetch_fn: Callable[[str], bytes] = _download) -> list[dict]:
84 rows: list[dict] = []
85 for year in years:
86 rows.extend(parse_zip_bytes(fetch_fn(URL.format(year=year))))
87 return sorted(rows, key=lambda row: (row["report_date"], row["market"]))
90def write_positioning(rows: list[dict], path: Path = OUTPUT) -> None:
91 with Path(path).open("w", newline="\n", encoding="utf-8") as handle:
92 writer = csv.DictWriter(handle, fieldnames=["report_date", "publication_date", "market", "net_pct_oi"], lineterminator="\n")
93 writer.writeheader()
94 for row in rows:
95 writer.writerow({**row, "net_pct_oi": f"{row['net_pct_oi']:.6f}"})
98def read_positioning(path: Path = OUTPUT) -> pd.DataFrame:
99 """Read the cached CFTC positioning table, with its dates and market as strings."""
100 return pd.read_csv(path, dtype={"report_date": str, "publication_date": str, "market": str})
103def change_by_session(positioning: pd.DataFrame, sessions: list[str], weeks: int = CHANGE_WEEKS) -> pd.DataFrame:
104 """session x market: the `weeks`-report change in net positioning, as known at each session's close. A report
105 published on date P (after the close) is usable on the first session after P."""
106 frame = positioning.sort_values("report_date")
107 pivot = frame.pivot_table(index="publication_date", columns="market", values="net_pct_oi", aggfunc="last").sort_index()
108 change = pivot - pivot.shift(weeks)
109 union = change.reindex(sorted(set(change.index) | set(sessions))).ffill()
110 # shift(1) over the union: a row published on a session date is first read on the next entry
111 return union.shift(1).reindex(sessions)
114def fx_pair_scores(change: pd.DataFrame, pairs: Iterable[str]) -> pd.DataFrame:
115 """Each pair's score: the change in speculators' positioning in its base currency minus that in its quote currency
116 (the dollar has no contract of its own and counts as zero)."""
117 out = {}
118 for pair in pairs:
119 base, quote = pair[:3], pair[3:]
120 first = change.get(base, 0.0 if base == "USD" else np.nan)
121 second = change.get(quote, 0.0 if quote == "USD" else np.nan)
122 out[pair] = first - second
123 return pd.DataFrame(out, index=change.index)
126def macro_scores(change: pd.DataFrame) -> pd.DataFrame:
127 """Direction for the index and the bond ETFs from the S&P and 10-year contracts."""
128 return pd.DataFrame(
129 {"SPY": np.sign(change["SPX"]), "IEF": np.sign(change["UST10"]), "TLT": np.sign(change["UST10"])}, index=change.index
130 )
133def main(argv: list[str] | None = None) -> int:
134 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
135 parser.add_argument("--apply", action="store_true", help="download and write; without it, only prints what would be done")
136 parser.add_argument("--start-year", type=int, default=2005)
137 parser.add_argument("--end-year", type=int, default=date.today().year)
138 args = parser.parse_args(argv)
139 years = range(args.start_year, args.end_year + 1)
140 if not args.apply:
141 print(f"would fetch {len(list(years))} years into {OUTPUT}")
142 return 0
143 rows = fetch_years(years)
144 write_positioning(rows)
145 print(f"{len(rows)} rows, {rows[0]['report_date']}..{rows[-1]['report_date']} -> {OUTPUT}")
146 return 0
149if __name__ == "__main__":
150 raise SystemExit(main())