diff --git a/MARKET_EVIDENCE.md b/MARKET_EVIDENCE.md new file mode 100644 index 0000000..c04bc27 --- /dev/null +++ b/MARKET_EVIDENCE.md @@ -0,0 +1,37 @@ +# Market evidence from trades.csv + +`trades.csv` contains asking listings. Its `offer` column is often an entire +inventory, while `lf` and `mlf` can contain several alternatives. Pairing all +items across those columns would invent exchange rates that nobody quoted. + +Run `py -B extract_exchange_quotes.py` to regenerate `exchange_quotes.csv`. +This reads only exact unit-for-unit proposals: a single offered variant and a +single requested variant, with optional explicit quantities. It rejects +bundles, adds, alternatives, and quality descriptions. It also requires the +offered variant to appear in that listing's `offer` field and counts identical +quotes from an author once. The CSV keeps the source row and text for review. + +The current 835 listings yield 11 such asking quotes. They connect only small +groups of units, and each relation has too few independent quotes to claim a +market price. For example, one seller asks for five Dark Mage Evo in exchange +for one Shiny Dark Mage Evo; another asks for one Alucard Evo in exchange for +two Homura Evo. These are **proposed** ratios, not completed trades. + +Shiny Aizen Evo has no clean unit-for-unit quote against normal Aizen Evo in +this file. One listing asks for 900 rerolls for a Shiny Aizen Evo, and another +asks for unspecified "bulks" of normal Aizen Evo. Neither gives a reliable +conversion between the two variants. Shiny and normal variants must remain +separate in any future valuation model. The known ordering supplied by the +user is Shiny Aizen Evo > Aizen Evo; the CSV does not establish the multiplier. + +`interest_index.csv` is a separate demand-versus-supply report. Run +`py -B calculate_interest_index.py` to regenerate it. Its score is **not a +value**: it counts distinct authors requesting and offering each explicit Evo +or Unevo variant, requires at least 20 total mentions and five on each side, +then scales `(requested_by + 3) / (offered_by + 3)` to a median of 100. It +excludes `nlf`, quantities, reposts, and repeat mentions by an author. + +For a defensible relative ValueList, collect completed trades or several +independent, specific two-sided quotes per unit pair, including quantities, +variant, evolution, stat quality, and date. Then fit values only within a +connected network of comparable trades and show uncertainty for thin data. diff --git a/calculate_interest_index.py b/calculate_interest_index.py new file mode 100644 index 0000000..9cf0fd7 --- /dev/null +++ b/calculate_interest_index.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Build a market-interest index from trades.csv. + +This is a relative asking-interest index, not a price or a record of completed +trades. Only explicitly named Evo and Unevo units are compared. +""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import csv +from pathlib import Path +import re +from statistics import median + +from discord_trade_parser import KNOWN_UNIT_NAMES, normalize_unit_names + + +UNIT_NAMES = tuple( + name for name in KNOWN_UNIT_NAMES if name.casefold() != "shiny skull knight" +) +CANONICAL_NAMES = {name.casefold(): normalize_unit_names(name) for name in UNIT_NAMES} +UNIT_PATTERN = re.compile( + r"(?Shiny\s+)?(?P" + + "|".join(re.escape(name).replace(r"\ ", r"\s+") for name in UNIT_NAMES) + + r")\s+(?PEvo|Unevo)\b", + re.IGNORECASE, +) +MY_PREFIX = re.compile(r"\bmy\s+$", re.IGNORECASE) + + +def variants(text: str, *, request: bool = False) -> set[str]: + """Find explicit unit variants, counting each at most once per side.""" + found: set[str] = set() + for match in UNIT_PATTERN.finditer(text): + if request and MY_PREFIX.search(text[max(0, match.start() - 12):match.start()]): + continue + name = CANONICAL_NAMES[match.group("unit").casefold()] + shiny = "Shiny " if match.group("shiny") else "" + evolution = match.group("evolution").capitalize() + found.add(f"{shiny}{name} {evolution}") + return found + + +def calculate(input_path: Path, minimum_mentions: int = 20) -> tuple[list[dict], dict]: + if minimum_mentions < 1: + raise ValueError("minimum mentions must be positive") + + offered_by: dict[str, set[str]] = defaultdict(set) + requested_by: dict[str, set[str]] = defaultdict(set) + rows = 0 + authors: set[str] = set() + with input_path.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 []): + raise ValueError(f"CSV needs columns: {', '.join(sorted(required))}") + for row in reader: + rows += 1 + author = row["author_hash"].strip() + if not author: + # An untracked listing cannot be deduplicated reliably. + continue + authors.add(author) + for unit in variants(row["offer"]): + offered_by[unit].add(author) + for unit in variants(" | ".join((row["lf"], row["mlf"])), request=True): + requested_by[unit].add(author) + + candidates = [] + for unit in offered_by.keys() | requested_by.keys(): + supply = len(offered_by[unit]) + demand = len(requested_by[unit]) + if supply + demand < minimum_mentions or min(supply, demand) < 5: + continue + # Three mentions on either side shrink extreme ratios from small samples. + pressure = (demand + 3) / (supply + 3) + candidates.append((unit, supply, demand, pressure)) + + baseline = median(item[3] for item in candidates) if candidates else 1.0 + result = [ + { + "unit_variant": unit, + "interest_index": round(100 * pressure / baseline), + "requested_by": demand, + "offered_by": supply, + "total_mentions": demand + supply, + } + for unit, supply, demand, pressure in candidates + ] + result.sort(key=lambda item: (-item["interest_index"], -item["total_mentions"], item["unit_variant"])) + summary = { + "source_rows": rows, + "distinct_authors": len(authors), + "ranked_variants": len(result), + "minimum_mentions": minimum_mentions, + } + 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("interest_index.csv")) + parser.add_argument("--minimum-mentions", type=int, default=20) + args = parser.parse_args() + if args.input.resolve() == args.output.resolve(): + parser.error("input and output paths must differ") + try: + result, summary = calculate(args.input, args.minimum_mentions) + except (OSError, ValueError) as error: + parser.error(str(error)) + 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=[ + "unit_variant", "interest_index", "requested_by", "offered_by", "total_mentions" + ]) + writer.writeheader() + writer.writerows(result) + print(f"Saved {len(result)} variants to {args.output} from " + f"{summary['source_rows']} listings and {summary['distinct_authors']} authors.") + + +if __name__ == "__main__": + main() diff --git a/exchange_quotes.csv b/exchange_quotes.csv new file mode 100644 index 0000000..f039915 --- /dev/null +++ b/exchange_quotes.csv @@ -0,0 +1,12 @@ +source_row,quote_type,offered_unit,offered_qty,requested_unit,requested_qty,requested_units_per_offered_unit,source_text +6,explicit_for,Alucard Evo,1,Aizen Evo,1,1.0,MY Alucard Evo FOR Aizen Evo +65,explicit_for,Shiny Nagumo Evo,2,Alucard Unevo,1,0.5,2 Shiny Nagumo Evo for Alucard Unevo +115,explicit_for,Buddha Evo,1,Gilgamesh Unevo,1,1.0,Gilgamesh Unevo for my Buddha Evo +190,explicit_for,Homura Evo,2,Alucard Evo,1,0.5,2 Homura Evo FOR Alucard Evo +381,explicit_for,Shiny Siren Unevo,1,Shiny Elf Mage Unevo,1,1.0,My Shiny Siren Unevo for Shiny Elf Mage Unevo +383,listing_pair,Shiny Dark Mage Evo,1,Dark Mage Evo,5,5.0,Shiny Dark Mage Evo -> 5 Dark Mage Evo +495,listing_pair,Shiny Killstreak Evo,1,Dark Mage Evo,1,1.0,Shiny Killstreak Evo -> Dark Mage Evo +593,explicit_for,Shiny Cream Evo,1,Shiny Deer Tan Evo,1,1.0,Shiny Cream Evo for Shiny Deer Tan Evo +720,explicit_for,Shiny Siren Unevo,1,Shiny Elf Mage Unevo,1,1.0,My Shiny Siren Unevo for Shiny Elf Mage Unevo +755,listing_pair,Chuuni Evo,1,Dark Mage Evo,1,1.0,Chuuni Evo -> Dark Mage Evo +761,listing_pair,Shizo Evo,1,Rohan Evo,1,1.0,SHIZO Evo -> ROHAN Evo diff --git a/extract_exchange_quotes.py b/extract_exchange_quotes.py new file mode 100644 index 0000000..65c217c --- /dev/null +++ b/extract_exchange_quotes.py @@ -0,0 +1,123 @@ +#!/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() diff --git a/interest_index.csv b/interest_index.csv new file mode 100644 index 0000000..f914c47 --- /dev/null +++ b/interest_index.csv @@ -0,0 +1,21 @@ +unit_variant,interest_index,requested_by,offered_by,total_mentions +Aizen Evo,265,97,117,214 +Homura Evo,203,107,169,276 +Mamy Evo,201,9,16,25 +Shiny Homura Evo,176,7,15,22 +Shiny Cid Evo,167,7,16,23 +Alucard Evo,142,31,73,104 +Shiny Aizen Evo,141,5,15,20 +Shiny Dark Mage Evo,118,17,51,68 +Roger Evo,111,11,37,48 +Shiny Chuuni Evo,103,18,62,80 +Chuuni Evo,97,35,121,156 +Shiny Mamy Evo,82,6,32,38 +Dark Mage Evo,72,48,223,271 +Gilgamesh Evo,55,19,125,144 +Shiny Nagumo Evo,48,5,50,55 +Shiny Elf Mage Evo,47,6,58,64 +Poseidon Evo,43,8,79,87 +Buddha Evo,40,16,149,165 +Cid Evo,33,12,141,153 +Nagumo Evo,26,11,168,179 diff --git a/test_calculate_interest_index.py b/test_calculate_interest_index.py new file mode 100644 index 0000000..493281a --- /dev/null +++ b/test_calculate_interest_index.py @@ -0,0 +1,42 @@ +import csv +from io import StringIO +from pathlib import Path +import unittest +from unittest.mock import patch + +from calculate_interest_index import calculate, variants + + +class ValueListTests(unittest.TestCase): + def test_variant_extraction_keeps_shiny_separate_and_normalizes_case(self): + self.assertEqual( + variants("ROGER Evo | Shiny Roger Evo | Roger Unevo"), + {"Roger Evo", "Shiny Roger Evo", "Roger Unevo"}, + ) + self.assertEqual( + variants("my Aizen Evo for Homura Evo", request=True), + {"Homura Evo"}, + ) + + def test_counts_authors_once_and_excludes_nlf(self): + stream = StringIO(newline="") + writer = csv.DictWriter(stream, fieldnames=[ + "offer", "lf", "mlf", "nlf", "author_hash" + ]) + writer.writeheader() + for i in range(5): + writer.writerow({"offer": "2 Aizen Evo | Aizen Evo", "author_hash": f"seller{i}"}) + writer.writerow({"offer": "Aizen Evo", "author_hash": f"seller{i}"}) + writer.writerow({"lf": "Aizen Evo", "nlf": "Homura Evo", "author_hash": f"buyer{i}"}) + stream.seek(0) + with patch.object(Path, "open", return_value=stream): + path = Path("fixture.csv") + result, summary = calculate(path, minimum_mentions=10) + self.assertEqual(summary["source_rows"], 15) + self.assertEqual(result[0]["unit_variant"], "Aizen Evo") + self.assertEqual((result[0]["offered_by"], result[0]["requested_by"]), (5, 5)) + self.assertEqual(len(result), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/test_extract_exchange_quotes.py b/test_extract_exchange_quotes.py new file mode 100644 index 0000000..4e037f6 --- /dev/null +++ b/test_extract_exchange_quotes.py @@ -0,0 +1,29 @@ +import unittest + +from extract_exchange_quotes import extract_quotes, parse_side + + +class ExchangeQuoteTests(unittest.TestCase): + def test_only_exact_variant_and_quantity(self): + self.assertEqual(parse_side("my 2 Shiny Aizen Evo"), + ("Shiny Aizen Evo", 2, "my")) + self.assertIsNone(parse_side("Shiny Aizen Evo + adds")) + self.assertIsNone(parse_side("Aizen Evo or Homura Evo")) + + def test_owner_direction_deduplication_and_ambiguous_listing(self): + rows = [ + {"author_hash": "a", "offer": "Homura Evo | Dark Mage Evo", + "lf": "Aizen Evo for my Homura Evo", "mlf": "", "nlf": ""}, + {"author_hash": "a", "offer": "Homura Evo", + "lf": "Aizen Evo for my Homura Evo", "mlf": "", "nlf": ""}, + {"author_hash": "b", "offer": "Shiny Aizen Evo | Homura Evo", + "lf": "Aizen Evo", "mlf": "", "nlf": ""}, + ] + quotes = extract_quotes(rows) + self.assertEqual(len(quotes), 1) + self.assertEqual(quotes[0]["offered_unit"], "Homura Evo") + self.assertEqual(quotes[0]["requested_unit"], "Aizen Evo") + + +if __name__ == "__main__": + unittest.main() diff --git a/trades_state.sqlite-shm b/trades_state.sqlite-shm new file mode 100644 index 0000000..fe9ac28 Binary files /dev/null and b/trades_state.sqlite-shm differ diff --git a/trades_state.sqlite-wal b/trades_state.sqlite-wal new file mode 100644 index 0000000..e69de29