You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

168 lines
8.7 KiB

1 month ago
  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. # Kronos: A Foundation Model for the Language of Financial Markets
  11. [![Paper](https://img.shields.io/badge/Paper-2508.02739-b31b1b.svg)](https://arxiv.org/abs/2508.02739)
  12. [![Live Demo](https://img.shields.io/badge/%F0%9F%9A%80-Live_Demo-brightgreen)](https://shiyu-coder.github.io/Kronos-demo/)
  13. [![GitHub](https://img.shields.io/badge/%F0%9F%92%BB-GitHub-blue?logo=github)](https://github.com/shiyu-coder/Kronos)
  14. <p align="center">
  15. <img src="https://github.com/shiyu-coder/Kronos/blob/master/figures/logo.png?raw=true" alt="Kronos Logo" width="100">
  16. </p>
  17. **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.
  18. ## Introduction
  19. 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:
  20. 1. A specialized tokenizer first quantizes continuous, multi-dimensional K-line data (OHLCV) into **hierarchical discrete tokens**.
  21. 2. A large, autoregressive Transformer is then pre-trained on these tokens, enabling it to serve as a unified model for diverse quantitative tasks.
  22. <p align="center">
  23. <img src="https://github.com/shiyu-coder/Kronos/blob/master/figures/overview.png?raw=true" alt="Kronos Overview" align="center" width="700px" />
  24. </p>
  25. 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.
  26. ## Live Demo
  27. 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.
  28. 👉 [Access the Live Demo Here](https://shiyu-coder.github.io/Kronos-demo/)
  29. ## Model Zoo
  30. 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.
  31. | Model | Tokenizer | Context length | Param | Hugging Face Model Card |
  32. |--------------|---------------------------------------------------------------------------------| -------------- | ------ |--------------------------------------------------------------------------|
  33. | Kronos-mini | [Kronos-Tokenizer-2k](https://huggingface.co/NeoQuasar/Kronos-Tokenizer-2k) | 2048 | 4.1M | ✅ [NeoQuasar/Kronos-mini](https://huggingface.co/NeoQuasar/Kronos-mini) |
  34. | Kronos-small | [Kronos-Tokenizer-base](https://huggingface.co/NeoQuasar/Kronos-Tokenizer-base) | 512 | 24.7M | ✅ [NeoQuasar/Kronos-small](https://huggingface.co/NeoQuasar/Kronos-small) |
  35. | Kronos-base | [Kronos-Tokenizer-base](https://huggingface.co/NeoQuasar/Kronos-Tokenizer-base) | 512 | 102.3M | ✅ [NeoQuasar/Kronos-base](https://huggingface.co/NeoQuasar/Kronos-base) |
  36. | Kronos-large | [Kronos-Tokenizer-base](https://huggingface.co/NeoQuasar/Kronos-Tokenizer-base) | 512 | 499.2M | ❌ Not yet publicly available |
  37. ## Getting Started: Making Forecasts
  38. 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.
  39. **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.
  40. Here is a step-by-step guide to making your first forecast.
  41. ### Installation
  42. 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):
  43. ```shell
  44. pip install -r requirements.txt
  45. ```
  46. ### 1. Load the Tokenizer and Model
  47. First, load a pre-trained Kronos model and its corresponding tokenizer from the Hugging Face Hub.
  48. ```python
  49. from model import Kronos, KronosTokenizer, KronosPredictor
  50. # Load from Hugging Face Hub
  51. tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
  52. model = Kronos.from_pretrained("NeoQuasar/Kronos-small")
  53. ```
  54. ### 2. Instantiate the Predictor
  55. Create an instance of `KronosPredictor`, passing the model, tokenizer, and desired device.
  56. ```python
  57. # Initialize the predictor
  58. predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512)
  59. ```
  60. ### 3. Prepare Input Data
  61. The `predict` method requires three main inputs:
  62. - `df`: A pandas DataFrame containing the historical K-line data. It must include columns `['open', 'high', 'low', 'close']`. `volume` and `amount` are optional.
  63. - `x_timestamp`: A pandas Series of timestamps corresponding to the historical data in `df`.
  64. - `y_timestamp`: A pandas Series of timestamps for the future periods you want to predict.
  65. ```python
  66. import pandas as pd
  67. # Load your data (example data can be found in the GitHub repo)
  68. df = pd.read_csv("./data/XSHG_5min_600977.csv")
  69. df['timestamps'] = pd.to_datetime(df['timestamps'])
  70. # Define context window and prediction length
  71. lookback = 400
  72. pred_len = 120
  73. # Prepare inputs for the predictor
  74. x_df = df.loc[:lookback-1, ['open', 'high', 'low', 'close', 'volume', 'amount']]
  75. x_timestamp = df.loc[:lookback-1, 'timestamps']
  76. y_timestamp = df.loc[lookback:lookback+pred_len-1, 'timestamps']
  77. ```
  78. ### 4. Generate Forecasts
  79. 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.
  80. ```python
  81. # Generate predictions
  82. pred_df = predictor.predict(
  83. df=x_df,
  84. x_timestamp=x_timestamp,
  85. y_timestamp=y_timestamp,
  86. pred_len=pred_len,
  87. T=1.0, # Temperature for sampling
  88. top_p=0.9, # Nucleus sampling probability
  89. sample_count=1 # Number of forecast paths to generate and average
  90. )
  91. print("Forecasted Data Head:")
  92. print(pred_df.head())
  93. ```
  94. 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.
  95. ### 5. Example and Visualization
  96. 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.
  97. Running this script will generate a plot comparing the ground truth data against the model's forecast, similar to the one shown below:
  98. <p align="center">
  99. <img src="https://github.com/shiyu-coder/Kronos/blob/master/figures/prediction_example.png?raw=true" alt="Forecast Example" align="center" width="600px" />
  100. </p>
  101. 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).
  102. ## 🔧 Finetuning on Your Own Data (A-Share Market Example)
  103. Refer to the [README](https://github.com/shiyu-coder/Kronos) of GitHub repository.
  104. ## Citation
  105. If you use Kronos in your research, we would appreciate a citation to our [paper](https://huggingface.co/papers/2508.02739):
  106. ```bibtex
  107. @misc{shi2025kronos,
  108. title={Kronos: A Foundation Model for the Language of Financial Markets},
  109. author={Yu Shi and Zongliang Fu and Shuo Chen and Bohan Zhao and Wei Xu and Changshui Zhang and Jian Li},
  110. year={2025},
  111. eprint={2508.02739},
  112. archivePrefix={arXiv},
  113. primaryClass={q-fin.ST},
  114. url={https://arxiv.org/abs/2508.02739},
  115. }
  116. ```
  117. ## License
  118. This project is licensed under the [MIT License](https://github.com/shiyu-coder/Kronos/blob/main/LICENSE).