File size: 12,144 Bytes
8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 bcc98e7 8f8fb44 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | #!/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()
|