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()
|