File size: 9,257 Bytes
d24798b
 
 
 
7355d65
79eb22e
 
 
d24798b
79eb22e
d24798b
0b16dd0
 
 
 
d24798b
 
79eb22e
d24798b
 
 
 
 
0b929da
d24798b
 
 
 
0b16dd0
 
79eb22e
0b16dd0
7355d65
 
79eb22e
7355d65
 
 
79eb22e
7355d65
79eb22e
7355d65
 
 
 
 
79eb22e
 
 
 
0b929da
7355d65
 
79eb22e
7355d65
 
 
 
 
 
 
79eb22e
 
 
7355d65
 
 
 
 
 
 
 
 
 
 
79eb22e
7355d65
79eb22e
 
 
 
 
7355d65
 
 
 
 
 
 
 
 
 
 
 
 
79eb22e
 
 
 
 
 
 
 
 
 
7355d65
 
 
 
 
 
79eb22e
7355d65
 
 
 
79eb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7355d65
 
 
 
 
 
 
 
79eb22e
 
7355d65
 
 
79eb22e
 
 
7355d65
79eb22e
 
 
0b929da
98b6850
0b929da
79eb22e
 
0b16dd0
 
 
 
 
7355d65
0b16dd0
 
79eb22e
 
7355d65
79eb22e
 
0b16dd0
d24798b
0b16dd0
 
 
d24798b
79eb22e
d24798b
98b6850
d24798b
79eb22e
d24798b
79eb22e
 
 
 
 
 
 
 
 
 
 
 
 
d24798b
79eb22e
d24798b
0b16dd0
79eb22e
 
 
 
 
 
d24798b
 
79eb22e
d24798b
 
 
 
 
79eb22e
0b929da
 
 
 
79eb22e
d24798b
 
 
79eb22e
 
 
 
 
 
 
 
d24798b
 
 
79eb22e
d24798b
 
0b16dd0
 
 
 
79eb22e
 
 
 
 
 
d24798b
79eb22e
 
 
 
 
 
 
 
 
 
 
 
d24798b
79eb22e
 
 
 
 
 
 
 
 
d24798b
 
 
 
 
 
 
 
 
79eb22e
 
 
 
 
 
d24798b
0b929da
 
 
79eb22e
0b929da
79eb22e
d24798b
 
 
 
 
 
 
 
 
79eb22e
d24798b
 
 
 
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
import datetime as dt
import pandas as pd
import torch
import gradio as gr
import requests
import matplotlib
matplotlib.use("Agg")  # HF Space ๊ฐ™์ด GUI ์—†๋Š” ํ™˜๊ฒฝ์—์„œ ์•ˆ์ „ํ•˜๊ฒŒ
import matplotlib.pyplot as plt

from chronos import BaseChronosPipeline  # pip install chronos-forecasting


# =============================
#   Chronos ๋ชจ๋ธ ์บ์‹œ/๋กœ๋”
# =============================
_PIPELINE_CACHE = {}


def get_pipeline(model_id: str, device: str = "cpu"):
    key = (model_id, device)
    if key not in _PIPELINE_CACHE:
        _PIPELINE_CACHE[key] = BaseChronosPipeline.from_pretrained(
            model_id,
            device_map=device,  # "cpu" / "cuda"
            torch_dtype=torch.float32 if device == "cpu" else torch.bfloat16,
        )
    return _PIPELINE_CACHE[key]


# =============================
#   Binance ์ „์šฉ ๋กœ๋”
# =============================
_BINANCE_INTERVAL = {"1d": "1d", "1h": "1h", "30m": "30m", "15m": "15m", "5m": "5m"}


def _yf_to_binance_symbol(ticker: str) -> str | None:
    """
    BTC-USD -> BTCUSDT, ETH-USD -> ETHUSDT ...
    ๊ทธ ์™ธ ํ˜•์‹์€ None (ํ˜„์žฌ๋Š” -USD ์ฝ”์ธ๋งŒ ์ง€์›)
    """
    t = ticker.upper().strip()
    if t.endswith("-USD") and len(t) >= 6:
        base = t[:-4]  # remove "-USD"
        return f"{base}USDT"
    return None


