Imp3rtinence commited on
Commit
29ae4db
·
1 Parent(s): cf178b5

Add Kronos-Tokenizer-base and fix handler

Browse files
handler.py CHANGED
@@ -1,53 +1,43 @@
1
  import torch
2
- import json
3
- from safetensors.torch import load_file
4
- from model.kronos import Kronos
 
5
 
6
  class EndpointHandler:
7
  def __init__(self, path=""):
8
- with open(f"{path}/config.json", "r") as f:
9
- config = json.load(f)
10
-
11
- self.model = Kronos(
12
- input_dim=config.get("input_dim", 5),
13
- d_model=config.get("d_model", 256),
14
- nhead=config.get("nhead", 8),
15
- num_layers=config.get("num_layers", 6),
16
- dim_feedforward=config.get("dim_feedforward", 1024),
17
- max_seq_len=config.get("max_seq_len", 512),
18
- output_dim=config.get("output_dim", 5),
19
- dropout=config.get("dropout", 0.1),
20
- )
21
-
22
- weights = load_file(f"{path}/model.safetensors")
23
- self.model.load_state_dict(weights)
24
- self.model.eval()
25
 
26
  def __call__(self, data):
27
  inputs = data.get("inputs", [])
28
  parameters = data.get("parameters", {})
29
  prediction_length = parameters.get("prediction_length", 8)
30
 
 
 
 
 
31
  if isinstance(inputs[0], list):
32
- ohlcv = inputs
33
  else:
34
- ohlcv = [[v, v, v, v, 0] for v in inputs]
35
 
36
- tensor = torch.tensor([ohlcv], dtype=torch.float32)
 
37
 
38
- last_close = ohlcv[-1][3]
39
- if last_close > 0:
40
- tensor = tensor / last_close
41
 
42
- with torch.no_grad():
43
- output = self.model(tensor)
44
-
45
- predicted = output[0, -prediction_length:, :].tolist()
46
-
47
- if last_close > 0:
48
- predicted = [[v * last_close for v in candle] for candle in predicted]
49
 
50
- return {
51
- "predictions": predicted,
52
- "prediction_length": prediction_length,
53
- }
 
1
  import torch
2
+ import numpy as np
3
+ import pandas as pd
4
+ import os
5
+ from model.kronos import Kronos, KronosTokenizer, KronosPredictor
6
 
7
  class EndpointHandler:
8
  def __init__(self, path=""):
9
+ tokenizer_path = os.path.join(path, "tokenizer")
10
+ tokenizer = KronosTokenizer.from_pretrained(tokenizer_path)
11
+ model = Kronos.from_pretrained(path)
12
+ self.predictor = KronosPredictor(model, tokenizer, device="cpu", max_context=512)
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def __call__(self, data):
15
  inputs = data.get("inputs", [])
16
  parameters = data.get("parameters", {})
17
  prediction_length = parameters.get("prediction_length", 8)
18
 
19
+ if len(inputs) == 0:
20
+ return {"error": "No input data"}
21
+
22
+ cols = ["open", "high", "low", "close", "volume"]
23
  if isinstance(inputs[0], list):
24
+ df = pd.DataFrame(inputs, columns=cols[:len(inputs[0])])
25
  else:
26
+ df = pd.DataFrame({"open": inputs, "high": inputs, "low": inputs, "close": inputs})
27
 
28
+ if "volume" not in df.columns:
29
+ df["volume"] = 0.0
30
 
31
+ now = pd.Timestamp.now()
32
+ x_timestamps = pd.date_range(end=now, periods=len(df), freq="15min")
33
+ y_timestamps = pd.date_range(start=now + pd.Timedelta("15min"), periods=prediction_length, freq="15min")
34
 
35
+ pred_df = self.predictor.predict(
36
+ df, x_timestamps, y_timestamps,
37
+ pred_len=prediction_length,
38
+ T=1.0, top_k=0, top_p=0.9,
39
+ sample_count=5, verbose=False
40
+ )
 
41
 
