File size: 4,456 Bytes
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
#!/usr/bin/env python3
"""Evaluate QuantInvBench baselines or submitted portfolio weights."""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np

from common import ASSETS, TRANSACTION_COST, read_jsonl, validated_weights


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"))
    group.add_argument("--predictions", type=Path, help="JSONL records with id and weights")
    parser.add_argument("--transaction-cost", type=float, default=TRANSACTION_COST)
    return parser.parse_args()


def baseline_weights(record: dict, baseline: str) -> list[float]:
    if baseline == "equal_weight":
        return [1.0 / len(ASSETS)] * len(ASSETS)
    proposals = [proposal["weights"] for proposal in record["strategy_proposals"]]
    return validated_weights(np.mean(proposals, axis=0).tolist(), label="simple_avg")


def load_predictions(path: Path) -> dict[str, list[float]]:
    predictions = {}
    for index, record in enumerate(read_jsonl(path)):
        if set(record) != {"id", "weights"}:
            raise ValueError(f"prediction {index}: expected only id and weights")
        identifier = record["id"]
        if not isinstance(identifier, str) or identifier in predictions:
            raise ValueError(f"prediction {index}: invalid or duplicate id")
        predictions[identifier] = validated_weights(record["weights"], label=identifier)
    return predictions


def evaluate(records: list[dict], weights_by_id: dict[str, list[float]], transaction_cost: float) -> dict:
    if not 0 <= transaction_cost < 1:
        raise ValueError("transaction cost must be in [0, 1)")
    capital = 1.0
    peak = capital
    maximum_drawdown = 0.0
    previous_weights = np.full(len(ASSETS), 1.0 / len(ASSETS))
    period_returns = []
    turnovers = []

    for record in records:
        identifier = record["id"]
        if identifier not in weights_by_id:
            raise ValueError(f"missing prediction for {identifier}")
        weights = np.asarray(weights_by_id[identifier], dtype=float)
        asset_returns = np.asarray(record["next_7d_returns"], dtype=float)
        turnover = float(np.abs(weights - previous_weights).sum() / 2.0)
        gross_return = float(weights @ asset_returns)
        net_growth = (1.0 - transaction_cost * turnover) * (1.0 + gross_return)
        if net_growth <= 0:
            raise ValueError(f"{identifier}: portfolio value became non-positive")
        net_return = net_growth - 1.0
        capital *= net_growth
        peak = max(peak, capital)
        maximum_drawdown = max(maximum_drawdown, 1.0 - capital / peak)
        period_returns.append(net_return)
        turnovers.append(turnover)
        previous_weights = weights

    returns = np.asarray(period_returns, dtype=float)
    volatility = float(returns.std(ddof=1)) if len(returns) > 1 else 0.0
    sharpe = float(returns.mean() / volatility * np.sqrt(52)) if volatility > 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": transaction_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
    else:
        weights_by_id = load_predictions(args.predictions.resolve())
        expected_ids = {record["id"] for record in records}
        extra_ids = set(weights_by_id) - expected_ids
        if extra_ids:
            raise ValueError(f"predictions contain unknown ids: {sorted(extra_ids)[:3]}")
        method = str(args.predictions)

    metrics = evaluate(records, weights_by_id, args.transaction_cost)
    print(json.dumps({"method": method, **metrics}, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()