Close Auction Volume prediction throughout the trading period is essential for various trading stratagies to make critical decisions.
Stock trades on exchange in two phases:
code
Continuous phase – stock trades in the phase from the start of day till Close Auction takes place. Trades continuously happen in this phase as buyers and sellers agrees on a price. Volume of shares traded in this phase is called Order Book volume.
Close Auction phase – stock trades in this phase at the end of the trading. In this phase large volume is traded at a single price through an auction, we call this volume as close auction volume.
image
Objective
You have to devlop a model which can predict close auction volume based on historic data provided.
Note: You should use training data to come up with a model that predict the Close volume based on historic data.
Use the model that you have developed (based on trainig data), and with the input of test data predict the Close volume for respective symbol_ids.
Training Dataset
You can download the training dataset from here
In the dataset you are given cumulative Order Book volume for various time buckets in a day and close auction volume for that day.
Training dataset is essentially timeseries data for various symbol_ids.
Data Schema
symbol_id: Unique stock identifier.
date_id: Unique date identifier. date_id is sequential.
seconds_bucket: Numbers of seconds elapsed since the start of continuous phase.
cummulative_continous_volume: total volume traded in continuous phase since the start of the continuous phase till the seconds_bucket.
close_volume: volume traded in Close Auction of the stock on that date. This will tick at the end of the day at seconds_bucket = 31200
Evaluation Criteria
Each prediction (xi) will be assessed against the realised Close Auction Volume (yi) for that day using
\text{Score} = 1 - \left( \frac{1}{n} \sum_{i=1}^{n} \frac{|x_i - y_i|}{y_i} \right)
n -> number of symbol_ids
Write code in python and train and save the model.
Assistant
To develop a model that predicts the Close Auction Volume (close_volume) based on historical cumulative continuous volumes (cummulative_continuous_volume), we'll follow a structured approach:
Data Understanding and Preprocessing
Feature Engineering
Model Selection and Training
Evaluation
Saving the Model
We'll use Python along with popular libraries like pandas, numpy, and LightGBM for this task. Below is a comprehensive step-by-step guide with code snippets to achieve the objective.
1. Import Necessary Libraries
First, let's import all the necessary libraries.
python
import pandas as pd
import numpy as np
import lightgbm as lgb
import joblib
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import mean_absolute_error
import warnings
warnings.filterwarnings('ignore')
2. Load the Data
Assuming you have the training data in a CSV file (train.csv) and test data in test.csv. Replace these with the actual file paths if they differ.
python
# Load training data
train_df = pd.read_csv('train.csv')
# Load test data
test_df = pd.read_csv('test.csv')
3. Data Preprocessing
a. Understanding the Data Structure
Your training data has the following columns:
symbol_id: Unique stock identifier.
date_id: Unique date identifier.
seconds_bucket: Number of seconds elapsed since the start of the continuous phase.
cummulative_continous_volume: Total volume traded in the continuous phase till the seconds_bucket.
close_volume: Volume traded in Close Auction (target variable).
b. Handling Time-Series Data
For each symbol_id and date_id, we have a time-series of cummulative_continous_volume across different seconds_bucket. To model this, we'll aggregate the time-series data into meaningful features.
c. Feature Engineering
We'll extract statistical features from the cumulative volume time-series which might help the model to learn patterns effectively.
Apply the feature engineering function to both training and test data.
python
# Apply feature engineering on training data
train_features = feature_engineering(train_df)
train_features = train_features.merge(
train_df[['symbol_id', 'date_id', 'close_volume']].drop_duplicates(),
on=['symbol_id', 'date_id'],
how='left'
)
# Apply feature engineering on test data (Assuming test data has the same structure)
test_features = feature_engineering(test_df)
d. Handling Missing Values
It's essential to handle any missing values that might exist after feature engineering.
python
# Check for missing values
print(train_features.isnull().sum())
# Fill missing values if any
train_features.fillna(0, inplace=True)
test_features.fillna(0, inplace=True)
e. Encoding Categorical Variables
If there are any categorical variables, encode them appropriately. In this case, symbol_id can be treated as a categorical feature.
python
# Encode 'symbol_id' using label encoding
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
train_features['symbol_id'] = le.fit_transform(train_features['symbol_id'])
test_features['symbol_id'] = le.transform(test_features['symbol_id'])
4. Preparing Data for Modeling
Separate the target variable from the features.
python
X = train_features.drop(['symbol_id', 'date_id', 'close_volume'], axis=1)
y = train_features['close_volume']
X_test = test_features.drop(['symbol_id', 'date_id', 'close_volume'], axis=1) # Assuming test has 'close_volume'
5. Train-Test Split
Split the data into training and validation sets to evaluate the model's performance.
Create a submission DataFrame with symbol_id, date_id, and the predicted close_volume.
python
submission = test_features[['symbol_id', 'date_id']].copy()
submission['predicted_close_volume'] = test_predictions
# If you wish to inverse transform the 'symbol_id' to original labels
submission['symbol_id'] = le.inverse_transform(submission['symbol_id'])
# Save to CSV
submission.to_csv('close_volume_predictions.csv', index=False)
10. Save the Model
It's crucial to save the trained model for future use or deployment.
Feature Importance: Understanding which features contribute most to the prediction can provide insights.
python
import matplotlib.pyplot as plt
lgb.plot_importance(final_model, max_num_features=10, importance_type='split')
plt.show()
Hyperparameter Tuning: To potentially improve model performance, consider performing hyperparameter tuning using GridSearchCV or RandomizedSearchCV.
Cross-Validation: Implement cross-validation to ensure that your model generalizes well to unseen data.
Handling Time-Series Data More Effectively: Depending on the complexity and patterns in your data, more sophisticated time-series models like Recurrent Neural Networks (RNNs) or Long Short-Term Memory networks (LSTMs) might be beneficial.
Scaling and Normalization: Depending on the model and features, scaling the features might improve performance.
Handling Categorical Variables More Richly: If symbol_id has inherent relationships or hierarchies, more advanced encoding techniques like target encoding can be explored.
This comprehensive approach should help you build an effective model to predict the Close Auction Volume based on historical data. Make sure to experiment with different features and model configurations to achieve the best performance based on your specific dataset.