42
+ result = pred_df[["open", "high", "low", "close"]].values.tolist()
43
+ return {"predictions": result}
 
 
tokenizer/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
tokenizer/README.md ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ pipeline_tag: time-series-forecasting
4
+ tags:
5
+ - Finance
6
+ - Candlestick
7
+ - K-line
8
+ library_name: pytorch
9
+ ---
10
+
11
+ # Kronos: A Foundation Model for the Language of Financial Markets
12
+
13
+ [![Paper](https://img.shields.io/badge/Paper-2508.02739-b31b1b.svg)](https://arxiv.org/abs/2508.02739)
14
+ [![Live Demo](https://img.shields.io/badge/%F0%9F%9A%80-Live_Demo-brightgreen)](https://shiyu-coder.github.io/Kronos-demo/)
15
+ [![GitHub](https://img.shields.io/badge/%F0%9F%92%BB-GitHub-blue?logo=github)](https://github.com/shiyu-coder/Kronos)
16
+
17
+ <p align="center">
18
+ <img src="https://github.com/shiyu-coder/Kronos/blob/master/figures/logo.png?raw=true" alt="Kronos Logo" width="100">
19
+ </p>
20
+
21
+ **Kronos** is the **first open-source foundation model** for financial candlesticks (K-lines), trained on data from over **45 global exchanges**. It is designed to handle the unique, high-noise characteristics of financial data.
22
+
23
+ ## Introduction
24
+
25
+ Kronos is a family of decoder-only foundation models, pre-trained specifically for the "language" of financial markets—K-line sequences. It leverages a novel two-stage framework:
26
+ 1. A specialized tokenizer first quantizes continuous, multi-dimensional K-line data (OHLCV) into **hierarchical discrete tokens**.
27
+ 2. A large, autoregressive Transformer is then pre-trained on these tokens, enabling it to serve as a unified model for diverse quantitative tasks.
28
+
29
+ <p align="center">
30
+ <img src="https://github.com/shiyu-coder/Kronos/blob/master/figures/overview.png?raw=true" alt="Kronos Overview" align="center" width="700px" />
31
+ </p>
32
+
33
+ The success of large-scale pre-training paradigm, exemplified by Large Language Models (LLMs), has inspired the development of Time Series Foundation Models (TSFMs). Kronos addresses existing limitations by introducing a specialized tokenizer that discretizes continuous market information into token sequences, preserving both price dynamics and trade activity patterns. We pre-train Kronos using an autoregressive objective on a massive, multi-market corpus of over 12 billion K-line records from 45 global exchanges, enabling it to learn nuanced temporal and cross-asset representations. Kronos excels in a zero-shot setting across a diverse set of financial tasks, including price series forecasting, volatility forecasting, and synthetic data generation.
34
+
35
+ ## Live Demo
36
+
37
+ We have set up a live demo to visualize Kronos's forecasting results. The webpage showcases a forecast for the **BTC/USDT** trading pair over the next 24 hours.
38
+
39
+ 👉 [Access the Live Demo Here](https://shiyu-coder.github.io/Kronos-demo/)
40
+
41
+ ## Model Zoo
42
+
43
+ We release a family of pre-trained models with varying capacities to suit different computational and application needs. All models are readily accessible from the Hugging Face Hub.
44
+
45
+ | Model | Tokenizer | Context length | Param | Hugging Face Model Card |
46
+ |--------------|---------------------------------------------------------------------------------| -------------- | ------ |--------------------------------------------------------------------------|
47
+ | Kronos-mini | [Kronos-Tokenizer-2k](https://huggingface.co/NeoQuasar/Kronos-Tokenizer-2k) | 2048 | 4.1M | ✅ [NeoQuasar/Kronos-mini](https://huggingface.co/NeoQuasar/Kronos-mini) |
48
+ | Kronos-small | [Kronos-Tokenizer-base](https://huggingface.co/NeoQuasar/Kronos-Tokenizer-base) | 512 | 24.7M | ✅ [NeoQuasar/Kronos-small](https://huggingface.co/NeoQuasar/Kronos-small) |
49
+ | Kronos-base | [Kronos-Tokenizer-base](https://huggingface.co/NeoQuasar/Kronos-Tokenizer-base) | 512 | 102.3M | ✅ [NeoQuasar/Kronos-base](https://huggingface.co/NeoQuasar/Kronos-base) |
50
+ | Kronos-large | [Kronos-Tokenizer-base](https://huggingface.co/NeoQuasar/Kronos-Tokenizer-base) | 512 | 499.2M | ❌ Not yet publicly available |
51
+
52
+ ## Getting Started: Making Forecasts
53
+
54
+ Forecasting with Kronos is straightforward using the `KronosPredictor` class. It handles data preprocessing, normalization, prediction, and inverse normalization, allowing you to get from raw data to forecasts in just a few lines of code.
55
+
56
+ **Important Note**: The `max_context` for `Kronos-small` and `Kronos-base` is **512**. This is the maximum sequence length the model can process. For optimal performance, it is recommended that your input data length (i.e., `lookback`) does not exceed this limit. The `KronosPredictor` will automatically handle truncation for longer contexts.
57
+
58
+ Here is a step-by-step guide to making your first forecast.
59
+
60
+ ### Installation
61
+
62
+ 1. Install Python 3.10+, and then install the dependencies from the [GitHub repository's `requirements.txt`](https://github.com/shiyu-coder/Kronos/blob/main/requirements.txt):
63
+
64
+ ```shell
65
+ pip install -r requirements.txt
66
+ ```
67
+
68
+ ### 1. Load the Tokenizer and Model
69
+
70
+ First, load a pre-trained Kronos model and its corresponding tokenizer from the Hugging Face Hub.
71
+
72
+ ```python
73
+ from model import Kronos, KronosTokenizer, KronosPredictor
74
+
75
+ # Load from Hugging Face Hub
76
+ tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
77
+ model = Kronos.from_pretrained("NeoQuasar/Kronos-small")
78
+ ```
79
+
80
+ ### 2. Instantiate the Predictor
81
+
82
+ Create an instance of `KronosPredictor`, passing the model, tokenizer, and desired device.
83
+
84
+ ```python
85
+ # Initialize the predictor
86
+ predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512)
87
+ ```
88
+
89
+ ### 3. Prepare Input Data
90
+
91
+ The `predict` method requires three main inputs:
92
+ - `df`: A pandas DataFrame containing the historical K-line data. It must include columns `['open', 'high', 'low', 'close']`. `volume` and `amount` are optional.
93
+ - `x_timestamp`: A pandas Series of timestamps corresponding to the historical data in `df`.
94
+ - `y_timestamp`: A pandas Series of timestamps for the future periods you want to predict.
95
+
96
+ ```python
97
+ import pandas as pd
98
+
99
+ # Load your data (example data can be found in the GitHub repo)
100
+ df = pd.read_csv("./data/XSHG_5min_600977.csv")
101
+ df['timestamps'] = pd.to_datetime(df['timestamps'])
102
+
103
+ # Define context window and prediction length
104
+ lookback = 400
105
+ pred_len = 120
106
+
107
+ # Prepare inputs for the predictor
108
+ x_df = df.loc[:lookback-1, ['open', 'high', 'low', 'close', 'volume', 'amount']]
109
+ x_timestamp = df.loc[:lookback-1, 'timestamps']
110
+ y_timestamp = df.loc[lookback:lookback+pred_len-1, 'timestamps']
111
+ ```
112
+
113
+ ### 4. Generate Forecasts
114
+
115
+ Call the `predict` method to generate forecasts. You can control the sampling process with parameters like `T`, `top_p`, and `sample_count` for probabilistic forecasting.
116
+
117
+ ```python
118
+ # Generate predictions
119
+ pred_df = predictor.predict(
120
+ df=x_df,
121
+ x_timestamp=x_timestamp,
122
+ y_timestamp=y_timestamp,
123
+ pred_len=pred_len,
124
+ T=1.0, # Temperature for sampling
125
+ top_p=0.9, # Nucleus sampling probability
126
+ sample_count=1 # Number of forecast paths to generate and average
127
+ )
128
+
129
+ print("Forecasted Data Head:")
130
+ print(pred_df.head())
131
+ ```
132
+
133
+ The `predict` method returns a pandas DataFrame containing the forecasted values for `open`, `high`, `low`, `close`, `volume`, and `amount`, indexed by the `y_timestamp` you provided.
134
+
135
+ ### 5. Example and Visualization
136
+
137
+ For a complete, runnable script that includes data loading, prediction, and plotting, please see [`examples/prediction_example.py`](https://github.com/shiyu-coder/Kronos/blob/main/examples/prediction_example.py) in the GitHub repository.
138
+
139
+ Running this script will generate a plot comparing the ground truth data against the model's forecast, similar to the one shown below:
140
+
141
+ <p align="center">
142
+ <img src="https://github.com/shiyu-coder/Kronos/blob/master/figures/prediction_example.png?raw=true" alt="Forecast Example" align="center" width="600px" />
143
+ </p>
144
+
145
+ Additionally, a script that makes predictions without Volume and Amount data can be found in [`examples/prediction_wo_vol_example.py`](https://github.com/shiyu-coder/Kronos/blob/main/examples/prediction_wo_vol_example.py).
146
+
147
+ ## 🔧 Finetuning on Your Own Data (A-Share Market Example)
148
+
149
+ Refer to the [README](https://github.com/shiyu-coder/Kronos) of GitHub repository.
150
+
151
+ ## Citation
152
+
153
+ If you use Kronos in your research, we would appreciate a citation to our [paper](https://huggingface.co/papers/2508.02739):
154
+
155
+ ```bibtex
156
+ @misc{shi2025kronos,
157
+ title={Kronos: A Foundation Model for the Language of Financial Markets},
158
+ author={Yu Shi and Zongliang Fu and Shuo Chen and Bohan Zhao and Wei Xu and Changshui Zhang and Jian Li},
159
+ year={2025},
160
+ eprint={2508.02739},
161
+ archivePrefix={arXiv},
162
+ primaryClass={q-fin.ST},
163
+ url={https://arxiv.org/abs/2508.02739},
164
+ }
165
+ ```
166
+
167
+ ## License
168
+
169
+ This project is licensed under the [MIT License](https://github.com/shiyu-coder/Kronos/blob/main/LICENSE).
tokenizer/config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attn_dropout_p": 0.0,
3
+ "beta": 0.05,
4
+ "d_in": 6,
5
+ "d_model": 256,
6
+ "ff_dim": 512,
7
+ "ffn_dropout_p": 0.0,
8
+ "gamma": 1.1,
9
+ "gamma0": 1.0,
10
+ "group_size": 4,
11
+ "n_dec_layers": 4,
12
+ "n_enc_layers": 4,
13
+ "n_heads": 4,
14
+ "resid_dropout_p": 0.0,
15
+ "s1_bits": 10,
16
+ "s2_bits": 10,
17
+ "zeta": 0.05
18
+ }
tokenizer/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59d85f6af76a2c3b8240ea06cb21db4213b4eeca053f246b23e29cf832fc6bee
3
+ size 15842368