def _fetch_binance_klines(
    ticker: str, interval: str, start: str | None, end: str | None
) -> pd.Series:
    """
    Binance Klines (๋ฌด์ธ์ฆ)
    https://api.binance.com/api/v3/klines

    ๋ฐ˜ํ™˜: pandas.Series(index=datetime, values=float close)
    """
    if interval not in _BINANCE_INTERVAL:
        raise ValueError("Binance๋Š” ํ•ด๋‹น interval์„ ์ง€์›ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.")

    symbol = _yf_to_binance_symbol(ticker)
    if not symbol:
        raise ValueError(
            "์ด ํ‹ฐ์ปค๋Š” Binance ์‹ฌ๋ณผ๋กœ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์˜ˆ: BTC-USD, ETH-USD ํ˜•ํƒœ๋งŒ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค."
        )

    base = "https://api.binance.com/api/v3/klines"

    def to_ms(s: str) -> int:
        return int(pd.to_datetime(s).timestamp() * 1000)

    start_ms = to_ms(start) if start else None
    end_ms = to_ms(end) if end else None

    rows = []
    cur_start = start_ms

    while True:
        params = {
            "symbol": symbol,
            "interval": _BINANCE_INTERVAL[interval],
            "limit": 1000,
        }
        if cur_start is not None:
            params["startTime"] = cur_start
        if end_ms is not None:
            params["endTime"] = end_ms

        r = requests.get(base, params=params, timeout=30)
        r.raise_for_status()
        data = r.json()
        if not data:
            break

        rows.extend(data)

        # data[i] = [
        #   0 openTime,
        #   1 open,
        #   2 high,
        #   3 low,
        #   4 close,
        #   5 volume,
        #   6 closeTime,
        #   ...
        # ]
        last_close_time = data[-1][6]  # closeTime (ms)
        next_start = last_close_time + 1
        if cur_start is not None and next_start <= cur_start:
            break
        cur_start = next_start

        # ๋” ์ด์ƒ 1000๊ฐœ ์•ˆ ๋‚˜์˜ค๋ฉด ๋งˆ์ง€๋ง‰ ํŽ˜์ด์ง€๋กœ ํŒ๋‹จ
        if len(data) < 1000:
            break

    if not rows:
        raise ValueError("Binance์—์„œ ๊ฐ€์ ธ์˜จ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")

    df = pd.DataFrame(
        rows,
        columns=[
            "openTime",
            "open",
            "high",
            "low",
            "close",
            "volume",
            "closeTime",
            "quoteAssetVolume",
            "numTrades",
            "takerBuyBase",
            "takerBuyQuote",
            "ignore",
        ],
    )
    df["ts"] = pd.to_datetime(df["closeTime"], unit="ms")
    s = df.set_index("ts")["close"].astype(float).sort_index()

    if start:
        s = s[s.index >= pd.to_datetime(start)]
    if end:
        s = s[s.index <= pd.to_datetime(end)]
    if s.empty:
        raise ValueError("Binance ์‹œ๋ฆฌ์ฆˆ๊ฐ€ ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ๊ธฐ๊ฐ„/๊ฐ„๊ฒฉ์„ ๋‹ค์‹œ ์„ค์ •ํ•ด ์ฃผ์„ธ์š”.")

    return s


