Update trade listings
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user