Welcome Forex EA downloads & MT4/MT5 auto-trading resources — EAs, Gold EAs, quant tools and real-world automation.
Sign In Sign Up

Kronos: the basic model of the language of financial markets | Trading script download - MT4/MT5 resources - MetaTrader 5 resources

author EAcpu | 11 reads | 0 comments |

Hugface Live Demonstration Final Submission GitHub Star GitHub Forks License Kronos is the first open source financial K-line basic model, which is trained using data from more than 45 exchanges around the world. 📰 News 🚩 [2025.08.17] We released the script for fine-tuning! Check out these scripts and adapt Kronos to your tasks. 🚩 [2025.08.02] Our paper is now available on arXiv! 📜 Introduction Kronos is a series of basic models used only for decoders, specifically pre-trained for the "language" of financial markets - K-line sequences. Unlike general-purpose TSFM models, Kronos is designed to handle the unique high-noise characteristics of financial data. It adopts a novel two-stage framework: a specialized marker first quantifies continuous multidimensional K-line data (OHLCV) into hierarchical discrete markers. These markers are then pre-trained on a large autoregressive Transformer, enabling it to serve as a unified model for a variety of quantitative tasks. ✨ Live Demonstration We have built a real-time demonstration platform to visually present Kronos’ prediction results. This page shows predictions for the BTC/USDT trading pair over the next 24 hours. https://github.com/shiyu-coder/Kronos 👉Access live demo here📦Model Zoo We release a series of pre-trained models of different capacities to meet different computing and application needs. All models are easily accessible from Hugging Face Hub. Model Tokenizer Context Length Parameter Open Source Kronos-mini Kronos-Tokenizer-2k 2048 4.1 million ✅ NeoQuasar/Kronos-mini Kronos-small Kronos-Tokenizer-base 512 24.7 million ✅ NeoQuasar/Kronos-mini Kronos-base Kronos-Tokenizer-base 512 102.3 million ✅ NeoQuasar/Kronos Basic Kronos-Big Kronos-Tokenizer-base 512 499.2 million ❌ 🚀 Getting Started Installation Install Python 3.10+, then install dependencies: pip install -r requirements.txt 📈 Making predictions Making predictions with Kronos is very simple with KronosPredictor. It handles data preprocessing, normalization, prediction, and denormalization to get predictions from raw data in just a few lines of code. IMPORTANT: The max_context length for and is 512. This is the maximum sequence length that the model can handle. For best performance, it is recommended that your input data length (ie) does not exceed this limit. For longer contexts, truncation is handled automatically. Kronos-smallKronos-baselookbackKronosPredictor Here is a step-by-step guide to making your first prediction. 1. Load the tagger and model First, load the pre-trained Kronos model and its corresponding tagger from Hugging Face Hub. 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 KronosPredictor instance created by the predictor, passing the model, tokenizer and required equipment. # Initialize the predictor predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512) 3. Prepare input data. The predict method requires three main inputs: df: pandas DataFrame containing historical K-line data. Must contain ['open', 'high', 'low', 'close']. Volume and amount are optional columns. x_timestamp: timestamp series df corresponding to historical data in pandas. y_timestamp: A sequence of pandas timestamps for the future period you want to predict. 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 predictions. Call the predict method to generate predictions. You can control the sampling process using parameters such as T, top_p, and sample_count for probabilistic predictions. # 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()) This method returns a pandas DataFrame containing the predicted values (by index) of , , , , and , that you provide. openhighlowclosevolumeamounty_timestamp 5. Examples and Visualizations For a complete runnable script including data loading, prediction, and plotting, see examples/prediction_example.py. Running this script will generate a chart comparing real data to the model's predictions, similar to the chart shown below: Forecast Example Additionally, we have provided a script for making predictions without volume and amount data, which can be found in examples/prediction_wo_vol_example.py. 🔧 Fine-tuning based on your own data (A-share market example) We provide a complete process to facilitate you to fine-tune Kronos on your own data set. As an example, we will demonstrate how to use Qlib to prepare data for the China A-share market and conduct a simple backtest. Disclaimer: This flow is intended to demonstrate the fine-tuning process. It is a simplified example and is not a production-ready quantitative trading system. Robust quantitative strategies require more sophisticated techniques, such as portfolio optimization and risk factor neutralization, to achieve stable alpha values. The fine-tuning process is divided into four main steps: Configuration: Set paths and hyperparameters. Data preparation: Use Qlib to process and split the data. Model fine-tuning: Fine-tune tokenizer and predictor models. Backtesting: Evaluating the performance of fine-tuned models. Prerequisites First, make sure you have all dependencies installed in the requirements.txt. This pipeline depends on qlib. Please install it: pip install pyqlib You need to prepare Qlib data. Please follow the official Qlib guide to download and set up the data locally. The example script assumes you are using daily frequency data. Step 1: Configure your experimental data, training and model paths. All settings are centralized in finetune/config.py. Before running any scripts, modify the following paths according to your environment: qlib_data_path: The path to the local Qlib data directory. dataset_path: The directory where processed training/validation/test pickle files are saved. save_path: The base directory where model checkpoints are saved. backtest_result_path: directory where backtest results are saved. pretrained_tokenizer_path and pretrained_predictor_path: The path to the pretrained model you want to start (can be a local path or Hugging Face model name). You can also adjust other parameters such as instrument, train_time_range, epochs and batch_size to suit your specific task. If you are not using Comet.ml, set use_comet = False. Step 2: Prepare the data set and 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. After running python finetune/qlib_data_preprocess.py, you will find train_data.pkl, val_data.pkl and .in the directory specified in the configuration. test_data.pkldataset_path Step 3: Run fine-tuning The fine-tuning process consists of two stages: first fine-tuning the marker and then fine-tuning the predictor. Both training scripts are designed for multi-GPU training using torchrun. 3.1 Fine-tuning the tagger This step tunes the tagger to the data distribution of a specific domain. # Replace NUM_GPUS with the number of GPUs you want to use (eg, 2) torchrun --standalone --nproc_per_node=NUM_GPUS finetune/train_tokenizer.py The optimal tokenizer checkpoint will be saved to the path configured in config.py (derived from save_path and tokenizer_save_folder_name). 3.2 Fine-tuning the predictor This step fine-tunes the main Kronos model for the prediction task. # Replace NUM_GPUS with the number of GPUs you want to use (eg, 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 through backtesting Finally, run the backtesting script to evaluate your fine-tuned model. The script loads the model, performs inference on the test set, generates predictive signals (e.g., predicts price changes), and runs a simple Top-K strategy backtest. #Specify the GPU for inference python finetune/qlib_test.py --device cuda:0 This script will output a detailed performance analysis in your console and generate a graph showing the cumulative return curve of your strategy against the baseline, similar to the following graph: Backtesting Example 💡 From Demo to Production: Important Notes Raw Signal vs. Pure Alpha: The signal generated by the model in this demo is the raw prediction. In a real quantitative workflow, these signals are typically fed into portfolio optimization models. The model imposes constraints to neutralize exposure to common risk factors such as market beta, style factors such as size and value, thereby isolating "pure alpha" and improving the robustness of the strategy. Data processing: The above QlibDataset is only an example. For different data sources or formats, you need to adjust your data loading and preprocessing logic. Strategy and Backtest Complexity: The simple Top-K strategy used in this article is a basic starting point. Production-level strategies typically include more complex logic for portfolio construction, dynamic position sizing, and risk management (such as stop-loss/take-profit rules). Additionally, high-fidelity backtesting should accurately simulate transaction costs, slippage, and market impact to more accurately assess actual performance. 📝 AI generated comments: Please note that many of the code comments in the directory finetune/ are generated by the AI ​​assistant (Gemini 2.5 Pro) for explanation purposes. Although they are intended to be helpful, they may contain inaccuracies. We recommend thinking of the code itself as the ultimate source of logic. 📖 Citation If you use Kronos in your research, we would be very grateful if you cite our paper: @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.

Verification code Refresh