File size: 9,087 Bytes
a252e46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13508c
 
 
a252e46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""HuggingFace Inference Endpoint custom handler for Kronos.

Kronos (https://github.com/shiyu-coder/Kronos) is a foundation model for K-line
forecasting. This handler loads the pretrained tokenizer + model from the HF
hub once at startup, then accepts batches of historical OHLCV data and returns
probabilistic forecasts (mean path + confidence band from N stochastic samples).

Expected request body (JSON):
  {
    "history": [
      {"timestamp": "2024-01-01", "open": 100.0, "high": 102.1, "low": 99.4, "close": 101.5, "volume": 1234567, "amount": null},
      ...
    ],
    "pred_len": 30,                # number of future steps to forecast
    "n_samples": 30,               # stochastic samples (more = tighter CI, slower)
    "temperature": 1.0,            # sampling temperature
    "top_p": 0.9,                  # nucleus sampling
    "seed": 0                      # optional, for reproducibility
  }

Response shape:
  {
    "predictions": [
      {"step": 1, "open_mean": ..., "high_mean": ..., "low_mean": ..., "close_mean": ..., "volume_mean": ...,
       "close_low": ..., "close_high": ...},
      ...
    ],
    "history_len": <int>,
    "samples_used": <int>,
    "model": "Kronos-small"
  }
"""

from __future__ import annotations

import os
from datetime import datetime, timedelta
from typing import Any, Dict, List

import numpy as np
import pandas as pd
import torch

# Kronos itself lives in the shiyu-coder/Kronos repo. The HF endpoint image
# clones the repo so `from model import Kronos, KronosTokenizer, KronosPredictor`
# works directly. If you prefer to vendor the model files, copy `model/` from
# the repo into the same dir as this handler.
from model import Kronos, KronosPredictor, KronosTokenizer  # type: ignore


MODEL_REPO = os.environ.get("KRONOS_MODEL_REPO", "NeoQuasar/Kronos-small")
TOKENIZER_REPO = os.environ.get(
    "KRONOS_TOKENIZER_REPO", "NeoQuasar/Kronos-Tokenizer-base"
)
MAX_CONTEXT = int(os.environ.get("KRONOS_MAX_CONTEXT", "512"))
DEFAULT_PRED_LEN = int(os.environ.get("KRONOS_DEFAULT_PRED_LEN", "30"))
CI_LOWER = float(os.environ.get("KRONOS_CI_LOWER", "0.1"))   # 10th percentile
CI_UPPER = float(os.environ.get("KRONOS_CI_UPPER", "0.9"))   # 90th percentile


class EndpointHandler:
    """HuggingFace Inference Endpoint entrypoint.

    HF instantiates this once per worker; __call__ runs per request.
    """

    def __init__(self, path: str = "") -> None:
        device = "cuda" if torch.cuda.is_available() else "cpu"
        # `path` is the local snapshot of the repo HF pulled into the container.
        # We still need the *separate* tokenizer repo, so go through from_pretrained.
        self.tokenizer = KronosTokenizer.from_pretrained(TOKENIZER_REPO)
        self.model = Kronos.from_pretrained(MODEL_REPO)
        self.predictor = KronosPredictor(
            model=self.model,
            tokenizer=self.tokenizer,
            device=device,
            max_context=MAX_CONTEXT,
        )
        self.device = device

    def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
        # HF endpoints wrap the body in {"inputs": ...}. Be liberal about
        # accepting either form so the same code works in local tests too.
        inputs = data.get("inputs", data) if isinstance(data, dict) else {}
        if not isinstance(inputs, dict):
            return {"error": "inputs must be a JSON object"}

        history = inputs.get("history")
        if not isinstance(history, list) or len(history) < 32:
            return {
                "error": "history must be a list of >=32 OHLCV bars",
                "received_len": len(history) if isinstance(history, list) else 0,
            }

        pred_len = int(inputs.get("pred_len", DEFAULT_PRED_LEN))
        pred_len = max(1, min(pred_len, 120))
        # Free HF Space is CPU-only; aggressive default keeps a request under ~3 min.
        default_samples = int(os.environ.get("KRONOS_DEFAULT_SAMPLES", "5"))
        n_samples = int(inputs.get("n_samples", default_samples))
        n_samples = max(1, min(n_samples, 60))
        temperature = float(inputs.get("temperature", 1.0))
        top_p = float(inputs.get("top_p", 0.9))
        seed = inputs.get("seed")
        if seed is not None:
            torch.manual_seed(int(seed))
            np.random.seed(int(seed))

        df, timestamps = _history_to_dataframe(history)
        future_timestamps = _project_timestamps(timestamps, pred_len)

        # KronosPredictor.predict returns a DataFrame of OHLCV predictions.
        # We call it n_samples times and stack to compute CI bands. This is
        # how the official Kronos examples produce probabilistic forecasts.
        sample_frames: List[pd.DataFrame] = []
        for _ in range(n_samples):
            pred_df = self.predictor.predict(
                df=df,
                x_timestamp=pd.Series(timestamps),
                y_timestamp=pd.Series(future_timestamps),
                pred_len=pred_len,
                T=temperature,
                top_p=top_p,
                sample_count=1,
            )
            sample_frames.append(pred_df.reset_index(drop=True))

        # Stack into (n_samples, pred_len) arrays per column.
        cols = ["open", "high", "low", "close", "volume"]
        stacks = {c: np.stack([f[c].to_numpy() for f in sample_frames]) for c in cols}
        close_stack = stacks["close"]
        ci_low = np.quantile(close_stack, CI_LOWER, axis=0)
        ci_high = np.quantile(close_stack, CI_UPPER, axis=0)

        predictions = []
        for i in range(pred_len):
            row = {
                "step": i + 1,
                "timestamp": future_timestamps[i].isoformat(),
                "close_low": float(ci_low[i]),
                "close_high": float(ci_high[i]),
            }
            for c in cols:
                row[f"{c}_mean"] = float(stacks[c][:, i].mean())
            predictions.append(row)

        return {
            "predictions": predictions,
            "history_len": len(history),
            "samples_used": n_samples,
            "pred_len": pred_len,
            "model": MODEL_REPO.split("/")[-1],
            "ci_lower_pct": CI_LOWER,
            "ci_upper_pct": CI_UPPER,
        }


def _history_to_dataframe(
    history: List[Dict[str, Any]],
) -> tuple[pd.DataFrame, List[datetime]]:
    rows = []
    timestamps: List[datetime] = []
    for bar in history:
        ts = bar.get("timestamp")
        if isinstance(ts, str):
            timestamps.append(pd.to_datetime(ts).to_pydatetime())
        elif isinstance(ts, (int, float)):
            timestamps.append(datetime.utcfromtimestamp(float(ts)))
        else:
            # If timestamps weren't provided, synthesize a daily index. Kronos
            # doesn't actually condition on absolute dates, only their spacing,
            # so this is safe as long as the caller's history really is daily.
            timestamps.append(datetime(2000, 1, 1) + timedelta(days=len(timestamps)))
        rows.append(
            {
                "open": float(bar.get("open") or bar.get("close") or 0.0),
                "high": float(bar.get("high") or bar.get("close") or 0.0),
                "low": float(bar.get("low") or bar.get("close") or 0.0),
                "close": float(bar.get("close") or 0.0),
                "volume": float(bar.get("volume") or 0.0),
                # Kronos also wants `amount` (turnover). If absent, derive from
                # close*volume which is a reasonable proxy for daily turnover.
                "amount": float(
                    bar.get("amount")
                    or (bar.get("close") or 0.0) * (bar.get("volume") or 0.0)
                ),
            }
        )
    df = pd.DataFrame(rows)
    return df, timestamps


def _project_timestamps(history_ts: List[datetime], pred_len: int) -> List[datetime]:
    """Estimate the spacing of the history and roll forward by pred_len steps."""
    if len(history_ts) < 2:
        step = timedelta(days=1)
    else:
        deltas = [
            (history_ts[i] - history_ts[i - 1]) for i in range(1, len(history_ts))
        ]
        # Use the median spacing; robust to weekends/holidays in daily data.
        deltas_sorted = sorted(deltas)
        step = deltas_sorted[len(deltas_sorted) // 2]
        if step <= timedelta(0):
            step = timedelta(days=1)
    last = history_ts[-1]
    return [last + step * (i + 1) for i in range(pred_len)]


if __name__ == "__main__":
    # Smoke test: generate a sine-wave history and forecast 10 steps.
    handler = EndpointHandler()
    n = 256
    base = 100 + 5 * np.sin(np.linspace(0, 8 * np.pi, n))
    fake_hist = [
        {
            "timestamp": (datetime(2024, 1, 1) + timedelta(days=i)).isoformat(),
            "open": float(base[i]),
            "high": float(base[i] * 1.01),
            "low": float(base[i] * 0.99),
            "close": float(base[i]),
            "volume": 1_000_000,
        }
        for i in range(n)
    ]
    out = handler({"inputs": {"history": fake_hist, "pred_len": 10, "n_samples": 4}})
    print(out)