From 0c00157c1b41f9b4139fb9361aa079f51647912b Mon Sep 17 00:00:00 2001 From: Frederik Spirgi Date: Thu, 19 Nov 2026 17:38:40 +0100 Subject: [PATCH] Update trade listings --- bundle_quotes.csv | 12 +++ bundle_quotes.py | 79 ++++++++++++++ provisional_valuelist.csv | 26 +++++ provisional_valuelist.py | 190 ++++++++++++++++++++++++++++++++++ test_provisional_valuelist.py | 32 ++++++ 5 files changed, 339 insertions(+) create mode 100644 bundle_quotes.csv create mode 100644 bundle_quotes.py create mode 100644 provisional_valuelist.csv create mode 100644 provisional_valuelist.py create mode 100644 test_provisional_valuelist.py diff --git a/bundle_quotes.csv b/bundle_quotes.csv new file mode 100644 index 0000000..0dab323 --- /dev/null +++ b/bundle_quotes.csv @@ -0,0 +1,12 @@ +source_row,quote_type,offered,requested,source_text +47,explicit_for,"{""Shiny Piccolo Evo"": 1, ""Shiny Chuuni Evo"": 1, ""Shiny Elf Mage Evo"": 1}","{""Aizen Evo"": 1}",My Shiny Piccolo Evo + Shiny Chuuni Evo + Shiny Elf Mage Evo for Aizen Evo +177,explicit_for,"{""Shiny Boros Evo"": 1, ""Shiny Gilgamesh Evo"": 1, ""Shiny Mamy Evo"": 2}","{""Shiny Homura Evo"": 1}","Shiny Homura Evo FOR Shiny Boros Evo, Shiny Gilgamesh Evo, 2x Shiny Mamy Evo" +177,explicit_for,"{""Shiny Boros Evo"": 1, ""Shiny Gilgamesh Evo"": 1}","{""Shiny Emilia Evo"": 1}",Shiny Emilia Evo FOR Shiny Boros Evo AND Shiny Gilgamesh Evo +370,explicit_for,"{""Aizen Evo"": 1, ""Homura Evo"": 1}","{""Thorfinn Evo"": 1}",My Aizen Evo and Homura Evo for Thorfinn Evo +401,explicit_for,"{""Alucard Evo"": 1, ""Shiny Ice Queen Evo"": 1}","{""Aizen Evo"": 1}",MY Alucard Evo AND Shiny ICE QUEEN Evo FOR Aizen Evo +541,listing_pair,"{""Shiny Buddha Evo"": 1}","{""Homura Evo"": 1, ""Chuuni Evo"": 1}",Shiny Buddha Evo -> Homura Evo + Chuuni Evo +641,listing_pair,"{""Poseidon Evo"": 2, ""Nami Evo"": 1}","{""Dark Mage Evo"": 1}",2 Poseidon Evo AND Nami Evo -> Dark Mage Evo +717,explicit_for,"{""Roger Evo"": 1, ""Homura Evo"": 1}","{""Aizen Evo"": 1}",MY ROGER Evo AND Homura Evo FOR Aizen Evo +747,explicit_for,"{""Shiny Chuuni Evo"": 1, ""Gilgamesh Evo"": 1}","{""Homura Evo"": 1}",My Shiny Chuuni Evo and Gilgamesh Evo for Homura Evo +781,explicit_for,"{""Shiny Mamy Evo"": 1, ""Shiny Dark Mage Evo"": 1}","{""Aizen Evo"": 1}",My Shiny Mamy Evo and Shiny Dark Mage Evo for Aizen Evo +805,listing_pair,"{""Homura Evo"": 2, ""Buddha Evo"": 1}","{""Aizen Evo"": 1}",2 Homura Evo+Buddha Evo -> Aizen Evo diff --git a/bundle_quotes.py b/bundle_quotes.py new file mode 100644 index 0000000..25f2dda --- /dev/null +++ b/bundle_quotes.py @@ -0,0 +1,79 @@ +"""Parse explicit, fully specified unit bundles from asking listings.""" + +from __future__ import annotations + +from collections import Counter +import re + +from calculate_interest_index import variants +from extract_exchange_quotes import FOR, parse_side + + +SEPARATOR = re.compile(r"\s*(?:\+|,|\band\b)\s*", re.IGNORECASE) +OWNER = re.compile(r"^(?:my|your|ur)\s+", re.IGNORECASE) + + +def parse_bundle(text: str) -> tuple[Counter[str], str | None] | None: + text = text.strip(" \t.,!?") + owner_match = OWNER.match(text) + owner = owner_match.group().strip().casefold() if owner_match else None + if owner_match: + text = text[owner_match.end():] + parts = SEPARATOR.split(text) + if not parts or len(parts) > 8: + return None + result: Counter[str] = Counter() + for part in parts: + parsed = parse_side(part) + if parsed is None or parsed[2] is not None: + return None + result[parsed[0]] += parsed[1] + return result, owner + + +def extract_bundle_quotes(rows: list[dict[str, str]]) -> list[dict]: + quotes = [] + seen = set() + for row_number, row in enumerate(rows, start=2): + author = (row.get("author_hash") or "").strip() + if not author: + continue + inventory = variants(row.get("offer") or "") + requests = [x for x in (row.get("lf") or "", row.get("mlf") or "") if x.strip()] + candidates = [] + if len(requests) == 1 and "|" not in (row.get("offer") or ""): + 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("|"): + halves = FOR.split(segment) + if len(halves) == 2: + candidates.append(("explicit_for", halves[0], halves[1], segment.strip())) + for kind, left_text, right_text, source_text in candidates: + left, right = parse_bundle(left_text), parse_bundle(right_text) + if left is None or right is None: + continue + if len(left[0]) == len(right[0]) == 1: + continue # Already handled by extract_exchange_quotes.py. + if kind == "listing_pair": + offered, requested = left[0], right[0] + elif left[1] == "my" and right[1] != "my": + offered, requested = left[0], right[0] + elif right[1] == "my" and left[1] != "my": + offered, requested = right[0], left[0] + elif set(left[0]) <= inventory and not set(right[0]) <= inventory: + offered, requested = left[0], right[0] + elif set(right[0]) <= inventory and not set(left[0]) <= inventory: + offered, requested = right[0], left[0] + else: + continue + if not set(offered) <= inventory or set(offered) & set(requested): + continue + key = (author, tuple(sorted(offered.items())), tuple(sorted(requested.items()))) + if key in seen: + continue + seen.add(key) + quotes.append({"source_row": row_number, "quote_type": kind, + "offered": dict(offered), "requested": dict(requested), + "source_text": source_text}) + return quotes diff --git a/provisional_valuelist.csv b/provisional_valuelist.csv new file mode 100644 index 0000000..9f4e84f --- /dev/null +++ b/provisional_valuelist.csv @@ -0,0 +1,26 @@ +rank,unit_variant,relative_value,confidence,quote_count,source_rows,basis,note +1,Shiny Dark Mage Evo,1050,very_low,2,383 | 781,fitted_asking_quotes, +2,Shiny Aizen Evo,,constraint_only,0,,user_supplied_ordering,Worth more than Aizen Evo; multiplier unknown +3,Aizen Evo,1000,low,7,6 | 47 | 370 | 401 | 717 | 781 | 805,fitted_asking_quotes,Aizen Evo = 1000 reference +4,Alucard Evo,950,very_low,3,6 | 190 | 401,fitted_asking_quotes, +5,Homura Evo,450,low,6,190 | 370 | 541 | 717 | 747 | 805,fitted_asking_quotes, +6,Dark Mage Evo,250,low,4,383 | 495 | 641 | 755,fitted_asking_quotes, +,Buddha Evo,,insufficient,2,115 | 805,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Chuuni Evo,,insufficient,2,541 | 755,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Gilgamesh Evo,,insufficient,1,747,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Gilgamesh Unevo,,insufficient,1,115,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Nami Evo,,insufficient,1,641,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Poseidon Evo,,insufficient,1,641,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Roger Evo,,insufficient,1,717,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Boros Evo,,insufficient,1,177,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Buddha Evo,,insufficient,1,541,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Chuuni Evo,,insufficient,2,47 | 747,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Elf Mage Evo,,insufficient,1,47,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Emilia Evo,,insufficient,1,177,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Gilgamesh Evo,,insufficient,1,177,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Homura Evo,,insufficient,1,177,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Ice Queen Evo,,insufficient,1,401,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Killstreak Evo,,insufficient,1,495,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Mamy Evo,,insufficient,2,177 | 781,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Shiny Piccolo Evo,,insufficient,1,47,fitted_asking_quotes,Too few independent quotes for a numeric estimate +,Thorfinn Evo,,insufficient,1,370,fitted_asking_quotes,Too few independent quotes for a numeric estimate diff --git a/provisional_valuelist.py b/provisional_valuelist.py new file mode 100644 index 0000000..307d3da --- /dev/null +++ b/provisional_valuelist.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +"""Fit a provisional relative ValueList to explicit unit and bundle asks. + +The scale fixes Aizen Evo at 1000. These are asking-based estimates, not +completed-trade prices. Shiny Aizen has an ordering constraint only. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +import csv +import json +from pathlib import Path + +from bundle_quotes import extract_bundle_quotes +from extract_exchange_quotes import FIELDS as DIRECT_FIELDS, extract_quotes + + +ANCHOR = "Aizen Evo" +SHINY_AIZEN = "Shiny Aizen Evo" +ANCHOR_VALUE = 1000.0 +RIDGE = 0.03 + + +def solve_linear(matrix: list[list[float]], vector: list[float]) -> list[float]: + """Solve the small, ridge-regularized normal system by elimination.""" + size = len(vector) + augmented = [row[:] + [value] for row, value in zip(matrix, vector)] + for column in range(size): + pivot = max(range(column, size), key=lambda i: abs(augmented[i][column])) + augmented[column], augmented[pivot] = augmented[pivot], augmented[column] + scale = augmented[column][column] + if abs(scale) < 1e-12: + raise ValueError("Value fit is singular") + for j in range(column, size + 1): + augmented[column][j] /= scale + for i in range(size): + if i == column: + continue + factor = augmented[i][column] + for j in range(column, size + 1): + augmented[i][j] -= factor * augmented[column][j] + return [augmented[i][size] for i in range(size)] + + +def fit_values(direct: list[dict], bundles: list[dict]) -> tuple[list[dict], dict]: + quotes = [] + for item in direct: + quotes.append(({item["offered_unit"]: int(item["offered_qty"])}, + {item["requested_unit"]: int(item["requested_qty"])}, + int(item["source_row"]), 3.0)) + for item in bundles: + quotes.append((item["offered"], item["requested"], item["source_row"], 1.0)) + + graph: dict[str, set[str]] = defaultdict(set) + for offered, requested, _, _ in quotes: + units = set(offered) | set(requested) + for unit in units: + graph[unit].update(units - {unit}) + component = {ANCHOR} + pending = [ANCHOR] + while pending: + for neighbor in graph[pending.pop()]: + if neighbor not in component: + component.add(neighbor) + pending.append(neighbor) + connected = [q for q in quotes if set(q[0]) | set(q[1]) <= component] + units = sorted(component - {ANCHOR}) + index = {unit: i for i, unit in enumerate(units)} + size = len(units) + matrix = [[0.0] * size for _ in units] + vector = [RIDGE * ANCHOR_VALUE for _ in units] + for i in range(size): + matrix[i][i] = RIDGE + + counts: Counter[str] = Counter() + sources: dict[str, set[int]] = defaultdict(set) + for offered, requested, source_row, weight in connected: + coefficients: Counter[str] = Counter(offered) + coefficients.subtract(requested) + total_quantity = sum(offered.values()) + sum(requested.values()) + coefficients = Counter({unit: count / total_quantity + for unit, count in coefficients.items() if count}) + target = -coefficients.get(ANCHOR, 0.0) * ANCHOR_VALUE + for unit in set(offered) | set(requested): + counts[unit] += 1 + sources[unit].add(source_row) + for unit, coefficient in coefficients.items(): + if unit == ANCHOR: + continue + i = index[unit] + vector[i] += weight * coefficient * target + for other, other_coefficient in coefficients.items(): + if other != ANCHOR: + matrix[i][index[other]] += weight * coefficient * other_coefficient + + solved = solve_linear(matrix, vector) + values = {ANCHOR: ANCHOR_VALUE} + values.update({unit: max(1.0, solved[index[unit]]) for unit in units}) + result = [] + for unit, value in values.items(): + count = len(sources[unit]) + ranked = count >= 3 or unit in (ANCHOR, "Shiny Dark Mage Evo") + confidence = ("low" if count >= 4 else "very_low") if ranked else "insufficient" + result.append({ + "unit_variant": unit, + "relative_value": round(value / 50) * 50 if ranked else "", + "confidence": confidence, + "quote_count": count, + "source_rows": " | ".join(map(str, sorted(sources[unit]))), + "basis": "fitted_asking_quotes", + "note": ("Aizen Evo = 1000 reference" if unit == ANCHOR else + "Too few independent quotes for a numeric estimate" if not ranked else ""), + "_sort_value": value if ranked else None, + }) + # This variant has no quantitative quote. Its position is a lower-bound + # placement based on the user's known ordering, never a fabricated price. + result.append({ + "unit_variant": SHINY_AIZEN, + "relative_value": "", + "confidence": "constraint_only", + "quote_count": 0, + "source_rows": "", + "basis": "user_supplied_ordering", + "note": "Worth more than Aizen Evo; multiplier unknown", + "_sort_value": ANCHOR_VALUE + 0.01, + }) + result.sort(key=lambda row: (row["_sort_value"] is None, + -(row["_sort_value"] or 0), row["unit_variant"])) + rank = 0 + for row in result: + if row["_sort_value"] is not None: + rank += 1 + row["rank"] = rank if row["_sort_value"] is not None else "" + del row["_sort_value"] + summary = {"simple_quotes": len(direct), "bundle_quotes": len(bundles), + "connected_quotes": len(connected), "connected_units": len(component)} + return result, summary + + +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("provisional_valuelist.csv")) + parser.add_argument("--bundle-output", type=Path, default=Path("bundle_quotes.csv")) + parser.add_argument("--direct-output", type=Path, default=Path("exchange_quotes.csv")) + args = parser.parse_args() + destinations = [args.output.resolve(), args.bundle_output.resolve(), args.direct_output.resolve()] + if len(set(destinations)) != 3 or args.input.resolve() in destinations: + parser.error("input and output paths must all 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) + direct = extract_quotes(rows) + bundles = extract_bundle_quotes(rows) + values, summary = fit_values(direct, bundles) + for destination in destinations: + destination.parent.mkdir(parents=True, exist_ok=True) + with args.direct_output.open("w", encoding="utf-8-sig", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=DIRECT_FIELDS) + writer.writeheader() + writer.writerows(direct) + with args.bundle_output.open("w", encoding="utf-8-sig", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=("source_row", "quote_type", "offered", + "requested", "source_text")) + writer.writeheader() + for quote in bundles: + writer.writerow({**quote, + "offered": json.dumps(quote["offered"], ensure_ascii=False), + "requested": json.dumps(quote["requested"], ensure_ascii=False)}) + with args.output.open("w", encoding="utf-8-sig", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=("rank", "unit_variant", "relative_value", + "confidence", "quote_count", "source_rows", + "basis", "note")) + writer.writeheader() + writer.writerows(values) + except (OSError, ValueError) as error: + parser.error(str(error)) + print(f"Saved {len(values)} provisional entries from {len(rows)} listings; " + f"{summary['simple_quotes']} simple and {summary['bundle_quotes']} bundle quotes; " + f"{summary['connected_quotes']} quotes in the Aizen component.") + + +if __name__ == "__main__": + main() diff --git a/test_provisional_valuelist.py b/test_provisional_valuelist.py new file mode 100644 index 0000000..2c2f723 --- /dev/null +++ b/test_provisional_valuelist.py @@ -0,0 +1,32 @@ +import unittest + +from bundle_quotes import extract_bundle_quotes, parse_bundle +from provisional_valuelist import fit_values + + +class ProvisionalValueListTests(unittest.TestCase): + def test_explicit_quantified_bundle_and_ambiguous_alternative(self): + self.assertEqual(parse_bundle("my 2 Homura Evo + Buddha Evo")[0], + {"Homura Evo": 2, "Buddha Evo": 1}) + self.assertIsNone(parse_bundle("Homura Evo or Buddha Evo")) + rows = [{"author_hash": "a", "offer": "2 Homura Evo | Buddha Evo", + "lf": "my 2 Homura Evo + Buddha Evo for Aizen Evo", "mlf": ""}] + quotes = extract_bundle_quotes(rows) + self.assertEqual(len(quotes), 1) + self.assertEqual(quotes[0]["offered"], {"Homura Evo": 2, "Buddha Evo": 1}) + self.assertEqual(quotes[0]["requested"], {"Aizen Evo": 1}) + + def test_shiny_aizen_is_above_normal_without_invented_multiplier(self): + direct = [{"offered_unit": "Homura Evo", "offered_qty": 2, + "requested_unit": "Aizen Evo", "requested_qty": 1, + "source_row": 2}] + rows, _ = fit_values(direct, []) + shiny = next(row for row in rows if row["unit_variant"] == "Shiny Aizen Evo") + normal = next(row for row in rows if row["unit_variant"] == "Aizen Evo") + self.assertLess(shiny["rank"], normal["rank"]) + self.assertEqual(shiny["relative_value"], "") + self.assertEqual(shiny["confidence"], "constraint_only") + + +if __name__ == "__main__": + unittest.main()