Download source/proxy_eval/tasks/finance.py from rca-umb/five-desks-control: direct link, hf CLI and curl.
- Browser
- Download file 7.57 kB
-
https://huggingface.co/datasets/rca-umb/five-desks-control/resolve/main/source/proxy_eval/tasks/finance.py
- Command line
-
hf download hf://datasets/rca-umb/five-desks-control/source/proxy_eval/tasks/finance.py
-
curl -L -o finance.py https://huggingface.co/datasets/rca-umb/five-desks-control/resolve/main/source/proxy_eval/tasks/finance.py
7.57 kB
| """Finance: answer an accounts-receivable question by querying a read-only SQLite database.""" | |
| import datetime as dt | |
| import math | |
| import sqlite3 | |
| from typing import Any, Literal | |
| from pydantic import Field | |
| from ..core import Action, ProxyTask, Step, clip | |
| CUSTOMERS = ["Arcturus Labs", "Birchwood Foods", "Cobalt Freight", "Delta Optics", "Evergreen Clinics", | |
| "Fjord Marine", "Granite Legal", "Helios Solar"] | |
| FX = {"USD": 1.0, "EUR": 1.08, "GBP": 1.27, "CAD": 0.73} | |
| class LedgerAction(Action): | |
| type: Literal["query", "answer"] = Field( | |
| description="query: run one read-only SQL statement (SQLite) in `sql`. answer: submit `answer`, which " | |
| "ends the episode.") | |
| sql: str = Field(default="", description="A single SELECT statement.") | |
| answer: dict[str, Any] = Field(default_factory=dict, description="Final answer object.") | |
| class Receivables(ProxyTask): | |
| family = "finance-receivables" | |
| domain = "finance-economics" | |
| Action = LedgerAction | |
| max_steps = 10 | |
| finish_action = {"type": "answer", "answer": {}} | |
| def setup(self): | |
| r = self.rng | |
| self.as_of = dt.date(2026, 9, 30) | |
| self.variant = self.seed % 2 | |
| self.db = sqlite3.connect(":memory:", check_same_thread=False) | |
| c = self.db | |
| c.executescript(""" | |
| CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, country TEXT); | |
| CREATE TABLE invoices (id INTEGER PRIMARY KEY, customer_id INTEGER, issued TEXT, due TEXT, | |
| amount REAL, currency TEXT, status TEXT); | |
| CREATE TABLE payments (id INTEGER PRIMARY KEY, invoice_id INTEGER, paid_on TEXT, amount REAL); | |
| CREATE TABLE fx_rates (currency TEXT PRIMARY KEY, usd_per_unit REAL); | |
| """) | |
| for i, name in enumerate(CUSTOMERS, 1): | |
| c.execute("INSERT INTO customers VALUES (?,?,?)", (i, name, r.choice(["US", "DE", "UK", "CA"]))) | |
| c.executemany("INSERT INTO fx_rates VALUES (?,?)", FX.items()) | |
| inv_id, pay_id = 1000, 1 | |
| self.invoices, self.payments = [], [] | |
| for _ in range(r.randint(40, 60)): | |
| cust = r.randint(1, len(CUSTOMERS)) | |
| issued = self.as_of - dt.timedelta(days=r.randint(5, 200)) | |
| due = issued + dt.timedelta(days=r.choice([30, 45, 60])) | |
| amount = round(r.uniform(400, 25000), 2) | |
| cur = r.choice(list(FX)) | |
| status = r.choices(["open", "void"], [0.92, 0.08])[0] | |
| inv_id += 1 | |
| self.invoices.append((inv_id, cust, issued.isoformat(), due.isoformat(), amount, cur, status)) | |
| if status == "void": | |
| continue | |
| paid = r.choice([0, 0, amount, round(amount * r.uniform(0.2, 0.8), 2)]) | |
| if paid: | |
| when = issued + dt.timedelta(days=r.randint(3, 120)) | |
| if when <= self.as_of: | |
| self.payments.append((pay_id, inv_id, when.isoformat(), paid)) | |
| pay_id += 1 | |
| if r.random() < 0.12: # an accidental duplicate payment a day or two later | |
| self.payments.append((pay_id, inv_id, (when + dt.timedelta(days=r.randint(1, 2))).isoformat(), paid)) | |
| pay_id += 1 | |
| c.executemany("INSERT INTO invoices VALUES (?,?,?,?,?,?,?)", self.invoices) | |
| c.executemany("INSERT INTO payments VALUES (?,?,?,?)", self.payments) | |
| c.execute("PRAGMA query_only = ON") | |
| self.answer = self._truth() | |
| def _truth(self): | |
| paid = {} | |
| for _, inv, _, amt in self.payments: | |
| paid[inv] = paid.get(inv, 0) + amt | |
| if self.variant == 0: | |
| per_cust = {} | |
| for inv, cust, _, due, amt, cur, status in self.invoices: | |
| overdue_days = (self.as_of - dt.date.fromisoformat(due)).days | |
| bal = amt - paid.get(inv, 0) | |
| if status == "open" and overdue_days > 60 and bal > 0.005: | |
| per_cust[cust] = per_cust.get(cust, 0) + bal * FX[cur] | |
| assert len(per_cust) >= 2 | |
| top = max(per_cust, key=per_cust.get) | |
| ranked = sorted(per_cust.values()) | |
| assert ranked[-1] - ranked[-2] > 50 | |
| self.question = ("As of 2026-09-30, what is the total outstanding balance in USD of open (not void) " | |
| "invoices more than 60 days past their due date, and which customer owes the most of " | |
| "it? Outstanding = invoice amount minus all payments on it; convert with fx_rates.") | |
| return {"total_usd": round(sum(per_cust.values()), 2), "top_customer": CUSTOMERS[top - 1]} | |
| groups = {} | |
| for pid, inv, when, amt in self.payments: | |
| groups.setdefault((inv, amt), []).append(dt.date.fromisoformat(when)) | |
| dups, excess = 0, 0.0 | |
| cur = {i[0]: i[5] for i in self.invoices} | |
| for (inv, amt), dates in groups.items(): | |
| dates.sort() | |
| for prev, nxt in zip(dates, dates[1:]): | |
| if (nxt - prev).days <= 3: | |
| dups += 1 | |
| excess += amt * FX[cur[inv]] | |
| assert dups >= 1 | |
| self.question = ("Find duplicate payments: a payment is a duplicate when the same invoice already received " | |
| "a payment of exactly the same amount within the previous 3 days. How many duplicate " | |
| "payments are there, and what is their total in USD (convert with fx_rates)?") | |
| return {"duplicate_count": dups, "duplicate_total_usd": round(excess, 2)} | |
| def reset(self): | |
| keys = ", ".join(f'"{k}"' for k in self.answer) | |
| return {"output": f"Accounts receivable database (SQLite, read-only). Tables: customers, invoices, " | |
| f"payments, fx_rates. {self.question} Answer with an object with keys {keys}; amounts " | |
| f"are checked to the cent (within $1.00).", | |
| "queries_left": self.max_steps} | |
| def act(self, a): | |
| left = self.max_steps - self.steps | |
| if a.type == "query": | |
| try: | |
| cur = self.db.execute(a.sql) | |
| cols = [d[0] for d in cur.description or []] | |
| rows = cur.fetchmany(80) | |
| more = len(cur.fetchall()) | |
| text = "\t".join(cols) + "\n" + "\n".join("\t".join(map(str, row)) for row in rows) | |
| if more: | |
| text += f"\n... {more} more rows" | |
| except sqlite3.Error as exc: | |
| text = f"SQL error: {exc}" | |
| return Step({"output": clip(text, 3500), "queries_left": left}) | |
| got = {str(k).lower(): v for k, v in a.answer.items()} | |
| ok = True | |
| for key, want in self.answer.items(): | |
| val = got.get(key.lower()) | |
| if isinstance(want, str): | |
| ok &= isinstance(val, str) and val.strip().lower() == want.lower() | |
| elif isinstance(want, int): | |
| ok &= isinstance(val, (int, float)) and not isinstance(val, bool) and val == want | |
| else: | |
| try: | |
| num = float(str(val).replace("$", "").replace(",", "")) | |
| ok &= math.isfinite(num) and abs(num - want) <= 1.0 | |
| except ValueError: | |
| ok = False | |
| return Step({"output": "Answer recorded.", "queries_left": 0}, True, 1.0 if ok else 0.0) | |
| def oracle(self): | |
| return [{"type": "query", "sql": "SELECT name FROM sqlite_master"}, | |
| {"type": "answer", "answer": self.answer}] | |