Kronos Documentation

Kronos: A Foundation Model for the Language of Financial Markets

23,739 stars Python Python 1 file · ~5,958 tokens
RAW Doc

File: README.md

Kronos is the first open-source foundation model for financial candlesticks (K-lines),
trained on data from over 45 global exchanges.

📰 News

  • 🚩 [2025.11.10] Kronos has been accpeted by AAAI 2026.
  • 🚩 [2025.08.17] We have released the scripts for fine-tuning! Check them out to adapt Kronos to your own tasks.
  • 🚩 [2025.08.02] Our paper is now available on arXiv!

✨ Live Demo

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.

👉 Access the Live Demo Here

📦 Model Zoo

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.

Model Tokenizer Context length Params Open-source
Kronos-mini Kronos-Tokenizer-2k 2048 4.1M ✅ NeoQuasar/Kronos-mini
Kronos-small Kronos-Tokenizer-base 512 24.7M ✅ NeoQuasar/Kronos-small
Kronos-base Kronos-Tokenizer-base 512 102.3M ✅ NeoQuasar/Kronos-base
Kronos-large Kronos-Tokenizer-base 512 499.2M ❌

🚀 Getting Started

Installation

  1. Install Python 3.10+, and then install the dependencies:
shell
pip install -r requirements.txt

📈 Making Forecasts

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.

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.

Here is a step-by-step guide to making your first forecast.

1. Load the Tokenizer and Model

First, load a pre-trained Kronos model and its corresponding tokenizer from the Hugging Face Hub.

python
from model import Kronos, KronosTokenizer, KronosPredictor

# Load from Hugging Face Hub
tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
model = Kronos.from_pretrained("NeoQuasar/Kronos-small")

2. Instantiate the Predictor

Create an instance of KronosPredictor, passing the model, tokenizer, and desired device.

python
# Initialize the predictor
predictor = KronosPredictor(model, tokenizer, max_context=512)

3. Prepare Input Data

The predict method requires three main inputs:

  • df: A pandas DataFrame containing the historical K-line data. It must include columns ['open', 'high', 'low', 'close']. volume and amount are optional.
  • x_timestamp: A pandas Series of timestamps corresponding to the historical data in df.
  • y_timestamp: A pandas Series of timestamps for the future periods you want to predict.
python
import pandas as pd

# Load your data
df = pd.read_csv("./data/XSHG_5min_600977.csv")
df['timestamps'] = pd.to_datetime(df['timestamps'])

# Define context window and prediction length
lookback = 400
pred_len = 120

# Prepare inputs for the predictor
x_df = df.loc[:lookback-1, ['open', 'high', 'low', 'close', 'volume', 'amount']]
x_timestamp = df.loc[:lookback-1, 'timestamps']
y_timestamp = df.loc[lookback:lookback+pred_len-1, 'timestamps']

4. Generate Forecasts

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.

python
# Generate predictions
pred_df = predictor.predict(
    df=x_df,
    x_timestamp=x_timestamp,
    y_timestamp=y_timestamp,
    pred_len=pred_len,
    T=1.0,          # Temperature for sampling
    top_p=0.9,      # Nucleus sampling probability
    sample_count=1  # Number of forecast paths to generate and average
)

print("Forecasted Data Head:")
print(pred_df.head())

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.

For efficient processing of multiple time series, Kronos provides a predict_batch method that enables parallel prediction on multiple datasets simultaneously. This is particularly useful when you need to forecast multiple assets or time periods at once.

python
# Prepare multiple datasets for batch prediction
df_list = [df1, df2, df3]  # List of DataFrames
x_timestamp_list = [x_ts1, x_ts2, x_ts3]  # List of historical timestamps
y_timestamp_list = [y_ts1, y_ts2, y_ts3]  # List of future timestamps

# Generate batch predictions
pred_df_list = predictor.predict_batch(
    df_list=df_list,
    x_timestamp_list=x_timestamp_list,
    y_timestamp_list=y_timestamp_list,
    pred_len=pred_len,
    T=1.0,
    top_p=0.9,
    sample_count=1,
    verbose=True
)