def load_close_series(
    ticker: str, start: str | None, end: str | None, interval: str = "1d"
) -> pd.Series:
    """
    Binance ์ „์šฉ ์ข…๊ฐ€ ์‹œ๋ฆฌ์ฆˆ ๋กœ๋”.
    ์ž…๋ ฅ: ํ‹ฐ์ปค (์˜ˆ: BTC-USD, ETH-USD), ์‹œ์ž‘์ผ, ์ข…๋ฃŒ์ผ, ๊ฐ„๊ฒฉ(1d/1h/30m/15m/5m)
    ๋ฐ˜ํ™˜: pandas.Series (index=datetime, values=float close)
    """
    ticker = ticker.strip().upper()

    # ๊ธฐ๋ณธ ๊ธฐ๊ฐ„ ์„ค์ •
    _start = start or "2017-01-01"
    _end = end or dt.date.today().isoformat()
    try:
        sdt = pd.to_datetime(_start)
        edt = pd.to_datetime(_end)
        if edt < sdt:
            sdt, edt = edt, sdt
        _start, _end = sdt.date().isoformat(), edt.date().isoformat()
    except Exception:
        # ์ž˜๋ชป๋œ ๋‚ ์งœ ํฌ๋งท์ด ๋“ค์–ด์˜ค๋ฉด ์ผ๋‹จ ๊ธฐ๋ณธ๊ฐ’ ์‚ฌ์šฉ
        _start, _end = "2017-01-01", dt.date.today().isoformat()

    # ์˜ค๋กœ์ง€ Binance๋งŒ ์‚ฌ์šฉ
    return _fetch_binance_klines(ticker, interval, _start, _end)


# =============================
#   ์˜ˆ์ธก ํ•จ์ˆ˜ (Gradio ํ•ธ๋“ค๋Ÿฌ)
# =============================
def run_forecast(ticker, start_date, end_date, horizon, model_id, device, interval):
    # 1) ์‹œ๊ณ„์—ด ๋กœ๋”ฉ
    try:
        series = load_close_series(ticker, start_date, end_date, interval)
    except Exception as e:
        return None, pd.DataFrame(), f"๋ฐ์ดํ„ฐ ๋กœ๋”ฉ ์˜ค๋ฅ˜ (Binance): {e}"

    # 2) ํŒŒ์ดํ”„๋ผ์ธ ๋กœ๋”ฉ
    try:
        pipe = get_pipeline(model_id, device)
    except Exception as e:
        return None, pd.DataFrame(), f"๋ชจ๋ธ ๋กœ๋”ฉ ์˜ค๋ฅ˜: {e}"

    # 3) ์˜ˆ์ธก ๊ธธ์ด
    try:
        H = int(horizon)
        if H <= 0:
            raise ValueError("์˜ˆ์ธก ์Šคํ… H๋Š” 1 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.")
    except Exception:
        return None, pd.DataFrame(), "์˜ˆ์ธก ์Šคํ… H๊ฐ€ ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค."

    # 4) Chronos ์ž…๋ ฅ
    context = torch.tensor(series.values, dtype=torch.float32)

    # 5) ์˜ˆ์ธก: (num_series=1, num_quantiles=3, H) with q=[0.1, 0.5, 0.9]
    try:
        preds = pipe.predict(context=context, prediction_length=H)[0]
    except Exception as e:
        return None, pd.DataFrame(), f"์˜ˆ์ธก ์‹คํ–‰ ์˜ค๋ฅ˜: {e}"

    q10, q50, q90 = preds[0], preds[1], preds[2]

    # 6) ๊ฒฐ๊ณผ ํ‘œ (DataFrame)
    df_fcst = pd.DataFrame(
        {"q10": q10.numpy(), "q50": q50.numpy(), "q90": q90.numpy()},
        index=pd.RangeIndex(1, H + 1, name="step"),
    )

    # 7) ๋ฏธ๋ž˜ x์ถ• ๋งŒ๋“ค๊ธฐ
    freq_map = {"1d": "D", "1h": "H", "30m": "30T", "15m": "15T", "5m": "5T"}
    freq = freq_map.get(interval, "D")
    future_index = pd.date_range(series.index[-1], periods=H + 1, freq=freq)[1:]

    # 8) ๊ทธ๋ž˜ํ”„ ๊ทธ๋ฆฌ๊ธฐ
    fig = plt.figure(figsize=(10, 4))
    plt.plot(series.index, series.values, label="history")
    plt.plot(future_index, q50.numpy(), label="forecast(q50)")
    plt.fill_between(
        future_index,
        q10.numpy(),
        q90.numpy(),
        alpha=0.2,
        label="q10โ€“q90",
    )
    plt.title(f"{ticker} forecast by Chronos-Bolt (Binance, {interval}, H={H})")
    plt.legend()
    plt.tight_layout()

    note = "โ€ป ๋ฐ๋ชจ ๋ชฉ์ ์ž…๋‹ˆ๋‹ค. ํˆฌ์ž ํŒ๋‹จ๊ณผ ๊ฒฐ๊ณผ ์ฑ…์ž„์€ ์ „์ ์œผ๋กœ ๋ณธ์ธ์—๊ฒŒ ์žˆ์Šต๋‹ˆ๋‹ค."
    return fig, df_fcst, note


