File size: 7,007 Bytes
d24798b
 
 
 
 
 
0b16dd0
d24798b
0b16dd0
 
 
 
d24798b
 
 
 
 
 
 
0b929da
d24798b
 
 
 
0b16dd0
 
 
 
d24798b
0b929da
0b16dd0
 
 
 
 
 
 
0b929da
98b6850
0b929da
0b16dd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b929da
98b6850
0b929da
0b16dd0
 
 
0b929da
98b6850
 
0b16dd0
98b6850
0b16dd0
 
 
 
 
 
 
98b6850
 
0b929da
0b16dd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d24798b
0b16dd0
 
 
d24798b
 
98b6850
d24798b
0b16dd0
0b929da
d24798b
 
 
 
0b16dd0
d24798b
0b16dd0
 
d24798b
 
 
0b16dd0
d24798b
 
 
 
 
0b16dd0
d24798b
0b929da
 
 
 
0b16dd0
d24798b
 
 
 
0b929da
d24798b
 
 
0b16dd0
d24798b
 
0b16dd0
 
 
 
0b929da
 
d24798b
0b929da
 
d24798b
0b16dd0
 
d24798b
 
 
 
 
 
 
 
 
 
 
 
0b929da
 
 
 
 
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
import datetime as dt
import pandas as pd
import torch
import gradio as gr
import yfinance as yf

from chronos import BaseChronosPipeline  # pip: 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]


# =============================
#   yfinance ์ „์šฉ ๊ฒฌ๊ณ  ๋กœ๋”
# =============================
def load_close_series(ticker: str, start: str, end: str, interval: str = "1d"):
    """
    yfinance๋งŒ ์‚ฌ์šฉ.
    1) Ticker().history(start/end)
    2) download(start/end, repair=True)
    3) period ๊ธฐ๋ฐ˜ ํด๋ฐฑ:
       - 1d  โ†’ ["max", "10y", "5y", "2y", "1y"]
       - 1h  โ†’ ["730d", "365d", "60d"]
       - 30m/15m/5m โ†’ ["60d", "30d", "14d"]
    """
    ticker = ticker.strip().upper()

    # ๋‚ ์งœ ๋ณด์ •
    _start = start or "2014-09-17"                    # BTC-USD ํžˆ์Šคํ† ๋ฆฌ ์‹œ์ž‘ ๊ทผ์ฒ˜
    _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:
        pass  # ํŒŒ์‹ฑ ์‹คํŒจํ•ด๋„ ๋ฐ‘์˜ period ํด๋ฐฑ์ด ์ปค๋ฒ„

    def _extract_close(df):
        if df is None or df.empty:
            return None
        c = df.get("Close")
        if c is None:
            return None
        c = c.dropna().astype(float)
        return c if not c.empty else None

    # 1) history(start/end)
    try:
        tk = yf.Ticker(ticker)
        df = tk.history(start=_start, end=_end, interval=interval, auto_adjust=True, actions=False)
        s = _extract_close(df)
        if s is not None:
            return s
    except Exception:
        pass

    # 2) download(start/end) + repair=True
    try:
        df = yf.download(
            ticker, start=_start, end=_end, interval=interval,
            progress=False, threads=False, repair=True
        )
        s = _extract_close(df)
        if s is not None:
            return s
    except Exception:
        pass

    # 3) period ํด๋ฐฑ
    if interval == "1d":
        period_candidates = ["max", "10y", "5y", "2y", "1y"]
    elif interval == "1h":
        period_candidates = ["730d", "365d", "60d"]   # 1์‹œ๊ฐ„๋ด‰์€ ๊ณผ๊ฑฐ ์ œํ•œ ํผ
    else:  # 30m/15m/5m ๋“ฑ ๋ถ„๋ด‰
        period_candidates = ["60d", "30d", "14d"]     # ๋ถ„๋ด‰์€ ๋ณดํ†ต 60~30์ผ ์ด๋‚ด๋งŒ ๊ฐ€๋Šฅ

    for per in period_candidates:
        # Ticker().history(period=โ€ฆ)
        try:
            df = tk.history(period=per, interval=interval, auto_adjust=True, actions=False)
            s = _extract_close(df)
            if s is not None:
                return s
        except Exception:
            pass
        # download(period=โ€ฆ)
        try:
            df = yf.download(
                ticker, period=per, interval=interval,
                progress=False, threads=False, repair=True
            )
            s = _extract_close(df)
            if s is not None:
                return s
        except Exception:
            pass

    raise ValueError(
        "yfinance์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. "
        "๊ฐ„๊ฒฉ(interval)์ด๋‚˜ ๊ธฐ๊ฐ„(start/end ํ˜น์€ period)์„ ์กฐ์ •ํ•ด ๋‹ค์‹œ ์‹œ๋„ํ•ด ๋ณด์„ธ์š”."
    )


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

    pipe = get_pipeline(model_id, device)
    H = int(horizon)

    # Chronos ์ž…๋ ฅ: 1D ํ…์„œ (float)
    context = torch.tensor(series.values, dtype=torch.float32)

    # ์˜ˆ์ธก: (num_series=1, num_quantiles=3, H) with q=[0.1, 0.5, 0.9]
    preds = pipe.predict(context=context, prediction_length=H)[0]
    q10, q50, q90 = preds[0], preds[1], preds[2]

    # ํ‘œ ๋ฐ์ดํ„ฐ
    df_fcst = pd.DataFrame(
        {"q10": q10.numpy(), "q50": q50.numpy(), "q90": q90.numpy()},
        index=pd.RangeIndex(1, H + 1, name="step"),
    )

    # ๋ฏธ๋ž˜ x์ถ•: intervalโ†’pandas freq ๋งคํ•‘
    import matplotlib.pyplot as plt
    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:]

    # ๊ทธ๋ž˜ํ”„
    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 ({interval}, H={H})")
    plt.legend()
    plt.tight_layout()

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


# =============================
#   Gradio UI
# =============================
with gr.Blocks(title="Chronos Stock/Crypto Forecast") as demo:
    gr.Markdown("# Chronos ์ฃผ๊ฐ€ยทํฌ๋ฆฝํ†  ์˜ˆ์ธก ๋ฐ๋ชจ")
    with gr.Row():
        ticker = gr.Textbox(value="BTC-USD", label="ํ‹ฐ์ปค (์˜ˆ: AAPL, MSFT, 005930.KS, BTC-USD)")
        horizon = gr.Slider(5, 365, value=90, step=1, label="์˜ˆ์ธก ์Šคํ… H (๊ฐ„๊ฒฉ ๋‹จ์œ„์™€ ๋™์ผ)")
    with gr.Row():
        start = gr.Textbox(value="2014-09-17", 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"], value="cpu", label="๋””๋ฐ”์ด์Šค")
        interval = gr.Dropdown(
            choices=["1d", "1h", "30m", "15m", "5m"],
            value="1d",
            label="๊ฐ„๊ฒฉ"
        )
    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()