# pred_df_list contains prediction results in the same order as input
for i, pred_df in enumerate(pred_df_list):
    print(f"Predictions for series {i}:")
    print(pred_df.head())

Important Requirements for Batch Prediction:

  • All series must have the same historical length (lookback window)
  • All series must have the same prediction length (pred_len)
  • Each DataFrame must contain the required columns: ['open', 'high', 'low', 'close']
  • volume and amount columns are optional and will be filled with zeros if missing

The predict_batch method leverages GPU parallelism for efficient processing and automatically handles normalization and denormalization for each series independently.

5. Example and Visualization

For a complete, runnable script that includes data loading, prediction, and plotting, please see examples/prediction_example.py.

Running this script will generate a plot comparing the ground truth data against the model's forecast, similar to the one shown below:

Additionally, we provide a script that makes predictions without Volume and Amount data, which can be found in examples/prediction_wo_vol_example.py.

🔧 Finetuning on Your Own Data (A-Share Market Example)

We provide a complete pipeline for finetuning Kronos on your own datasets. As an example, we demonstrate how to use Qlib to prepare data from the Chinese A-share market and conduct a simple backtest.

Disclaimer: This pipeline is intended as a demonstration to illustrate the finetuning process. It is a simplified example and not a production-ready quantitative trading system. A robust quantitative strategy requires more sophisticated techniques, such as portfolio optimization and risk factor neutralization, to achieve stable alpha.

The finetuning process is divided into four main steps:

  1. Configuration: Set up paths and hyperparameters.
  2. Data Preparation: Process and split your data using Qlib.
  3. Model Finetuning: Finetune the Tokenizer and the Predictor models.
  4. Backtesting: Evaluate the finetuned model's performance.

Prerequisites

  1. First, ensure you have all dependencies from requirements.txt installed.
  2. This pipeline relies on qlib. Please install it:
    shell
    pip install pyqlib
  3. You will need to prepare your Qlib data. Follow the official Qlib guide to download and set up your data locally. The example scripts assume you are using daily frequency data.

Step 1: Configure Your Experiment

All settings for data, training, and model paths are centralized in finetune/config.py. Before running any scripts, please modify the following paths according to your environment:

  • qlib_data_path: Path to your local Qlib data directory.
  • dataset_path: Directory where the processed train/validation/test pickle files will be saved.
  • save_path: Base directory for saving model checkpoints.
  • backtest_result_path: Directory for saving backtesting results.
  • pretrained_tokenizer_path and pretrained_predictor_path: Paths to the pre-trained models you want to start from (can be local paths or Hugging Face model names).

You can also adjust other parameters like instrument, train_time_range, epochs, and batch_size to fit your specific task. If you don't use Comet.ml, set use_comet = False.

Step 2: Prepare the Dataset

Run the data preprocessing script. This script will load raw market data from your Qlib directory, process it, split it into training, validation, and test sets, and save them as pickle files.

shell
python finetune/qlib_data_preprocess.py

After running, you will find train_data.pkl, val_data.pkl, and test_data.pkl in the directory specified by dataset_path in your config.

Step 3: Run the Finetuning

The finetuning process consists of two stages: finetuning the tokenizer and then the predictor. Both training scripts are designed for multi-GPU training using torchrun.

3.1 Finetune the Tokenizer

This step adjusts the tokenizer to the data distribution of your specific domain.

shell
# Replace NUM_GPUS with the number of GPUs you want to use (e.g., 2)
torchrun --standalone --nproc_per_node=NUM_GPUS finetune/train_tokenizer.py

The best tokenizer checkpoint will be saved to the path configured in config.py (derived from save_path and tokenizer_save_folder_name).

3.2 Finetune the Predictor

This step finetunes the main Kronos model for the forecasting task.

shell
# Replace NUM_GPUS with the number of GPUs you want to use (e.g., 2)
torchrun --standalone --nproc_per_node=NUM_GPUS finetune/train_predictor.py

The best predictor checkpoint will be saved to the path configured in config.py.

Step 4: Evaluate with Backtesting

