quantinvbench / scripts /evaluate.py
anonymous-quantinv's picture
Publish QuantInvBench dataset
bcc98e7 verified
Raw History Blame
12.1 kB
#!/usr/bin/env python3
"""Evaluate QuantInvBench baselines or submitted portfolio weights."""
from __future__ import annotations
import argparse
import json
import math
from pathlib import Path
from typing import Sequence
import numpy as np
from common import ASSETS, REBALANCE_DAYS, TRANSACTION_COST, WEIGHT_TOLERANCE, read_jsonl
EQUAL_WEIGHTS = np.full(len(ASSETS), 1.0 / len(ASSETS), dtype=float)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--data",
type=Path,
default=Path(__file__).resolve().parents[1] / "data" / "test.jsonl",
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"--baseline",
choices=("equal_weight", "simple_avg"),
help="equal_weight is buy-and-hold; simple_avg rebalances every seven days",
)
group.add_argument(
"--predictions",
type=Path,
help="JSONL records with exactly id and weights",
)
parser.add_argument(
"--transaction-cost",
type=float,
default=TRANSACTION_COST,
help="one-way proportional cost applied to half-L1 turnover (default: 0.001)",
)
return parser.parse_args()
def strict_weights(values: object, *, label: str) -> list[float]:
"""Validate a submitted simplex vector without clipping or normalizing it."""
if not isinstance(values, list):
raise ValueError(
f"{label}: weights must be a JSON array in {list(ASSETS)} order"
)
if len(values) != len(ASSETS):
raise ValueError(
f"{label}: expected {len(ASSETS)} weights in {list(ASSETS)} order, "
f"got {len(values)}"
)
weights: list[float] = []
for index, value in enumerate(values):
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(f"{label}: weight {index} must be a JSON number")
weight = float(value)
if not math.isfinite(weight):
raise ValueError(f"{label}: weight {index} is NaN or Infinity")
if weight < 0.0:
raise ValueError(f"{label}: weight {index} must be non-negative")
weights.append(weight)
total = math.fsum(weights)
if not math.isclose(total, 1.0, rel_tol=0.0, abs_tol=WEIGHT_TOLERANCE):
raise ValueError(
f"{label}: weights must sum to 1 (got {total:.12g}); "
"the evaluator does not clip or normalize predictions"
)
return weights
def baseline_weights(record: dict, baseline: str) -> list[float]:
if baseline == "equal_weight":
return EQUAL_WEIGHTS.tolist()
if baseline != "simple_avg":
raise ValueError(f"unknown baseline: {baseline}")
proposals = record.get("strategy_proposals")
if not isinstance(proposals, list) or not proposals:
raise ValueError(f"{record.get('id', '<unknown>')}: missing strategy proposals")
proposal_weights = []
for index, proposal in enumerate(proposals):
if not isinstance(proposal, dict) or "weights" not in proposal:
raise ValueError(
f"{record.get('id', '<unknown>')}: strategy proposal {index} "
"must contain weights"
)
proposal_weights.append(
strict_weights(
proposal["weights"],
label=f"{record.get('id', '<unknown>')}.strategy_proposals[{index}]",
)
)
averaged = np.mean(np.asarray(proposal_weights, dtype=float), axis=0).tolist()
return strict_weights(averaged, label=f"{record.get('id', '<unknown>')}.simple_avg")
def load_predictions(path: Path) -> dict[str, list[float]]:
predictions: dict[str, list[float]] = {}
for index, record in enumerate(read_jsonl(path)):
if not isinstance(record, dict) or set(record) != {"id", "weights"}:
raise ValueError(
f"prediction {index}: expected exactly the fields id and weights"
)
identifier = record["id"]
if not isinstance(identifier, str) or not identifier:
raise ValueError(f"prediction {index}: id must be a non-empty string")
if identifier in predictions:
raise ValueError(f"prediction {index}: duplicate id {identifier!r}")
predictions[identifier] = strict_weights(
record["weights"], label=f"prediction {identifier!r}"
)
return predictions
def _daily_returns(record: dict) -> np.ndarray:
identifier = record.get("id", "<unknown>")
if "next_7d_daily_returns" not in record:
if "next_7d_returns" in record:
raise ValueError(
f"{identifier}: legacy record has next_7d_returns but no "
"next_7d_daily_returns; regenerate the dataset because weekly "
"returns cannot reproduce daily NAV and maximum drawdown"
)
raise ValueError(f"{identifier}: missing next_7d_daily_returns")
values = record["next_7d_daily_returns"]
if not isinstance(values, list) or len(values) != REBALANCE_DAYS:
length = len(values) if isinstance(values, list) else "non-list"
raise ValueError(
f"{identifier}: next_7d_daily_returns must contain exactly "
f"{REBALANCE_DAYS} daily rows (got {length})"
)
rows: list[list[float]] = []
for day_index, row in enumerate(values):
if not isinstance(row, list) or len(row) != len(ASSETS):
length = len(row) if isinstance(row, list) else "non-list"
raise ValueError(
f"{identifier}: next_7d_daily_returns[{day_index}] must contain "
f"{len(ASSETS)} returns in {list(ASSETS)} order (got {length})"
)
parsed_row = []
for asset_index, value in enumerate(row):
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(
f"{identifier}: daily return [{day_index}][{asset_index}] "
"must be a JSON number"
)
parsed = float(value)
if not math.isfinite(parsed):
raise ValueError(
f"{identifier}: daily return [{day_index}][{asset_index}] "
"is NaN or Infinity"
)
if parsed <= -1.0:
raise ValueError(
f"{identifier}: daily return [{day_index}][{asset_index}] "
"must be greater than -1"
)
parsed_row.append(parsed)
rows.append(parsed_row)
return np.asarray(rows, dtype=float)
def _update_drawdown(capital: float, peak: float, maximum: float) -> tuple[float, float]:
peak = max(peak, capital)
return peak, max(maximum, 1.0 - capital / peak)
def evaluate(
records: Sequence[dict],
weights_by_id: dict[str, list[float]],
transaction_cost: float,
*,
buy_and_hold: bool = False,
) -> dict:
"""Run the weekly-rebalanced portfolio simulation.
The paper starts every method from an already established equal-weight
portfolio. Regular methods trade from that portfolio at the first event and
subsequently trade from the return-drifted holdings. With ``buy_and_hold``
set, that initial equal-weight portfolio is never traded.
"""
if (
isinstance(transaction_cost, bool)
or not isinstance(transaction_cost, (int, float))
or not math.isfinite(float(transaction_cost))
or not 0.0 <= float(transaction_cost) < 1.0
):
raise ValueError("transaction cost must be a finite number in [0, 1)")
if not records:
raise ValueError("cannot evaluate an empty dataset")
if not isinstance(weights_by_id, dict):
raise ValueError("weights_by_id must be a mapping from record id to weights")
identifiers = []
seen_ids = set()
for index, record in enumerate(records):
if not isinstance(record, dict):
raise ValueError(f"record {index}: expected an object")
identifier = record.get("id")
if not isinstance(identifier, str) or not identifier:
raise ValueError(f"record {index}: id must be a non-empty string")
if identifier in seen_ids:
raise ValueError(f"record {index}: duplicate id {identifier!r}")
if "assets" in record and record["assets"] != list(ASSETS):
raise ValueError(
f"{identifier}: assets must be in canonical order {list(ASSETS)}"
)
seen_ids.add(identifier)
identifiers.append(identifier)
prediction_ids = set(weights_by_id)
missing_ids = seen_ids - prediction_ids
if missing_ids:
raise ValueError(f"missing prediction for {sorted(missing_ids)[0]}")
extra_ids = prediction_ids - seen_ids
if extra_ids:
raise ValueError(f"predictions contain unknown ids: {sorted(extra_ids)[:3]}")
validated_targets = {
identifier: np.asarray(
strict_weights(weights_by_id[identifier], label=f"prediction {identifier!r}"),
dtype=float,
)
for identifier in identifiers
}
daily_returns = [_daily_returns(record) for record in records]
capital = 1.0
peak = capital
maximum_drawdown = 0.0
current_weights = EQUAL_WEIGHTS.copy()
weekly_net_returns = []
turnovers = []
cost = float(transaction_cost)
for identifier, return_matrix in zip(identifiers, daily_returns):
period_start_capital = capital
if buy_and_hold:
turnover = 0.0
else:
target_weights = validated_targets[identifier]
turnover = float(np.abs(target_weights - current_weights).sum() / 2.0)
capital *= 1.0 - cost * turnover
peak, maximum_drawdown = _update_drawdown(
capital, peak, maximum_drawdown
)
current_weights = target_weights.copy()
turnovers.append(turnover)
for day_index, asset_returns in enumerate(return_matrix):
asset_growth = 1.0 + asset_returns
portfolio_growth = float(current_weights @ asset_growth)
if not math.isfinite(portfolio_growth) or portfolio_growth <= 0.0:
raise ValueError(
f"{identifier}: portfolio value became non-positive on "
f"daily return row {day_index}"
)
capital *= portfolio_growth
current_weights = current_weights * asset_growth / portfolio_growth
peak, maximum_drawdown = _update_drawdown(
capital, peak, maximum_drawdown
)
weekly_net_returns.append(capital / period_start_capital - 1.0)
returns = np.asarray(weekly_net_returns, dtype=float)
volatility = float(returns.std(ddof=0))
sharpe = (
float(returns.mean() / volatility * math.sqrt(52.0))
if volatility > 0.0
else 0.0
)
return {
"samples": len(records),
"cumulative_return": round(capital - 1.0, 10),
"annualized_sharpe": round(sharpe, 10),
"max_drawdown": round(maximum_drawdown, 10),
"average_turnover": round(float(np.mean(turnovers)), 10),
"transaction_cost": cost,
}
def main() -> None:
args = parse_args()
records = read_jsonl(args.data.resolve())
if not records:
raise ValueError(f"empty dataset: {args.data}")
if args.baseline:
weights_by_id = {
record["id"]: baseline_weights(record, args.baseline)
for record in records
}
method = args.baseline
buy_and_hold = args.baseline == "equal_weight"
else:
weights_by_id = load_predictions(args.predictions.resolve())
method = str(args.predictions)
buy_and_hold = False
metrics = evaluate(
records,
weights_by_id,
args.transaction_cost,
buy_and_hold=buy_and_hold,
)
print(json.dumps({"method": method, **metrics}, indent=2, allow_nan=False))
if __name__ == "__main__":
main()