File size: 8,135 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
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
#!/usr/bin/env python3
"""Generate causal QuantInvBench JSONL splits for Hugging Face."""

from __future__ import annotations

import argparse
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path

import numpy as np
import pandas as pd

from common import (
    ASSETS,
    COINS,
    REBALANCE_DAYS,
    STRATEGIES,
    TRANSACTION_COST,
    sha256_file,
    write_jsonl,
)
from strategies import SentimentIndex, compute_proposals


PROJECT_ROOT = Path(__file__).resolve().parents[3]
RELEASE_ROOT = Path(__file__).resolve().parents[1]
SPLIT_BOUNDS = {
    "train": (None, pd.Timestamp("2024-03-15", tz="UTC")),
    "validation": (
        pd.Timestamp("2024-03-16", tz="UTC"),
        pd.Timestamp("2025-03-15", tz="UTC"),
    ),
    "test": (
        pd.Timestamp("2025-03-16", tz="UTC"),
        pd.Timestamp("2026-03-15", tz="UTC"),
    ),
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-dir", type=Path, default=PROJECT_ROOT / "data")
    parser.add_argument(
        "--sentiment-file",
        type=Path,
        default=RELEASE_ROOT / "cache" / "crypto_news_sentiment.json",
    )
    parser.add_argument("--output-dir", type=Path, default=RELEASE_ROOT / "data")
    return parser.parse_args()


def load_daily_data(data_dir: Path) -> dict[str, pd.DataFrame]:
    frames = {}
    required_columns = {
        "date",
        "open",
        "high",
        "low",
        "close",
        "volume",
        "quote_volume",
    }
    for coin in COINS:
        path = data_dir / f"{coin}_prices_1h.csv"
        if not path.exists():
            raise FileNotFoundError(f"Missing source data: {path}")
        hourly = pd.read_csv(path)
        missing = required_columns - set(hourly.columns)
        if missing:
            raise ValueError(f"{path}: missing columns {sorted(missing)}")

        hourly["date"] = pd.to_datetime(hourly["date"], utc=True)
        for column in required_columns - {"date"}:
            hourly[column] = pd.to_numeric(hourly[column], errors="raise")
        if hourly["date"].duplicated().any():
            raise ValueError(f"{path}: duplicate hourly timestamps")
        if not hourly["date"].is_monotonic_increasing:
            hourly = hourly.sort_values("date")

        daily = (
            hourly.set_index("date")
            .resample("1D")
            .agg(
                {
                    "open": "first",
                    "high": "max",
                    "low": "min",
                    "close": "last",
                    "volume": "sum",
                    "quote_volume": "sum",
                }
            )
            .dropna()
        )
        if not np.isfinite(daily.to_numpy(dtype=float)).all():
            raise ValueError(f"{path}: daily data contains NaN or Infinity")
        if (daily[["open", "high", "low", "close"]] <= 0).any().any():
            raise ValueError(f"{path}: source contains non-positive prices")
        frames[coin] = daily

    common_dates = frames[COINS[0]].index
    for coin in COINS[1:]:
        common_dates = common_dates.intersection(frames[coin].index)
    if common_dates.empty:
        raise ValueError("The five assets have no common daily dates")
    return {coin: frame.loc[common_dates].copy() for coin, frame in frames.items()}


def scalar_at(frame: pd.DataFrame, date: pd.Timestamp, column: str) -> float:
    try:
        value = frame.at[date, column]
    except KeyError as exc:
        raise ValueError(f"Missing {column} for {date.date()}") from exc
    if isinstance(value, pd.Series):
        raise ValueError(f"Duplicate value for {date.date()}")
    return float(value)


def split_dates(
    split: str,
    common_dates: pd.DatetimeIndex,
) -> list[pd.Timestamp]:
    configured_start, configured_end = SPLIT_BOUNDS[split]
    history_ready = common_dates.min() + pd.Timedelta(days=61)
    start = max(history_ready, configured_start) if configured_start is not None else history_ready
    latest_execution = common_dates.max() - pd.Timedelta(days=REBALANCE_DAYS)
    end = min(configured_end, latest_execution)
    if start > end:
        raise ValueError(f"{split}: no dates available between {start} and {end}")

    dates = list(pd.date_range(start=start, end=end, freq=f"{REBALANCE_DAYS}D"))
    common_set = set(common_dates)
    for execution in dates:
        if execution not in common_set:
            raise ValueError(f"{split}: missing execution date {execution.date()}")
        exit_date = execution + pd.Timedelta(days=REBALANCE_DAYS)
        if exit_date not in common_set:
            raise ValueError(f"{split}: missing exit date {exit_date.date()}")
    return dates


def make_record(
    split: str,
    index: int,
    execution: pd.Timestamp,
    frames: dict[str, pd.DataFrame],
    sentiment: SentimentIndex,
) -> dict:
    history = {coin: frame.loc[frame.index < execution] for coin, frame in frames.items()}
    if min(len(frame) for frame in history.values()) < 61:
        raise ValueError(f"{execution.date()}: insufficient causal history")

    as_of_timestamp = execution.to_pydatetime() - timedelta(microseconds=1)
    exit_date = execution + pd.Timedelta(days=REBALANCE_DAYS)
    next_returns = []
    for coin in COINS:
        entry = scalar_at(frames[coin], execution, "open")
        exit_price = scalar_at(frames[coin], exit_date, "open")
        next_returns.append(round(exit_price / entry - 1.0, 10))

    proposals = compute_proposals(history, sentiment, as_of_timestamp)
    if [proposal["strategy"] for proposal in proposals] != list(STRATEGIES):
        raise ValueError(f"{execution.date()}: strategy roster changed")

    return {
        "id": f"quantinv_{split}_{index:04d}_{execution:%Y%m%d}",
        "split": split,
        "as_of": as_of_timestamp.astimezone(timezone.utc).isoformat().replace("+00:00", "Z"),
        "execution_at": execution.isoformat().replace("+00:00", "Z"),
        "assets": list(ASSETS),
        "strategy_proposals": proposals,
        "next_7d_returns": next_returns,
    }


def main() -> None:
    args = parse_args()
    data_dir = args.data_dir.resolve()
    sentiment_file = args.sentiment_file.resolve()
    output_dir = args.output_dir.resolve()

    frames = load_daily_data(data_dir)
    sentiment = SentimentIndex(sentiment_file)
    common_dates = frames[COINS[0]].index

    split_records = {}
    for split in SPLIT_BOUNDS:
        dates = split_dates(split, common_dates)
        records = [
            make_record(split, index, execution, frames, sentiment)
            for index, execution in enumerate(dates)
        ]
        split_records[split] = records

    output_dir.mkdir(parents=True, exist_ok=True)
    for split, records in split_records.items():
        write_jsonl(output_dir / f"{split}.jsonl", records)

    source_hashes = {
        f"{coin}_prices_1h.csv": sha256_file(data_dir / f"{coin}_prices_1h.csv")
        for coin in COINS
    }
    source_hashes[sentiment_file.name] = sha256_file(sentiment_file)
    manifest = {
        "dataset": "QuantInvBench",
        "version": "1.0.0",
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "assets": list(ASSETS),
        "strategies": list(STRATEGIES),
        "rebalance_days": REBALANCE_DAYS,
        "transaction_cost": TRANSACTION_COST,
        "splits": {split: len(records) for split, records in split_records.items()},
        "data_sha256": {
            f"{split}.jsonl": sha256_file(output_dir / f"{split}.jsonl")
            for split in split_records
        },
        "source_sha256": source_hashes,
        "notes": {"USDT": "synthetic cash-like series in the current source data"},
    }
    with (output_dir / "manifest.json").open("w", encoding="utf-8") as handle:
        json.dump(manifest, handle, indent=2, ensure_ascii=False, allow_nan=False)
        handle.write("\n")

    counts = ", ".join(f"{split}={len(records)}" for split, records in split_records.items())
    print(f"Generated QuantInvBench in {output_dir} ({counts})")


if __name__ == "__main__":
    main()