336 lines
18 KiB
Python
336 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""Fit a provisional relative ValueList to completed trades and asking quotes.
|
|
|
|
The scale fixes Aizen Evo at 1000. Completed trades are recorded separately
|
|
from proposed exchanges. Shiny Aizen has an ordering constraint only.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
from collections import Counter, defaultdict
|
|
import csv
|
|
from itertools import combinations
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from bundle_quotes import extract_bundle_quotes
|
|
from completed_trades import load_completed_trades
|
|
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
|
|
COMPLETED_WEIGHT = 9.0
|
|
MAX_STABLE_CHANGE_PCT = 25.0
|
|
CONFLICT_RATIO = 1.25
|
|
CONFIDENCE_FIELDS = ("unit_variant", "quote_count", "asking_quote_count",
|
|
"completed_trade_count", "full_fit_value",
|
|
"leave_one_out_min", "leave_one_out_max", "max_change_pct",
|
|
"most_influential_source_row", "most_influential_evidence_type",
|
|
"most_influential_quote",
|
|
"disconnects_when_removed", "status", "conflicting_source_rows")
|
|
CONFLICT_FIELDS = ("unit_a", "unit_b", "source_row_a", "source_row_b",
|
|
"value_ratio_a", "value_ratio_b", "ratio_difference_pct",
|
|
"source_text_a", "source_text_b")
|
|
IMPACT_FIELDS = ("unit_variant", "removed_source_row", "removed_evidence_type", "removed_quote",
|
|
"leave_one_out_value", "change_pct", "disconnected")
|
|
|
|
|
|
def source_order(source: int | str) -> tuple[int, int | str]:
|
|
return (1, source) if isinstance(source, str) else (0, source)
|
|
|
|
|
|
def source_list(sources: set[int | str]) -> str:
|
|
return " | ".join(map(str, sorted(sources, key=source_order)))
|
|
|
|
|
|
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_quotes(quotes: list[tuple]) -> tuple[dict[str, float], list[tuple], dict[str, set[int | str]]]:
|
|
"""Fit only the component connected to the fixed Aizen reference."""
|
|
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
|
|
|
|
sources: dict[str, set[int | str]] = 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):
|
|
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})
|
|
return values, connected, sources
|
|
|
|
|
|
def conflicting_quotes(direct: list[dict]) -> list[dict]:
|
|
"""Find direct quotes for the same pair whose implied ratios differ by >25%."""
|
|
pairs: dict[tuple[str, str], list[tuple[dict, float]]] = defaultdict(list)
|
|
for quote in direct:
|
|
first, second = sorted((quote["offered_unit"], quote["requested_unit"]))
|
|
offered_qty, requested_qty = int(quote["offered_qty"]), int(quote["requested_qty"])
|
|
ratio = (requested_qty / offered_qty if quote["offered_unit"] == first
|
|
else offered_qty / requested_qty)
|
|
pairs[first, second].append((quote, ratio))
|
|
result = []
|
|
for (first, second), items in sorted(pairs.items()):
|
|
for (left, left_ratio), (right, right_ratio) in combinations(items, 2):
|
|
difference = 100 * (max(left_ratio, right_ratio) / min(left_ratio, right_ratio) - 1)
|
|
if max(left_ratio, right_ratio) / min(left_ratio, right_ratio) <= CONFLICT_RATIO:
|
|
continue
|
|
result.append({"unit_a": first, "unit_b": second,
|
|
"source_row_a": left["source_row"], "source_row_b": right["source_row"],
|
|
"value_ratio_a": round(left_ratio, 4), "value_ratio_b": round(right_ratio, 4),
|
|
"ratio_difference_pct": round(difference, 1),
|
|
"source_text_a": left["source_text"], "source_text_b": right["source_text"]})
|
|
return result
|
|
|
|
|
|
def fit_values(direct: list[dict], bundles: list[dict], completed: list[dict] | None = None,
|
|
*, include_report: bool = False) -> tuple:
|
|
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, item.get("source_text", ""), "asking_direct"))
|
|
for item in bundles:
|
|
quotes.append((item["offered"], item["requested"], int(item["source_row"]),
|
|
1.0, item.get("source_text", ""), "asking_bundle"))
|
|
for item in completed or []:
|
|
quotes.append((item["offered"], item["requested"], item["source_row"],
|
|
COMPLETED_WEIGHT, item.get("source_text", ""), "completed_trade"))
|
|
values, connected, sources = fit_quotes(quotes)
|
|
conflicts = conflicting_quotes(direct)
|
|
conflicting_rows: dict[str, set[int]] = defaultdict(set)
|
|
for conflict in conflicts:
|
|
for unit in (conflict["unit_a"], conflict["unit_b"]):
|
|
conflicting_rows[unit].update((conflict["source_row_a"], conflict["source_row_b"]))
|
|
omissions = [(quote, fit_quotes(connected[:i] + connected[i + 1:])[0])
|
|
for i, quote in enumerate(connected)]
|
|
report = []
|
|
impacts = []
|
|
result = []
|
|
for unit, value in values.items():
|
|
count = len(sources[unit])
|
|
completed_count = len({q[2] for q in connected if q[5] == "completed_trade"
|
|
and unit in set(q[0]) | set(q[1])})
|
|
asking_count = count - completed_count
|
|
omitted_values = [(quote, fitted.get(unit)) for quote, fitted in omissions]
|
|
for quote, fitted in omitted_values:
|
|
impacts.append({
|
|
"unit_variant": unit, "removed_source_row": quote[2],
|
|
"removed_evidence_type": quote[5],
|
|
"removed_quote": quote[4],
|
|
"leave_one_out_value": round(fitted, 1) if fitted is not None else "",
|
|
"change_pct": round(100 * (fitted - value) / value, 1) if fitted is not None else "",
|
|
"disconnected": "yes" if fitted is None else "no",
|
|
})
|
|
retained = [(quote, fitted) for quote, fitted in omitted_values if fitted is not None]
|
|
disconnected = [quote for quote, fitted in omitted_values if fitted is None]
|
|
largest = (max(retained, key=lambda pair: abs(pair[1] - value), default=None)
|
|
if unit != ANCHOR else None)
|
|
max_change = (100 * abs(largest[1] - value) / value if largest else 0.0)
|
|
eligible = count >= 3 or (completed_count >= 1 and count >= 2) or unit in (
|
|
ANCHOR, "Shiny Dark Mage Evo")
|
|
ordering_conflict = unit == SHINY_AIZEN and value <= ANCHOR_VALUE
|
|
unstable = eligible and unit != ANCHOR and (
|
|
bool(disconnected) or max_change > MAX_STABLE_CHANGE_PCT or ordering_conflict)
|
|
ranked = eligible and not unstable
|
|
confidence = ("constraint_only" if unit == SHINY_AIZEN and not ranked else
|
|
"unstable" if unstable else
|
|
("low" if count >= 4 else "very_low") if ranked else "insufficient")
|
|
status = "reference" if unit == ANCHOR else "unstable" if unstable else (
|
|
"ranked" if ranked else "insufficient")
|
|
report.append({
|
|
"unit_variant": unit, "quote_count": count,
|
|
"asking_quote_count": asking_count, "completed_trade_count": completed_count,
|
|
"full_fit_value": round(value, 1),
|
|
"leave_one_out_min": round(min(fitted for _, fitted in retained), 1) if retained else "",
|
|
"leave_one_out_max": round(max(fitted for _, fitted in retained), 1) if retained else "",
|
|
"max_change_pct": round(max_change, 1),
|
|
"most_influential_source_row": largest[0][2] if largest else "",
|
|
"most_influential_evidence_type": largest[0][5] if largest else "",
|
|
"most_influential_quote": largest[0][4] if largest else "",
|
|
"disconnects_when_removed": source_list({q[2] for q in disconnected}),
|
|
"status": status,
|
|
"conflicting_source_rows": " | ".join(map(str, sorted(conflicting_rows[unit]))),
|
|
})
|
|
result.append({
|
|
"unit_variant": unit,
|
|
"relative_value": round(value / 50) * 50 if ranked else "",
|
|
"confidence": confidence,
|
|
"quote_count": count,
|
|
"asking_quote_count": asking_count,
|
|
"completed_trade_count": completed_count,
|
|
"source_rows": source_list(sources[unit]),
|
|
"basis": ("completed_and_asking" if completed_count and asking_count else
|
|
"completed_trades" if completed_count else "asking_quotes"),
|
|
"note": ("Worth more than Aizen Evo; numeric estimate unavailable or conflicts with ordering"
|
|
if unit == SHINY_AIZEN and not ranked else
|
|
"Aizen Evo = 1000 reference" if unit == ANCHOR else
|
|
"Estimate changes or disconnects when one quote is removed" if unstable else
|
|
"Too few independent quotes for a numeric estimate" if not ranked else ""),
|
|
"_sort_value": value if ranked else ANCHOR_VALUE + 0.01 if unit == SHINY_AIZEN 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.
|
|
if SHINY_AIZEN not in values:
|
|
result.append({
|
|
"unit_variant": SHINY_AIZEN,
|
|
"relative_value": "",
|
|
"confidence": "constraint_only",
|
|
"quote_count": 0,
|
|
"asking_quote_count": 0,
|
|
"completed_trade_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"]
|
|
report.sort(key=lambda row: row["unit_variant"])
|
|
summary = {"simple_quotes": len(direct), "bundle_quotes": len(bundles),
|
|
"completed_trades": len(completed or []),
|
|
"connected_quotes": len(connected), "connected_units": len(values),
|
|
"unstable_units": sum(row["status"] == "unstable" for row in report),
|
|
"conflicting_quote_pairs": len(conflicts)}
|
|
if include_report:
|
|
return result, summary, report, conflicts, impacts
|
|
return result, summary
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--input", type=Path, default=Path("trades.csv"))
|
|
parser.add_argument("--completed-trades", type=Path, default=Path("completed_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"))
|
|
parser.add_argument("--confidence-output", type=Path, default=Path("confidence_report.csv"))
|
|
parser.add_argument("--conflicts-output", type=Path, default=Path("quote_conflicts.csv"))
|
|
parser.add_argument("--impact-output", type=Path, default=Path("quote_impact.csv"))
|
|
args = parser.parse_args()
|
|
destinations = [args.output.resolve(), args.bundle_output.resolve(), args.direct_output.resolve(),
|
|
args.confidence_output.resolve(), args.conflicts_output.resolve(),
|
|
args.impact_output.resolve()]
|
|
inputs = {args.input.resolve(), args.completed_trades.resolve()}
|
|
if len(inputs) != 2 or len(set(destinations)) != len(destinations) or inputs.intersection(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)
|
|
completed = load_completed_trades(args.completed_trades)
|
|
values, summary, report, conflicts, impacts = fit_values(
|
|
direct, bundles, completed, include_report=True)
|
|
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", "asking_quote_count",
|
|
"completed_trade_count", "source_rows",
|
|
"basis", "note"))
|
|
writer.writeheader()
|
|
writer.writerows(values)
|
|
with args.confidence_output.open("w", encoding="utf-8-sig", newline="") as stream:
|
|
writer = csv.DictWriter(stream, fieldnames=CONFIDENCE_FIELDS)
|
|
writer.writeheader()
|
|
writer.writerows(report)
|
|
with args.conflicts_output.open("w", encoding="utf-8-sig", newline="") as stream:
|
|
writer = csv.DictWriter(stream, fieldnames=CONFLICT_FIELDS)
|
|
writer.writeheader()
|
|
writer.writerows(conflicts)
|
|
with args.impact_output.open("w", encoding="utf-8-sig", newline="") as stream:
|
|
writer = csv.DictWriter(stream, fieldnames=IMPACT_FIELDS)
|
|
writer.writeheader()
|
|
writer.writerows(impacts)
|
|
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 asks; "
|
|
f"{summary['completed_trades']} completed trades; "
|
|
f"{summary['connected_quotes']} exchanges in the Aizen component; "
|
|
f"{summary['unstable_units']} unstable variants and "
|
|
f"{summary['conflicting_quote_pairs']} conflicting quote pairs.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|