# =============================
#   Gradio UI
# =============================
with gr.Blocks(title="Chronos Crypto Forecast (Binance)") as demo:
    gr.Markdown("# Chronos ํฌ๋ฆฝํ†  ์˜ˆ์ธก ๋ฐ๋ชจ (Binance ์ „์šฉ)")
    gr.Markdown(
        "ํ‹ฐ์ปค๋Š” `BTC-USD`, `ETH-USD` ์ฒ˜๋Ÿผ ์ž…๋ ฅํ•˜๋ฉด ๋‚ด๋ถ€์—์„œ `BTCUSDT`, `ETHUSDT`๋กœ ๋ณ€ํ™˜ํ•ด์„œ Binance์—์„œ ๊ฐ€๊ฒฉ์„ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค."
    )

    with gr.Row():
        ticker = gr.Textbox(
            value="BTC-USD",
            label="ํ‹ฐ์ปค (์˜ˆ: BTC-USD, ETH-USD)",
        )
        horizon = gr.Slider(
            5,
            365,
            value=90,
            step=1,
            label="์˜ˆ์ธก ์Šคํ… H (๊ฐ„๊ฒฉ ๋‹จ์œ„์™€ ๋™์ผ)",
        )

    with gr.Row():
        start = gr.Textbox(
            value="2017-01-01",
            label="์‹œ์ž‘์ผ (YYYY-MM-DD)",
        )
        end = gr.Textbox(
            value=dt.date.today().isoformat(),
            label="์ข…๋ฃŒ์ผ (YYYY-MM-DD)",
        )

    with gr.Row():
        model_id = gr.Dropdown(
            choices=[
                "amazon/chronos-bolt-tiny",
                "amazon/chronos-bolt-mini",
                "amazon/chronos-bolt-small",
                "amazon/chronos-bolt-base",
            ],
            value="amazon/chronos-bolt-small",
            label="๋ชจ๋ธ",
        )
        device = gr.Dropdown(
            choices=["cpu"],  # ํ•„์š”ํ•˜๋ฉด "cuda" ์ถ”๊ฐ€
            value="cpu",
            label="๋””๋ฐ”์ด์Šค",
        )
        interval = gr.Dropdown(
            choices=["1d", "1h", "30m", "15m", "5m"],
            value="1d",
            label="๊ฐ„๊ฒฉ (Binance interval)",
        )

    btn = gr.Button("์˜ˆ์ธก ์‹คํ–‰")

    plot = gr.Plot(label="History + Forecast")
    table = gr.Dataframe(label="์˜ˆ์ธก ๊ฒฐ๊ณผ (๋ถ„์œ„์ˆ˜)")
    note = gr.Markdown()

    btn.click(
        fn=run_forecast,
        inputs=[ticker, start, end, horizon, model_id, device, interval],
        outputs=[plot, table, note],
    )

if __name__ == "__main__":
    demo.launch()