Finally, run the backtesting script to evaluate your finetuned model. This script loads the models, performs inference on the test set, generates prediction signals (e.g., forecasted price change), and runs a simple top-K strategy backtest.

shell
# Specify the GPU for inference
python finetune/qlib_test.py --device cuda:0

The script will output a detailed performance analysis in your console and generate a plot showing the cumulative return curves of your strategy against the benchmark, similar to the one below:

💡 From Demo to Production: Important Considerations

  • Raw Signals vs. Pure Alpha: The signals generated by the model in this demo are raw predictions. In a real-world quantitative workflow, these signals would typically be fed into a portfolio optimization model. This model would apply constraints to neutralize exposure to common risk factors (e.g., market beta, style factors like size and value), thereby isolating the "pure alpha" and improving the strategy's robustness.
  • Data Handling: The provided QlibDataset is an example. For different data sources or formats, you will need to adapt the data loading and preprocessing logic.
  • Strategy and Backtesting Complexity: The simple top-K strategy used here is a basic starting point. Production-level strategies often incorporate more complex logic for portfolio construction, dynamic position sizing, and risk management (e.g., stop-loss/take-profit rules). Furthermore, a high-fidelity backtest should meticulously model transaction costs, slippage, and market impact to provide a more accurate estimate of real-world performance.

📝 AI-Generated Comments: Please note that many of the code comments within the finetune/ directory were generated by an AI assistant (Gemini 2.5 Pro) for explanatory purposes. While they aim to be helpful, they may contain inaccuracies. We recommend treating the code itself as the definitive source of logic.

📖 Citation

If you use Kronos in your research, we would appreciate a citation to our paper:

