Spaces:
Sleeping

File size: 5,932 Bytes
e912599
 
8793c78
e912599
 
 
 
 
802c217
 
 
 
 
 
 
e912599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8793c78
 
e912599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""cruscy data — demo explorer.

Public evaluation sample (3 days of real Binance spot microstructure, normalized).
Full platform: https://data.cruscy.com
"""
from functools import lru_cache

try:
    # ZeroGPU требует >=1 функции с @spaces.GPU на старте, иначе RUNTIME_ERROR.
    # Демо CPU-only, функция-заглушка нигде не вызывается.
    import spaces

    @spaces.GPU
    def _zerogpu_probe() -> str:
        return "ok"
except ImportError:
    pass

import gradio as gr
import matplotlib
import pandas as pd

matplotlib.use("Agg")
import matplotlib.pyplot as plt

REPO = "GOD111111111/synthetic-timeseries-data"
DAYS = ["day_01", "day_02", "day_03"]
FG, GRID, UP, DN, ACC = "#d7dde4", "#2a3038", "#26a269", "#c0392b", "#4f9cf9"


@lru_cache(maxsize=8)
def load(kind: str, day: str) -> pd.DataFrame:
    from huggingface_hub import hf_hub_download
    path = hf_hub_download(REPO, f"{kind}/{day}.parquet", repo_type="dataset")
    return pd.read_parquet(path)


def _fig(nrows=1, height=4.6, ratios=None):
    fig, axes = plt.subplots(
        nrows, 1, figsize=(11, height), dpi=110, sharex=True,
        gridspec_kw={"height_ratios": ratios or [1] * nrows})
    fig.patch.set_facecolor("#14181d")
    for ax in (axes if nrows > 1 else [axes]):
        ax.set_facecolor("#14181d")
        ax.tick_params(colors=FG, labelsize=8)
        for s in ax.spines.values():
            s.set_color(GRID)
        ax.grid(color=GRID, linewidth=0.4, alpha=0.6)
    fig.tight_layout(pad=1.4)
    return fig, axes


def candles(day: str, tf: str):
    df = load("trades", day)
    tf_ms = {"1m": 60_000, "5m": 300_000, "15m": 900_000}[tf]
    g = df.groupby(df.sensor_c // tf_ms)
    o, h = g.sensor_a.first(), g.sensor_a.max()
    l, c = g.sensor_a.min(), g.sensor_a.last()
    v = g.sensor_b.sum()
    t = o.index * tf_ms / 3_600_000  # hours since day start
    up = c >= o
    fig, (ax, axv) = _fig(2, 5.6, [4, 1])
    w = tf_ms / 3_600_000 * 0.75
    ax.vlines(t, l, h, color="#5c6670", linewidth=0.7)
    ax.bar(t[up], (c - o)[up], w, o[up], color=UP)
    ax.bar(t[~up], (c - o)[~up], w, o[~up], color=DN)
    ax.set_ylabel("relative price (day open = 1000)", color=FG, fontsize=9)
    axv.bar(t, v, w, color="#3d78c9", alpha=0.8)
    axv.set_ylabel("volume", color=FG, fontsize=9)
    axv.set_xlabel("hours (UTC day)", color=FG, fontsize=9)
    ax.set_title(f"{day} · {tf} candles from {len(df):,} raw trades",
                 color=FG, fontsize=11, loc="left")
    return fig


def cvd(day: str):
    df = load("trades", day)
    delta = df.sensor_b.where(df.sensor_d == 1, -df.sensor_b)
    m = delta.groupby(df.sensor_c // 60_000).sum().cumsum()
    px = df.groupby(df.sensor_c // 60_000).sensor_a.last()
    t = m.index / 60.0
    fig, (ax, ax2) = _fig(2, 5.6, [1, 1])
    ax.plot(t, px, color=FG, linewidth=1.0)
    ax.set_ylabel("price", color=FG, fontsize=9)
    ax.set_title(f"{day} · price vs cumulative volume delta (CVD)",
                 color=FG, fontsize=11, loc="left")
    ax2.plot(t, m, color=ACC, linewidth=1.1)
    ax2.fill_between(t, 0, m, color=ACC, alpha=0.18)
    ax2.axhline(0, color=GRID, linewidth=0.8)
    ax2.set_ylabel("CVD (mean-size units)", color=FG, fontsize=9)
    ax2.set_xlabel("hours (UTC day)", color=FG, fontsize=9)
    return fig


def flow(day: str):
    ob = load("flow", day)
    t = ob.sensor_c / 3_600_000
    fig, (ax, ax2) = _fig(2, 5.6, [2, 1])
    ax.fill_between(t, ob.sensor_i_lo, ob.sensor_i_hi, color=ACC, alpha=0.15,
                    label="5-min range")
    ax.plot(t, ob.sensor_i, color=ACC, linewidth=1.2, label="mean imbalance")
    ax.axhline(0, color=GRID, linewidth=0.8)
    ax.set_ylim(-1.05, 1.05)
    ax.set_ylabel("book imbalance (−1…1)", color=FG, fontsize=9)
    ax.legend(loc="upper right", fontsize=8, facecolor="#14181d",
              edgecolor=GRID, labelcolor=FG)
    ax.set_title(f"{day} · order-book imbalance & spread (from raw L2)",
                 color=FG, fontsize=11, loc="left")
    ax2.plot(t, ob.sensor_s, color="#e8a33d", linewidth=1.1)
    ax2.set_ylabel("spread, bps", color=FG, fontsize=9)
    ax2.set_xlabel("hours (UTC day)", color=FG, fontsize=9)
    return fig


CSS = """
.gradio-container {max-width: 1080px !important}
#hero {margin-bottom: 4px}
"""

with gr.Blocks(css=CSS, theme=gr.themes.Base(), title="cruscy data — L2 explorer") as demo:
    gr.Markdown(
        "# cruscy data — live L2 explorer\n"
        "Real Binance spot microstructure — every trade, full order-book depth, "
        "derived features and regime labels, recorded with sequence-gap auditing "
        "and daily integrity manifests.\n\n"
        "This Space renders a **normalized 3-day sample** (relative prices, sizes "
        "in units of the day's mean trade; instrument and dates withheld). The full feed is "
        "explored *inside* the platform: SQL console, backtest runner on real "
        "L2, notebook workspace, and **MCP access for AI agents**.\n\n"
        "**[→ Full access: data.cruscy.com](https://data.cruscy.com/?ref=hf)**",
        elem_id="hero")
    day = gr.Dropdown(DAYS, value=DAYS[-1], label="Sample day")
    with gr.Tab("Candles"):
        tf = gr.Radio(["1m", "5m", "15m"], value="5m", label="Timeframe")
        p1 = gr.Plot(show_label=False)
    with gr.Tab("Volume delta (CVD)"):
        p2 = gr.Plot(show_label=False)
    with gr.Tab("Book imbalance"):
        p3 = gr.Plot(show_label=False)
    gr.Markdown(
        "Sample dataset: "
        "[synthetic-timeseries-data](https://huggingface.co/datasets/GOD111111111/synthetic-timeseries-data) "
        "· ~400k trades/day · schema in the dataset card")

    def render_all(d, t):
        return candles(d, t), cvd(d), flow(d)

    day.change(render_all, [day, tf], [p1, p2, p3])
    tf.change(candles, [day, tf], p1)
    demo.load(render_all, [day, tf], [p1, p2, p3])

demo.launch()