#!/usr/bin/env python3 """Extract conservative unit-for-unit asking quotes from trades.csv. These are proposed exchanges, not completed trades or verified unit values. Ambiguous inventories, wish lists, quality modifiers, and adds are excluded. """ from __future__ import annotations import argparse import csv from pathlib import Path import re from calculate_interest_index import UNIT_PATTERN, variants QUANTITY = re.compile(r"^(?P\d+)\s*x?\s+", re.IGNORECASE) OWNER = re.compile(r"^(?Pmy|your|ur)\s+", re.IGNORECASE) FOR = re.compile(r"\bfor\b", re.IGNORECASE) FIELDS = ("source_row", "quote_type", "offered_unit", "offered_qty", "requested_unit", "requested_qty", "requested_units_per_offered_unit", "source_text") def parse_side(text: str) -> tuple[str, int, str | None] | None: """Accept only an exact named variant with an optional owner and quantity.""" text = text.strip(" \t.,!?") owner_match = OWNER.match(text) owner = owner_match.group("owner").casefold() if owner_match else None if owner_match: text = text[owner_match.end():] quantity_match = QUANTITY.match(text) quantity = int(quantity_match.group("count")) if quantity_match else 1 if quantity_match: text = text[quantity_match.end():] if quantity < 1 or UNIT_PATTERN.fullmatch(text) is None: return None unit = next(iter(variants(text))) return unit, quantity, owner def extract_quotes(rows: list[dict[str, str]]) -> list[dict[str, str | int | float]]: quotes = [] seen: set[tuple[str, str, int, str, int]] = set() for row_number, row in enumerate(rows, start=2): author = (row.get("author_hash") or "").strip() if not author: continue offered_inventory = variants(row.get("offer") or "") candidates = [] requests = [value for value in (row.get("lf") or "", row.get("mlf") or "") if value.strip()] if len(requests) == 1: candidates.append(("listing_pair", row.get("offer") or "", requests[0], f"{row.get('offer') or ''} -> {requests[0]}")) for request in requests: for segment in request.split("|"): parts = FOR.split(segment) if len(parts) == 2: candidates.append(("explicit_for", parts[0], parts[1], segment.strip())) for kind, left_text, right_text, source_text in candidates: left, right = parse_side(left_text), parse_side(right_text) if left is None or right is None or left[0] == right[0]: continue if kind == "listing_pair": offered, requested = left, right elif left[2] == "my" and right[2] != "my": offered, requested = left, right elif right[2] == "my" and left[2] != "my": offered, requested = right, left elif left[0] in offered_inventory and right[0] not in offered_inventory: offered, requested = left, right elif right[0] in offered_inventory and left[0] not in offered_inventory: offered, requested = right, left else: continue if offered[0] not in offered_inventory: continue key = (author, offered[0], offered[1], requested[0], requested[1]) if key in seen: continue seen.add(key) quotes.append({ "source_row": row_number, "quote_type": kind, "offered_unit": offered[0], "offered_qty": offered[1], "requested_unit": requested[0], "requested_qty": requested[1], "requested_units_per_offered_unit": round(requested[1] / offered[1], 4), "source_text": source_text, }) return quotes def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, default=Path("trades.csv")) parser.add_argument("--output", type=Path, default=Path("exchange_quotes.csv")) args = parser.parse_args() if args.input.resolve() == args.output.resolve(): parser.error("input and output paths must differ") try: with args.input.open(encoding="utf-8-sig", newline="") as stream: reader = csv.DictReader(stream) required = {"offer", "lf", "mlf", "author_hash"} if not required.issubset(reader.fieldnames or []): parser.error(f"CSV needs columns: {', '.join(sorted(required))}") rows = list(reader) quotes = extract_quotes(rows) args.output.parent.mkdir(parents=True, exist_ok=True) with args.output.open("w", encoding="utf-8-sig", newline="") as stream: writer = csv.DictWriter(stream, fieldnames=FIELDS) writer.writeheader() writer.writerows(quotes) except OSError as error: parser.error(str(error)) print(f"Saved {len(quotes)} conservative asking quotes from {len(rows)} listings to {args.output}.") if __name__ == "__main__": main()