File size: 3,478 Bytes
7b0a8c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Convert pdata.world's nightly bulk files (gzipped JSON lines) to Parquet
for the Hugging Face dataset. Usage: build.py BULK_DIR OUT_DIR

Line 1 of each bulk file is a manifest; it is written to OUT_DIR/manifests/
and the rows to OUT_DIR/data/<kind>.parquet with an explicit schema, so a
column never changes type between monthly snapshots.
"""

import gzip
import json
import sys
from datetime import datetime
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq

TS = pa.timestamp("us", tz="UTC")
STR_LIST = pa.list_(pa.string())

SCHEMAS = {
    "markets-open": pa.schema([
        ("source", pa.string()), ("id", pa.string()), ("event_id", pa.string()),
        ("event_title", pa.string()), ("question", pa.string()), ("label", pa.string()),
        ("categories", STR_LIST), ("outcomes", STR_LIST), ("outcome_prices", pa.list_(pa.float64())),
        ("probability", pa.float64()), ("prob_24h_change", pa.float64()),
        ("volume", pa.float64()), ("volume_24hr", pa.float64()),
        ("liquidity", pa.float64()), ("open_interest", pa.float64()),
        ("start_date", TS), ("end_date", TS), ("status", pa.string()),
        ("countries", STR_LIST), ("updated_at", TS), ("url", pa.string()), ("pdata_url", pa.string()),
    ]),
    "events-open": pa.schema([
        ("source", pa.string()), ("id", pa.string()), ("title", pa.string()),
        ("categories", STR_LIST), ("start_date", TS), ("end_date", TS),
        ("volume", pa.float64()), ("volume_24hr", pa.float64()), ("open_interest", pa.float64()),
        ("mutually_exclusive", pa.bool_()), ("market_count", pa.int64()), ("is_group", pa.bool_()),
        ("parent_event_id", pa.string()), ("synthetic", pa.bool_()),
        ("updated_at", TS), ("url", pa.string()), ("pdata_url", pa.string()),
    ]),
    "resolved": pa.schema([
        ("source", pa.string()), ("id", pa.string()), ("title", pa.string()),
        ("categories", STR_LIST), ("closed_time", TS),
        ("markets", pa.list_(pa.struct([
            ("id", pa.string()), ("question", pa.string()), ("result", pa.string()),
            ("probability", pa.float64()), ("volume", pa.float64()),
        ]))),
        ("url", pa.string()), ("pdata_url", pa.string()), ("pruned_at", TS),
    ]),
}


def convert(bulk: Path, out: Path, kind: str) -> tuple[int, dict]:
    schema = SCHEMAS[kind]
    ts_cols = [f.name for f in schema if f.type == TS]
    with gzip.open(bulk / f"{kind}.jsonl.gz", "rt") as f:
        manifest = json.loads(next(f))["_manifest"]
        rows = []
        for line in f:
            r = json.loads(line)
            for c in ts_cols:
                if r.get(c) is not None:
                    r[c] = datetime.fromisoformat(r[c])
            rows.append(r)
    extra = set().union(*(r.keys() for r in rows)) - set(schema.names)
    if extra:
        raise SystemExit(f"{kind}: fields not in the schema: {sorted(extra)}")
    table = pa.Table.from_pylist(rows, schema=schema)
    pq.write_table(table, out / "data" / f"{kind}.parquet", compression="zstd")
    (out / "manifests" / f"{kind}.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n")
    return table.num_rows, manifest


if __name__ == "__main__":
    bulk, out = Path(sys.argv[1]), Path(sys.argv[2])
    for kind in SCHEMAS:
        n, m = convert(bulk, out, kind)
        size = (out / "data" / f"{kind}.parquet").stat().st_size
        print(f"{kind}: {n:,} rows, {size/1e6:.1f} MB, as_of {m['as_of']}")