### Installing and Running the Kronos Web UI Source: https://context7.com/shiyu-coder/kronos/llms.txt Instructions to set up and launch the Flask-based web interface for Kronos. This includes installing dependencies via pip and starting the web server. It also provides alternative methods like using shell scripts or directly running the app file. ```bash # Install web UI dependencies pip install -r webui/requirements.txt # Start the web server (available at http://localhost:7070) cd webui python run.py # Alternative methods: ./start.sh python app.py ``` -------------------------------- ### Install Qlib Python Package Source: https://github.com/shiyu-coder/kronos/blob/master/README.md This command installs the Qlib library, which is a prerequisite for data preparation and finetuning the Kronos model on custom datasets. Ensure pip is available and updated. ```shell pip install pyqlib ``` -------------------------------- ### Start Kronos Web UI with Shell Script Source: https://github.com/shiyu-coder/kronos/blob/master/webui/README.md This snippet demonstrates starting the Kronos Web UI using a shell script. It involves changing to the webui directory, making the start.sh script executable, and then running it. This is a convenient option for command-line users. ```bash cd webui chmod +x start.sh ./start.sh ``` -------------------------------- ### Start Kronos Web UI with Python Script Source: https://github.com/shiyu-coder/kronos/blob/master/webui/README.md This snippet shows how to start the Kronos Web UI by navigating to the webui directory and executing the run.py Python script. This method is straightforward for users familiar with Python. ```bash cd webui python run.py ``` -------------------------------- ### Sequential Training Command Examples Source: https://github.com/shiyu-coder/kronos/blob/master/finetune_csv/README.md These bash commands demonstrate how to execute the sequential training script for Kronos models. They cover full training, skipping existing models, and selectively training only the tokenizer or predictor. ```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 ``` -------------------------------- ### Run Prediction Example Script Source: https://github.com/shiyu-coder/kronos/blob/master/README.md This Python script demonstrates data loading, prediction, and plotting for the Kronos model. It generates a comparison plot between ground truth and forecasted data. Ensure you have the necessary dependencies installed. ```python import os # Assuming the script is in the root directory script_path = "examples/prediction_example.py" if os.path.exists(script_path): print(f"Running prediction example: {script_path}") # In a real scenario, you would execute this script: # os.system(f"python {script_path}") else: print(f"Prediction example script not found at: {script_path}") ``` -------------------------------- ### Install Dependencies for Kronos Web UI Source: https://github.com/shiyu-coder/kronos/blob/master/webui/README.md This snippet shows the command to install all necessary Python dependencies for the Kronos Web UI. It assumes a requirements.txt file is present in the project's root or a relevant subdirectory. This is crucial for setting up the environment correctly. ```bash pip install -r requirements.txt ``` -------------------------------- ### Start Flask Application Directly Source: https://github.com/shiyu-coder/kronos/blob/master/webui/README.md This snippet illustrates how to launch the Kronos Web UI by directly running the Flask application file (app.py) from the webui directory. This method is useful for development or when more direct control over the Flask server is needed. ```bash cd webui python app.py ``` -------------------------------- ### Finetune Predictor using Torchrun Source: https://github.com/shiyu-coder/kronos/blob/master/README.md This command starts the finetuning process for the main predictor model of Kronos. It leverages `torchrun` for multi-GPU training. Customize `NUM_GPUS` according to your hardware. Refer to `finetune/config.py` for all relevant settings. ```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 ``` -------------------------------- ### Fine-tuning Kronos with Custom CSV Data Source: https://context7.com/shiyu-coder/kronos/llms.txt Instructions and examples for fine-tuning the Kronos model on custom financial data provided in CSV format. Supports sequential and individual component training, as well as distributed training. ```APIDOC ## Fine-tuning Kronos with Custom CSV Data ### Description This section details how to fine-tune the Kronos model using custom financial data formatted as CSV files. It covers sequential training (tokenizer then predictor), individual component training, and multi-GPU distributed training. ### CSV Data Format Timestamps,Open,High,Low,Close,Volume,Amount Example: `2019/11/26 9:35,182.45,184.95,182.45,184.45,15136000,0` ### Methods #### Method 1: Sequential Training (Tokenizer + Predictor) **Command:** `python finetune_csv/train_sequential.py --config ` **Options:** - `--skip-existing`: Skip training if model artifacts already exist. - `--skip-basemodel`: Only train the tokenizer. - `--skip-tokenizer`: Only train the predictor (requires a fine-tuned tokenizer). **Example Usage:** ```bash python finetune_csv/train_sequential.py --config configs/config_ali09988_candle-5min.yaml python finetune_csv/train_sequential.py --config configs/config.yaml --skip-existing ``` #### Method 2: Individual Component Training **Commands:** - `python finetune_csv/finetune_tokenizer.py --config ` - `python finetune_csv/finetune_base_model.py --config ` #### Multi-GPU Distributed Training **Command:** `DIST_BACKEND=nccl torchrun --standalone --nproc_per_node= finetune_csv/train_sequential.py --config ` **Example:** ```bash DIST_BACKEND=nccl torchrun --standalone --nproc_per_node=8 \ finetune_csv/train_sequential.py --config configs/config.yaml ``` ### Configuration File Example (`config_ali09988_candle-5min.yaml`) ```yaml data: data_path: "/path/to/your/data.csv" lookback_window: 512 predict_window: 48 max_context: 512 training: epochs: 100 batch_size: 32 tokenizer_lr: 2e-4 basemodel_lr: 4e-5 adam_beta1: 0.9 adam_beta2: 0.95 model: pretrained_tokenizer: "NeoQuasar/Kronos-Tokenizer-base" pretrained_basemodel: "NeoQuasar/Kronos-small" output: base_save_path: "./outputs" exp_name: "my_experiment" ``` ``` -------------------------------- ### Run Prediction Example Script (Without Volume and Amount Data) Source: https://github.com/shiyu-coder/kronos/blob/master/README.md This Python script is designed to make predictions without utilizing Volume and Amount data. It's useful for scenarios where such data is unavailable or not relevant. Ensure all dependencies are met before execution. ```python import os # Assuming the script is in the root directory script_path = "examples/prediction_wo_vol_example.py" if os.path.exists(script_path): print(f"Running prediction example without volume/amount: {script_path}") # In a real scenario, you would execute this script: # os.system(f"python {script_path}") else: print(f"Prediction example script not found at: {script_path}") ``` -------------------------------- ### Load Data File List (JavaScript) Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html Fetches a list of available data files from the '/api/data-files' endpoint using an HTTP GET request. It populates a dropdown menu ('data-file-select') with file names and sizes, allowing users to select a file for loading. ```javascript // Load data file list async function loadDataFiles() { try { const response = await axios.get('/api/data-files'); const dataFiles = response.data; const dataFileSelect = document.getElementById('data-file-select'); dataFileSelect.innerHTML = ''; dataFiles.forEach(file => { const option = document.createElement('option'); option.value = file.path; option.textContent = `${file.name} (${file.size})`; dataFileSelect.appendChild(option); }); console.log('✅ Data file list loaded successfully:', dataFiles); } catch (error) { console.error('❌ Failed to load data file list:', error); showStatus('error', 'Failed to load data file list'); } } ``` -------------------------------- ### Start Prediction API Call (JavaScript) Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html Initiates a prediction request to the '/api/predict' endpoint using Axios. It collects parameters from UI elements, formats them, and handles the response, including displaying results or errors. ```javascript async function startPrediction() { if (!currentDataFile) { showStatus('error', 'Please load data file first'); return; } if (!modelLoaded) { showStatus('error', 'Please load model first'); return; } try { showLoading(true); document.getElementById('predict-btn').disabled = true; const lookback = parseInt(document.getElementById('lookback').value); const predLen = parseInt(document.getElementById('pred-len').value); const startHandle = document.getElementById('start-handle'); const startPercentage = parseFloat(startHandle.style.left) / 100; if (!sliderData) { showStatus('error', 'Time window slider not initialized'); return; } const totalTime = sliderData.endDate.getTime() - sliderData.startDate.getTime(); const startTime = sliderData.startDate.getTime() + (totalTime * startPercentage); const startDate = new Date(startTime); const temperature = parseFloat(document.getElementById('temperature').value); const topP = parseFloat(document.getElementById('top-p').value); const sampleCount = parseInt(document.getElementById('sample-count').value); let predictionParams = { file_path: currentDataFile, lookback: lookback, pred_len: predLen, start_date: startDate.toISOString().slice(0, 16), temperature: temperature, top_p: topP, sample_count: sampleCount }; console.log('🚀 Starting prediction, parameters:', predictionParams); const response = await axios.post('/api/predict', predictionParams); if (response.data.success) { displayPredictionResult(response.data); showStatus('success', response.data.message); } else { showStatus('error', response.data.error); } } catch (error) { console.error('❌ Prediction failed:', error); showStatus('error', `Prediction failed: ${error.response?.data?.error || error.message}`); } finally { showLoading(false); document.getElementById('predict-btn').disabled = false; } } ``` -------------------------------- ### Load Available Models (JavaScript) Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html Fetches the list of available prediction models from the '/api/available-models' endpoint using an HTTP GET request. It populates a dropdown menu with model names, parameters, and descriptions. Handles potential errors during the API call. ```javascript // Load available models async function loadAvailableModels() { try { const response = await axios.get('/api/available-models'); if (response.data.model_available) { availableModels = response.data.models; populateModelSelect(); console.log('✅ Available models loaded successfully:', availableModels); } else { console.warn('⚠️ Kronos model library not available'); showStatus('warning', 'Kronos model library not available, will use simulated prediction'); } } catch (error) { console.error('❌ Failed to load available models:', error); showStatus('error', 'Failed to load available models'); } } ``` -------------------------------- ### Get Model Status (JavaScript) Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html Retrieves the current status of the loaded machine learning model from the '/api/model-status' endpoint via an HTTP GET request. It updates the UI with information about whether a model is loaded and on which device. ```javascript // Update model status async function updateModelStatus() { try { const response = await axios.get('/api/model-status'); const status = response.data; if (status.loaded) { showStatus('success', `Model loaded: ${status.current_model.name} on ${status.current_model.device}`); } else if (status.available) { showStatus('info', 'Model available but not loaded'); } else { showStatus('warning', 'Model library not available'); } } catch (error) { console.error('❌ Failed to get model status:', error); } } ``` -------------------------------- ### Kronos Fine-tuning Pipeline with Qlib (A-Share Market) Source: https://context7.com/shiyu-coder/kronos/llms.txt Provides a complete pipeline for fine-tuning Kronos on Chinese A-share market data. It uses Qlib for data preparation and backtesting. The process involves configuring parameters, preprocessing data, training the tokenizer and predictor (potentially using multi-GPU), and running backtest evaluations. ```python # finetune/config.py - Configuration class for fine-tuning class Config: def __init__(self): # Data paths self.qlib_data_path = "~/.qlib/qlib_data/cn_data" self.dataset_path = "./data/processed_datasets" # Time ranges self.train_time_range = ["2011-01-01", "2022-12-31"] self.val_time_range = ["2022-09-01", "2024-06-30"] self.test_time_range = ["2024-04-01", "2025-06-05"] # Model parameters self.lookback_window = 90 self.predict_window = 10 self.max_context = 512 # Training parameters self.epochs = 30 self.batch_size = 50 self.tokenizer_learning_rate = 2e-4 self.predictor_learning_rate = 4e-5 # Pretrained model paths (Hugging Face IDs or local paths) self.pretrained_tokenizer_path = "NeoQuasar/Kronos-Tokenizer-base" self.pretrained_predictor_path = "NeoQuasar/Kronos-small" # Save paths self.save_path = "./outputs/models" self.tokenizer_save_folder_name = 'finetune_tokenizer_demo' self.predictor_save_folder_name = 'finetune_predictor_demo' ``` ```bash # Step 1: Prepare dataset from Qlib python finetune/qlib_data_preprocess.py # Step 2: Fine-tune tokenizer (multi-GPU with torchrun) torchrun --standalone --nproc_per_node=2 finetune/train_tokenizer.py # Step 3: Fine-tune predictor torchrun --standalone --nproc_per_node=2 finetune/train_predictor.py # Step 4: Run backtest evaluation python finetune/qlib_test.py --device cuda:0 ``` -------------------------------- ### Training Kronos Models from CSV Data using Command Line Source: https://context7.com/shiyu-coder/kronos/llms.txt Command-line interface scripts for training Kronos models with CSV data. Supports sequential training of tokenizer and predictor, individual component training, and distributed multi-GPU training. Includes options to skip existing models or specific components. ```bash # Required CSV format: # timestamps,open,high,low,close,volume,amount # 2019/11/26 9:35,182.45,184.95,182.45,184.45,15136000,0 # Method 1: Sequential training (tokenizer + predictor) python finetune_csv/train_sequential.py --config configs/config_ali09988_candle-5min.yaml # Skip existing models python finetune_csv/train_sequential.py --config configs/config.yaml --skip-existing # Only train tokenizer python finetune_csv/train_sequential.py --config configs/config.yaml --skip-basemodel # Only train predictor (requires fine-tuned tokenizer) python finetune_csv/train_sequential.py --config configs/config.yaml --skip-tokenizer # Method 2: Individual component training python finetune_csv/finetune_tokenizer.py --config configs/config.yaml python finetune_csv/finetune_base_model.py --config configs/config.yaml # Multi-GPU distributed training DIST_BACKEND=nccl torchrun --standalone --nproc_per_node=8 \ finetune_csv/train_sequential.py --config configs/config.yaml ``` -------------------------------- ### Finetune Tokenizer using Torchrun Source: https://github.com/shiyu-coder/kronos/blob/master/README.md This command initiates the finetuning process for the tokenizer component of the Kronos model. It utilizes `torchrun` for distributed training across multiple GPUs. Replace `NUM_GPUS` with the desired number of GPUs. Ensure `finetune/config.py` is properly configured. ```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 ``` -------------------------------- ### Run Qlib Data Preprocessing Script Source: https://github.com/shiyu-coder/kronos/blob/master/README.md This shell command executes the Python script responsible for preparing your market data using Qlib. It loads raw data, processes it, splits it into train/validation/test sets, and saves them as pickle files. Ensure `qlib_data_path` is correctly configured in `finetune/config.py`. ```shell python finetune/qlib_data_preprocess.py ``` -------------------------------- ### Run Backtesting Script Source: https://github.com/shiyu-coder/kronos/blob/master/README.md This command executes the backtesting script to evaluate the performance of the finetuned Kronos model. It loads the trained models, performs inference on the test data, generates prediction signals, and runs a backtest simulation. Ensure all paths and configurations in `finetune/config.py` are correctly set. ```shell # The command to run the backtesting script is typically: # python finetune/backtest.py # Placeholder for the actual command if it differs or requires specific arguments: print("Running the backtesting script to evaluate the finetuned model.") ``` -------------------------------- ### Kronos Web UI REST API Endpoints Source: https://context7.com/shiyu-coder/kronos/llms.txt Defines the REST API endpoints for the Kronos web UI, covering model and data management, prediction execution, and status checks. Each endpoint specifies the HTTP method, path, expected request payload, and example response structure. ```json # Web UI REST API endpoints # GET /api/available-models - List available models # Response: {"models": {...}, "model_available": true} # POST /api/load-model - Load a Kronos model # Request: {"model_key": "kronos-small", "device": "cuda:0"} # Response: {"success": true, "model_info": {...}} # GET /api/data-files - List available data files # Response: [{"name": "data.csv", "path": "/path/to/data.csv", "size": "1.2 MB"}] # POST /api/load-data - Load and validate data file # Request: {"file_path": "/path/to/data.csv"} # Response: {"success": true, "data_info": {"rows": 1000, "columns": [...]}} # POST /api/predict - Run prediction # Request: { # "file_path": "/path/to/data.csv", # "lookback": 400, # "pred_len": 120, # "temperature": 1.0, # "top_p": 0.9, # "sample_count": 1, # "start_date": "2024-01-01T00:00:00" # optional # } # Response: { # "success": true, # "chart": "", # "prediction_results": [...], # "actual_data": [...], # "has_comparison": true # } # GET /api/model-status - Check model loading status # Response: {"available": true, "loaded": true, "current_model": {...}} ``` -------------------------------- ### Individual Component Training Commands Source: https://github.com/shiyu-coder/kronos/blob/master/finetune_csv/README.md This section provides bash commands for training the tokenizer and predictor components of the Kronos model separately. This allows for more granular control over the fine-tuning process. ```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 ``` -------------------------------- ### Fine-tuning Kronos with Custom CSV Data Configuration Source: https://context7.com/shiyu-coder/kronos/llms.txt Configuration file for fine-tuning Kronos on custom CSV financial data. Specifies data paths, training parameters, model details, and output settings for experiments. ```yaml # finetune_csv/configs/config_ali09988_candle-5min.yaml data: data_path: "/path/to/your/data.csv" lookback_window: 512 predict_window: 48 max_context: 512 training: epochs: 100 batch_size: 32 tokenizer_lr: 2e-4 basemodel_lr: 4e-5 adam_beta1: 0.9 adam_beta2: 0.95 model: pretrained_tokenizer: "NeoQuasar/Kronos-Tokenizer-base" pretrained_basemodel: "NeoQuasar/Kronos-small" output: base_save_path: "./outputs" exp_name: "my_experiment" ``` -------------------------------- ### Set Up Event Listeners (JavaScript) Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html Initializes event listeners for various UI elements including buttons for loading models, loading data, and initiating predictions. It also sets up listeners for sliders related to prediction quality parameters ('temperature', 'top-p') and updates related display elements. ```javascript function setupEventListeners() { // Load model button document.getElementById('load-model-btn').addEventListener('click', loadModel); // Load data button document.getElementById('load-data-btn').addEventListener('click', loadData); // Prediction button document.getElementById('predict-btn').addEventListener('click', startPrediction); // Prediction quality parameter sliders document.getElementById('temperature').addEventListener('input', function() { document.getElementById('temperature-value').textContent = this.value; }); document.getElementById('top-p').addEventListener('input', function() { document.getElementById('top-p-value').textContent = this.value; }); // Update slider when lookback window size changes document.getElementById('lookback').addEventListener('input', updateSliderFromInputs); document.getElementById('pred-len').addEventListener('input', updateSliderFromInputs); } ``` -------------------------------- ### Distributed Data Parallel (DDP) Training Command Source: https://github.com/shiyu-coder/kronos/blob/master/finetune_csv/README.md This bash command illustrates how to initiate distributed data parallel training for the Kronos model using `torchrun`. It specifies the communication backend and the number of processes per node for multi-GPU acceleration. ```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 ``` -------------------------------- ### Load Kronos Model and Tokenizer (Python) Source: https://github.com/shiyu-coder/kronos/blob/master/README.md Loads a pre-trained Kronos model and its tokenizer from the Hugging Face Hub. This is the first step before initializing the predictor. It requires the `model` and `KronosTokenizer` classes. ```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") ``` -------------------------------- ### Instantiate Kronos Predictor (Python) Source: https://github.com/shiyu-coder/kronos/blob/master/README.md Creates an instance of the KronosPredictor class. This object will be used for making forecasts. It requires the loaded model, tokenizer, and optionally a device and `max_context` setting. ```python # Initialize the predictor predictor = KronosPredictor(model, tokenizer, max_context=512) ``` -------------------------------- ### Initialize Kronos Application (JavaScript) Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html Initializes the Kronos web UI by loading available models, data files, setting up event listeners, and initializing the time slider. This function is called when the DOM is fully loaded. ```javascript // Global variables let currentDataFile = null; let currentDataInfo = null; let availableModels = []; let modelLoaded = false; // Initialize after page loads document.addEventListener('DOMContentLoaded', function() { initializeApp(); }); // Initialize application async function initializeApp() { console.log('🚀 Initializing Kronos Web UI...'); // Load available models await loadAvailableModels(); // Load data file list await loadDataFiles(); // Set up event listeners setupEventListeners(); // Initialize time slider initializeTimeSlider(); console.log('✅ Application initialization completed'); } ``` -------------------------------- ### Parallel Batch Prediction with KronosPredictor Source: https://context7.com/shiyu-coder/kronos/llms.txt Demonstrates how to perform parallel batch prediction on multiple time series simultaneously using KronosPredictor. It leverages GPU parallelism for efficient processing. This requires the `pandas`, `Kronos`, `KronosTokenizer`, and `KronosPredictor` libraries. ```python import pandas as pd from model import Kronos, KronosTokenizer, KronosPredictor # Load model and create predictor tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base") model = Kronos.from_pretrained("NeoQuasar/Kronos-base") predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512) # Load sample data df = pd.read_csv("./examples/data/XSHG_5min_600977.csv") df['timestamps'] = pd.to_datetime(df['timestamps']) lookback = 400 pred_len = 120 # Prepare multiple time series for batch prediction dfs = [] x_timestamps = [] y_timestamps = [] for i in range(5): # Process 5 different time windows start_idx = i * 400 idf = df.loc[start_idx:start_idx+lookback-1, ['open', 'high', 'low', 'close', 'volume', 'amount']] i_x_timestamp = df.loc[start_idx:start_idx+lookback-1, 'timestamps'] i_y_timestamp = df.loc[start_idx+lookback:start_idx+lookback+pred_len-1, 'timestamps'] dfs.append(idf) x_timestamps.append(i_x_timestamp) y_timestamps.append(i_y_timestamp) # Batch prediction - all series must have same lookback and pred_len pred_dfs = predictor.predict_batch( df_list=dfs, x_timestamp_list=x_timestamps, y_timestamp_list=y_timestamps, pred_len=pred_len, T=1.0, top_p=0.9, sample_count=1, verbose=True ) # Results returned in same order as input for i, pred_df in enumerate(pred_dfs): print(f"Series {i} prediction shape: {pred_df.shape}") print(pred_df.head()) ``` -------------------------------- ### Prepare Input Data for Kronos (Python) Source: https://github.com/shiyu-coder/kronos/blob/master/README.md Prepares historical and future data for the Kronos predictor. Requires a pandas DataFrame with specific columns and pandas Series for timestamps. The `lookback` and `pred_len` parameters define the context window and prediction length. ```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'] ``` -------------------------------- ### Basic Page and Container Styling (CSS) Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html This snippet defines the fundamental styling for the entire web page, including background gradients, font families, and the main content container. It ensures a consistent and visually appealing layout across different screen sizes. ```css body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; color: #333; } .container { max-width: 1400px; margin: 0 auto; padding: 20px; } ``` -------------------------------- ### Load Kronos Tokenizer from Hugging Face Hub (Python) Source: https://context7.com/shiyu-coder/kronos/llms.txt Loads a pre-trained tokenizer for converting continuous OHLCV candlestick data into discrete hierarchical tokens using Binary Spherical Quantization. It supports encoding raw financial data and decoding tokens back to continuous values. ```python from model import KronosTokenizer # Load tokenizer from Hugging Face Hub tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base") # Available tokenizers: # - NeoQuasar/Kronos-Tokenizer-base (for Kronos-small and Kronos-base, context: 512) # - NeoQuasar/Kronos-Tokenizer-2k (for Kronos-mini, context: 2048) # Tokenizer can encode raw financial data into discrete tokens import torch import numpy as np # Example: normalize and encode sample data sample_data = torch.randn(1, 100, 6) # (batch, seq_len, features: OHLCV+amount) token_indices = tokenizer.encode(sample_data, half=True) # Returns tuple of (s1_indices, s2_indices) for hierarchical tokens # Decode tokens back to continuous values reconstructed = tokenizer.decode(token_indices, half=True) # Output shape: (batch, seq_len, 6) ``` -------------------------------- ### Initialize and Manage Time Window Slider in JavaScript Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html The `initializeTimeSlider` and `setupSliderEventListeners` functions set up an interactive time window slider. This slider allows users to select a time range by dragging handles. It includes functionality to handle mouse events for dragging, clicking the slider track, and updating the visual selection. The slider is designed to maintain a fixed window size relative to the total data range. ```javascript let sliderData = null; let isDragging = false; let currentHandle = null; function initializeTimeSlider() { setupSliderEventListeners(); } function setupSliderEventListeners() { const startHandle = document.getElementById('start-handle'); const endHandle = document.getElementById('end-handle'); const track = document.querySelector('.slider-track'); startHandle.addEventListener('mousedown', (e) => { isDragging = true; currentHandle = 'start'; e.preventDefault(); }); endHandle.addEventListener('mousedown', (e) => { isDragging = true; currentHandle = 'end'; e.preventDefault(); }); document.addEventListener('mousemove', (e) => { if (!isDragging) return; const rect = track.getBoundingClientRect(); const x = e.clientX - rect.left; const percentage = Math.max(0, Math.min(1, x / rect.width)); if (currentHandle === 'start') { updateStartHandle(percentage); } else if (currentHandle === 'end') { updateEndHandle(percentage); } updateSliderFromHandles(); }); document.addEventListener('mouseup', () => { isDragging = false; currentHandle = null; }); track.addEventListener('click', (e) => { const rect = track.getBoundingClientRect(); const x = e.clientX - rect.left; const percentage = Math.max(0, Math.min(1, x / rect.width)); const startHandle = document.getElementById('start-handle'); const endHandle = document.getElementById('end-handle'); const startRect = startHandle.getBoundingClientRect(); const endRect = endHandle.getBoundingClientRect(); if (Math.abs(x - (startRect.left - rect.left)) < Math.abs(x - (endRect.left - rect.left))) { updateStartHandle(percentage); } else { updateEndHandle(percentage); } updateSliderFromHandles(); }); } ``` ```javascript function updateStartHandle(percentage) { const startHandle = document.getElementById('start-handle'); const selection = document.getElementById('slider-selection'); const windowSize = 520; const totalRows = sliderData ? sliderData.totalRows : 1000; const windowPercentage = windowSize / totalRows; if (percentage + windowPercentage > 1) { percentage = 1 - windowPercentage; } startHandle.style.left = (percentage * 100) + '%'; selection.style.left = (percentage * 100) + '%'; selection.style.width = (windowPercentage * 100) + '%'; const endHandle = document.getElementById('end-handle'); endHandle.style.left = ((percentage + windowPercentage) * 100) + '%'; } function updateEndHandle(percentage) { const endHandle = document.getElementById('end-handle'); const selection = document.getElementById('slider-selection'); const windowSize = 520; const totalRows = sliderData ? sliderData.totalRows : 1000; const windowPercentage = windowSize / totalRows; if (percentage - windowPercentage < 0) { percentage = windowPercentage; } endHandle.style.left = (percentage * 100) + '%'; selection.style.left = ((percentage - windowPercentage) * 100) + '%'; selection.style.width = (windowPercentage * 100) + '%'; const startHandle = document.getElementById('start-handle'); startHandle.style.left = ((percentage - windowPercentage) * 100) + '%'; } function updateSliderFromHandles() { const startHandle = document.getElementById('start-handle'); const endHandle = document.getElementById('end-handle'); const startPercentage = parseFloat(startHandle.style.left) / 100; const endPercentage = parseFloat(endHandle.style.left) / 100; if (!sliderData) return; const totalTime = sliderData.endDate.getTime() - sliderData.startDate.getTime(); const startTime = } ``` -------------------------------- ### YAML Configuration for Data Parameters Source: https://github.com/shiyu-coder/kronos/blob/master/finetune_csv/README.md This snippet shows the essential data configuration parameters within a YAML file. It specifies the data path, historical lookback window, prediction window, and maximum context length for the Kronos model. ```yaml data: data_path: "/path/to/your/data.csv" lookback_window: 512 predict_window: 48 max_context: 512 ``` -------------------------------- ### Header and Main Content Layout (CSS) Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html Styles for the page header, including typography and text shadow for emphasis, and the main content layout using CSS Grid. This section dictates how the control panel and chart areas are arranged. ```css .header { text-align: center; margin-bottom: 30px; color: white; } .header h1 { font-size: 2.5rem; margin-bottom: 10px; text-shadow: 2px 2px 4px rgba(0,0,0,0.3); } .main-content { display: grid; grid-template-columns: 1fr 2fr; gap: 30px; margin-bottom: 30px; } ``` -------------------------------- ### Kronos Prediction Without Volume Data Source: https://context7.com/shiyu-coder/kronos/llms.txt Shows how to make predictions using Kronos with only OHLC price data when volume and amount data are unavailable. The model automatically fills missing volume/amount data with zeros during prediction. This requires `pandas`, `Kronos`, `KronosTokenizer`, and `KronosPredictor`. ```python import pandas as pd from model import Kronos, KronosTokenizer, KronosPredictor # Load model tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base") model = Kronos.from_pretrained("NeoQuasar/Kronos-small") predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512) # Prepare data with only OHLC columns (no volume/amount) df = pd.read_csv("./examples/data/XSHG_5min_600977.csv") df['timestamps'] = pd.to_datetime(df['timestamps']) lookback = 400 pred_len = 120 # Only include price columns - volume/amount will be auto-filled with zeros x_df = df.loc[:lookback-1, ['open', 'high', 'low', 'close']] x_timestamp = df.loc[:lookback-1, 'timestamps'] y_timestamp = df.loc[lookback:lookback+pred_len-1, 'timestamps'] # Prediction works the same way pred_df = predictor.predict( df=x_df, x_timestamp=x_timestamp, y_timestamp=y_timestamp, pred_len=pred_len, T=1.0, top_p=0.9, sample_count=1, verbose=True ) # Output still includes volume/amount columns (filled with zeros during prediction) print(pred_df[['open', 'high', 'low', 'close']].head()) ``` -------------------------------- ### KronosTokenizer - Load Pre-trained Tokenizer Source: https://context7.com/shiyu-coder/kronos/llms.txt Loads a pre-trained tokenizer from Hugging Face Hub for converting financial K-line data into hierarchical discrete tokens. ```APIDOC ## KronosTokenizer.from_pretrained ### Description Loads a pre-trained tokenizer from Hugging Face Hub that converts continuous OHLCV candlestick data into discrete hierarchical tokens using Binary Spherical Quantization. ### Method `KronosTokenizer.from_pretrained(model_name: str) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from model import KronosTokenizer # Load tokenizer from Hugging Face Hub tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base") # Available tokenizers: # - NeoQuasar/Kronos-Tokenizer-base (for Kronos-small and Kronos-base, context: 512) # - NeoQuasar/Kronos-Tokenizer-2k (for Kronos-mini, context: 2048) # Tokenizer can encode raw financial data into discrete tokens import torch import numpy as np # Example: normalize and encode sample data sample_data = torch.randn(1, 100, 6) # (batch, seq_len, features: OHLCV+amount) token_indices = tokenizer.encode(sample_data, half=True) # Returns tuple of (s1_indices, s2_indices) for hierarchical tokens # Decode tokens back to continuous values reconstructed = tokenizer.decode(token_indices, half=True) # Output shape: (batch, seq_len, 6) ``` ### Response #### Success Response (200) Returns a KronosTokenizer object configured with the specified pre-trained tokenizer. #### Response Example ```json { "message": "Tokenizer loaded successfully" } ``` ``` -------------------------------- ### Load Kronos Model from Hugging Face Hub (Python) Source: https://context7.com/shiyu-coder/kronos/llms.txt Loads a pre-trained Kronos model, a decoder-only Transformer, from Hugging Face Hub. The model performs autoregressive generation on tokenized financial sequences and can be moved to a GPU for faster processing. It takes hierarchical token IDs and outputs logits for next-token prediction. ```python from model import Kronos # Load model from Hugging Face Hub model = Kronos.from_pretrained("NeoQuasar/Kronos-small") # Available models: # - NeoQuasar/Kronos-mini (4.1M params, context: 2048) # - NeoQuasar/Kronos-small (24.7M params, context: 512) # - NeoQuasar/Kronos-base (102.3M params, context: 512) # Move to GPU if available import torch device = "cuda:0" if torch.cuda.is_available() else "cpu" model = model.to(device) # The model takes hierarchical token IDs (s1, s2) and outputs logits # s1_ids: pre-token IDs, s2_ids: post-token IDs # Returns (s1_logits, s2_logits) for next-token prediction ``` -------------------------------- ### Fill Comparison Table (JavaScript) Source: https://github.com/shiyu-coder/kronos/blob/master/webui/templates/index.html Populates an HTML table with prediction and actual data for comparison. It iterates through the minimum length of prediction and actual data arrays, creating table rows with timestamp, open, high, low, and close prices for both predicted and actual values. ```javascript function fillComparisonTable(predictions, actuals) { const tbody = document.getElementById('comparison-tbody'); tbody.innerHTML = ''; const minLen = Math.min(predictions.length, actuals.length); for (let i = 0; i < minLen; i++) { const pred = predictions[i]; const act = actuals[i]; const row = document.createElement('tr'); row.innerHTML = ` ${new Date(pred.timestamp).toLocaleString()} ${act.open.toFixed(4)} ${pred.open.toFixed(4)} ${act.high.toFixed(4)} ${pred.high.toFixed(4)} ${act.low.toFixed(4)} ${pred.low.toFixed(4)} ${act.close.toFixed(4)} ${pred.close.toFixed(4)} `; tbody.appendChild(row); } } ``` -------------------------------- ### Generate Batch Forecasts with Kronos (Python) Source: https://github.com/shiyu-coder/kronos/blob/master/README.md Generates forecasts for multiple time series simultaneously using `predict_batch`. Requires lists of DataFrames and timestamps, ensuring consistent historical and prediction lengths across all series. This method leverages GPU parallelism for efficiency. ```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()) ``` -------------------------------- ### KronosPredictor for Financial Forecasting (Python) Source: https://context7.com/shiyu-coder/kronos/llms.txt Provides a high-level interface for generating financial forecasts using Kronos. It handles data preprocessing, normalization, tokenization, autoregressive inference, and inverse normalization. This is the recommended method for generating forecasts, supporting custom sampling controls. ```python import pandas as pd from model import Kronos, KronosTokenizer, KronosPredictor # 1. Load tokenizer and model tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base") model = Kronos.from_pretrained("NeoQuasar/Kronos-small") # 2. Create predictor (auto-detects device: cuda > mps > cpu) predictor = KronosPredictor( model=model, tokenizer=tokenizer, device=None, # Auto-detect, or specify "cuda:0", "mps", "cpu" max_context=512, # Maximum sequence length (512 for small/base, 2048 for mini) clip=5 # Clip normalized values to [-5, 5] ) # 3. Prepare input data df = pd.read_csv("./examples/data/XSHG_5min_600977.csv") df['timestamps'] = pd.to_datetime(df['timestamps']) lookback = 400 # Historical data points pred_len = 120 # Future points to predict # Input DataFrame must have columns: open, high, low, close # Optional columns: volume, amount (filled with 0 if missing) 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 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 (higher = more random) top_p=0.9, # Nucleus sampling probability sample_count=1, # Number of samples to average verbose=True # Show progress bar ) print(pred_df.head()) # Output DataFrame with columns: open, high, low, close, volume, amount # Indexed by y_timestamp ```