127 lines
4.8 KiB
Python
127 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Build a first, evidence-backed market-interest list 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"(?<!\w)(?P<shiny>Shiny\s+)?(?P<unit>"
|
|
+ "|".join(re.escape(name).replace(r"\ ", r"\s+") for name in UNIT_NAMES)
|
|
+ r")\s+(?P<evolution>Evo|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("valuelist.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()
|