text
@misc{shi2025kronos,
      title={Kronos: A Foundation Model for the Language of Financial Markets}, 
      author={Yu Shi and Zongliang Fu and Shuo Chen and Bohan Zhao and Wei Xu and Changshui Zhang and Jian Li},
      year={2025},
      eprint={2508.02739},
      archivePrefix={arXiv},
      primaryClass={q-fin.ST},
      url={https://arxiv.org/abs/2508.02739}, 
}

📜 License

This project is licensed under the MIT License.


File: finetune_csv/README.md

Kronos Fine-tuning on Custom CSV Datasets

This module provides a comprehensive pipeline for fine-tuning Kronos models on your own CSV-formatted financial data. It supports both sequential training (tokenizer followed by predictor) and individual component training, with full distributed training capabilities.

1. Data Preparation

Required Data Format

Your CSV file must contain the following columns:

  • timestamps: DateTime stamps for each data point
  • open: Opening price
  • high: Highest price
  • low: Lowest price
  • close: Closing price
  • volume: Trading volume
  • amount: Trading amount

(volume and amount can be 0 if not available)

Sample Data Format

timestamps open close high low volume amount
2019/11/26 9:35 182.45215 184.45215 184.95215 182.45215 15136000 0
2019/11/26 9:40 184.35215 183.85215 184.55215 183.45215 4433300 0
2019/11/26 9:45 183.85215 183.35215 183.95215 182.95215 3070900 0

Reference: Check data/HK_ali_09988_kline_5min_all.csv for a complete example of the proper data format.

2. Config Preparation

Please edit the correct data path & pretrained model path and set your training parameters.

yaml
# Data configuration
data:
  data_path: "/path/to/your/data.csv"
  lookback_window: 512        # Historical data points to use
  predict_window: 48           # Future points to predict
  max_context: 512            # Maximum context length

...

There are some other settings here, please see configs/config_ali09988_candle-5min.yaml for more comments.

3. Training

The train_sequential.py script handles the complete training pipeline automatically:

bash
# Complete training (tokenizer + predictor)
python train_sequential.py --config configs/config_ali09988_candle-5min.yaml

# Skip existing models
python train_sequential.py --config configs/config_ali09988_candle-5min.yaml --skip-existing

# Only train tokenizer
python train_sequential.py --config configs/config_ali09988_candle-5min.yaml --skip-basemodel

# Only train predictor
python train_sequential.py --config configs/config_ali09988_candle-5min.yaml --skip-tokenizer

Method 2: Individual Component Training

Train each component separately for more control:

bash
# Step 1: Train tokenizer
python finetune_tokenizer.py --config configs/config_ali09988_candle-5min.yaml

# Step 2: Train predictor (requires fine-tuned tokenizer)
python finetune_base_model.py --config configs/config_ali09988_candle-5min.yaml

DDP Training

For faster training on multiple GPUs:

bash
# Set communication backend (nccl for NVIDIA GPUs, gloo for CPU/mixed)
DIST_BACKEND=nccl \
torchrun --standalone --nproc_per_node=8 train_sequential.py --config configs/config_ali09988_candle-5min.yaml

4. Training Results

The training process generates several outputs:

Model Checkpoints

  • Tokenizer: Saved to {base_save_path}/{exp_name}/tokenizer/best_model/
  • Predictor: Saved to {base_save_path}/{exp_name}/basemodel/best_model/

Training Logs

  • Console output: Real-time training progress and metrics
  • Log files: Detailed logs saved to {base_save_path}/logs/
  • Validation tracking: Best models are saved based on validation loss

5. Prediction Vis

The following images show example training results on alibaba (HK stock) data:


File: finetune_csv/README_CN.md

Kronos微调-支持自定义CSV数据集

这是一个在自定义的CSV格式数据上微调Kronos模型的完整流程。包含顺序训练(先训练tokenizer再训练predictor)和单独模块训练,同时支持分布式训练。

1. 准备数据

数据格式

CSV文件必须包含以下列:

  • timestamps: 每个数据点的时间戳
  • open: 开盘价
  • high: 最高价
  • low: 最低价
  • close: 收盘价
  • volume: 交易量
  • amount: 交易金额

(volume和amount可以全0如果没有这部分的数据)

示例数据格式

timestamps open close high low volume amount
2019/11/26 9:35 182.45215 184.45215 184.95215 182.45215 15136000 0
2019/11/26 9:40 184.35215 183.85215 184.55215 183.45215 4433300 0
2019/11/26 9:45 183.85215 183.35215 183.95215 182.95215 3070900 0

标准数据样例: data/HK_ali_09988_kline_5min_all.csv

2. 准备config文件

data_path及预训练模型路径需要修改,训练参数可以自己调节

yaml
# 数据配置
data:
  data_path: "/path/to/your/data.csv"
  lookback_window: 512        # 要使用的历史数据点
  predict_window: 48           # 要预测的未来点数
  max_context: 512            # 最大上下文长度

...

这里还有其他一些设置, configs/config_ali09988_candle-5min.yaml 有更详细的注释。

3. 训练

方法1: 直接顺序训练

train_sequential.py 脚本自动处理完整的训练流程:

bash
# 完整训练(tokenizer + predictor)
python train_sequential.py --config configs/config_ali09988_candle-5min.yaml

# 跳过已存在的模型
python train_sequential.py --config configs/config_ali09988_candle-5min.yaml --skip-existing

# 只训练tokenizer
python train_sequential.py --config configs/config_ali09988_candle-5min.yaml --skip-basemodel

# 只训练predictor
python train_sequential.py --config configs/config_ali09988_candle-5min.yaml --skip-tokenizer

方法2: 单独组件训练

可以单独训练每个组件:

bash
# 步骤1: 训练tokenizer
python finetune_tokenizer.py --config configs/config_ali09988_candle-5min.yaml

# 步骤2: 训练predictor(需要微调后的tokenizer)
python finetune_base_model.py --config configs/config_ali09988_candle-5min.yaml

DDP训练

如果有多卡,可以开启ddp加速训练:

bash
# 设置通信后端(NVIDIA GPU用nccl,CPU/混合用gloo)
DIST_BACKEND=nccl \
torchrun --standalone --nproc_per_node=8 train_sequential.py --config configs/config_ali09988_candle-5min.yaml

4. 训练结果

训练过程生成以下输出:

模型检查点

  • Tokenizer: 保存到 {base_save_path}/{exp_name}/tokenizer/best_model/
  • Predictor: 保存到 {base_save_path}/{exp_name}/basemodel/best_model/

训练日志

  • 控制台输出: 实时训练进度和指标
  • 日志文件: 详细日志保存到 {base_save_path}/logs/
  • 验证跟踪: 基于验证损失保存最佳模型

5. 预测可视化

以下图像显示了kronos在阿里巴巴股票数据上微调后的示例训练结果:


File: webui/README.md

Kronos Web UI

Web user interface for Kronos financial prediction model, providing intuitive graphical operation interface.

✨ Features

  • Multi-format data support: Supports CSV, Feather and other financial data formats
  • Smart time window: Fixed 400+120 data point time window slider selection
  • Real model prediction: Integrated real Kronos model, supports multiple model sizes
  • Prediction quality control: Adjustable temperature, nucleus sampling, sample count and other parameters
  • Multi-device support: Supports CPU, CUDA, MPS and other computing devices
  • Comparison analysis: Detailed comparison between prediction results and actual data
  • K-line chart display: Professional financial K-line chart display

🚀 Quick Start

Method 1: Start with Python script

bash
cd webui
python run.py

Method 2: Start with Shell script

bash
cd webui
chmod +x start.sh
./start.sh

Method 3: Start Flask application directly

bash
cd webui
python app.py

After successful startup, visit http://localhost:7070

📋 Usage Steps

  1. Load data: Select financial data file from data directory
  2. Load model: Select Kronos model and computing device
  3. Set parameters: Adjust prediction quality parameters
  4. Select time window: Use slider to select 400+120 data point time range
  5. Start prediction: Click prediction button to generate results
  6. View results: View prediction results in charts and tables

🔧 Prediction Quality Parameters

Temperature (T)

  • Range: 0.1 - 2.0
  • Effect: Controls prediction randomness
  • Recommendation: 1.2-1.5 for better prediction quality

Nucleus Sampling (top_p)

  • Range: 0.1 - 1.0
  • Effect: Controls prediction diversity
  • Recommendation: 0.95-1.0 to consider more possibilities

Sample Count

  • Range: 1 - 5
  • Effect: Generate multiple prediction samples
  • Recommendation: 2-3 samples to improve quality

📊 Supported Data Formats

Required Columns

  • open: Opening price
  • high: Highest price
  • low: Lowest price
  • close: Closing price

Optional Columns

  • volume: Trading volume
  • amount: Trading amount (not used for prediction)
  • timestamps/timestamp/date: Timestamp

🤖 Model Support

  • Kronos-mini: 4.1M parameters, lightweight fast prediction
  • Kronos-small: 24.7M parameters, balanced performance and speed
  • Kronos-base: 102.3M parameters, high quality prediction

🖥️ GPU Acceleration Support

  • CPU: General computing, best compatibility
  • CUDA: NVIDIA GPU acceleration, best performance
  • MPS: Apple Silicon GPU acceleration, recommended for Mac users

⚠️ Notes

  • amount column is not used for prediction, only for display
  • Time window is fixed at 400+120=520 data points
  • Ensure data file contains sufficient historical data
  • First model loading may require download, please be patient

🔍 Comparison Analysis

The system automatically provides comparison analysis between prediction results and actual data, including:

  • Price difference statistics
  • Error analysis
  • Prediction quality assessment

🛠️ Technical Architecture

  • Backend: Flask + Python
  • Frontend: HTML + CSS + JavaScript
  • Charts: Plotly.js
  • Data processing: Pandas + NumPy
  • Model: Hugging Face Transformers

📝 Troubleshooting

Common Issues

  1. Port occupied: Modify port number in app.py
  2. Missing dependencies: Run pip install -r requirements.txt
  3. Model loading failed: Check network connection and model ID
  4. Data format error: Ensure data column names and format are correct

Log Viewing

Detailed runtime information will be displayed in the console at startup, including model status and error messages.

📄 License

This project follows the license terms of the original Kronos project.

🤝 Contributing

Welcome to submit Issues and Pull Requests to improve this Web UI!

📞 Support

If you have questions, please check:

  1. Project documentation
  2. GitHub Issues
  3. Console error messages