To develop a model that predicts the Close Auction Volume based on historical trading data, we'll follow these steps:
- Data Preparation
- Feature Engineering
- Model Training
- Prediction
- Output Formatting
Below is a comprehensive Python script using pandas for data manipulation and LightGBM for regression. You can adjust the model and features based on your specific requirements and the nature of the data.
Prerequisites
Ensure you have the following Python libraries installed:
pip install pandas numpy scikit-learn lightgbm
Step-by-Step Implementation
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import sys
import warnings
from sklearn.model_selection import GroupKFold
from sklearn.metrics import mean_squared_error
import lightgbm as lgb
warnings.filterwarnings("ignore")
def main():
# Read the input filename
filename = sys.stdin.read().strip()
df = pd.read_csv(filename)
# Load training data
# Replace 'train.csv' with the actual path to your training data
train_df = pd.read_csv('train.csv')
# Combine train and test data for consistent preprocessing
train_df['is_test'] = 0
df['is_test'] = 1
full_df = pd.concat([train_df, df], ignore_index=True, sort=False)
# Feature Engineering
full_df['hour'] = full_df['seconds_bucket'] // 3600
full_df['minute'] = (full_df['seconds_bucket'] % 3600) // 60
full_df['second'] = full_df['seconds_bucket'] % 60
# Aggregate features up to the current seconds_bucket
agg_features = full_df.groupby(['symbol_id', 'date_id']).agg({
'seconds_bucket': 'max',
'cummulative_continous_volume': ['max', 'sum', 'mean', 'std']
}).reset_index()
# Flatten MultiIndex columns
agg_features.columns = ['symbol_id', 'date_id',
'seconds_bucket_max',
'cummulative_continous_volume_max',
'cummulative_continous_volume_sum',
'cummulative_continous_volume_mean',
'cummulative_continous_volume_std']
# Merge with original data to get close_volume
merged_df = pd.merge(agg_features, full_df[full_df['is_test'] == 0][['symbol_id', 'date_id', 'close_volume']],
on=['symbol_id', 'date_id'], how='left')
# Handle missing values if any
merged_df.fillna(0, inplace=True)
# Features and target
feature_cols = ['seconds_bucket_max',
'cummulative_continous_volume_max',
'cummulative_continous_volume_sum',
'cummulative_continous_volume_mean',
'cummulative_continous_volume_std']
X = merged_df[feature_cols]
y = merged_df['close_volume']
# Define the model
model = lgb.LGBMRegressor(
objective='regression',
num_leaves=31,
learning_rate=0.05,
n_estimators=1000,
random_state=42
)
# Cross-validation setup
folds = GroupKFold(n_splits=5)
split_groups = merged_df['symbol_id']
oof = np.zeros(len(merged_df))
scores = []
for train_idx, valid_idx in folds.split(X, y, groups=split_groups):
X_train, X_valid = X.iloc[train_idx], X.iloc[valid_idx]
y_train, y_valid = y.iloc[train_idx], y.iloc[valid_idx]
model.fit(
X_train, y_train,
eval_set=[(X_valid, y_valid)],
eval_metric='rmse',
early_stopping_rounds=100,
verbose=False
)
oof[valid_idx] = model.predict(X_valid, num_iteration=model.best_iteration_)
score = np.sqrt(mean_squared_error(y_valid, oof[valid_idx]))
scores.append(score)
print(f'CV RMSE: {np.mean(scores)}')
# Train on full training data
model.fit(X, y)
# Prepare test data
test_full_df = full_df[full_df['is_test'] == 1]
test_agg = test_full_df.groupby(['symbol_id', 'date_id']).agg({
'seconds_bucket': 'max',
'cummulative_continous_volume': ['max', 'sum', 'mean', 'std']
}).reset_index()
test_agg.columns = ['symbol_id', 'date_id',
'seconds_bucket_max',
'cummulative_continous_volume_max',
'cummulative_continous_volume_sum',
'cummulative_continous_volume_mean',
'cummulative_continous_volume_std']
# Handle missing values
test_agg.fillna(0, inplace=True)
X_test = test_agg[feature_cols]
# Predict close_volume
test_agg['close_volume'] = model.predict(X_test)
# Ensure non-negative predictions
test_agg['close_volume'] = test_agg['close_volume'].apply(lambda x: max(x, 0))
# Prepare the output
output = test_agg[['symbol_id', 'close_volume']]
output = output.drop_duplicates(subset=['symbol_id'])
# Print the output in the required format
print('symbol_id,close_volume')
for index, row in output.iterrows():
print(f"{int(row['symbol_id'])},{round(row['close_volume'], 1)}")
if __name__ == "__main__":
main()
Explanation of the Code
-
Reading Input and Training Data
- The script reads the input CSV file provided via standard input.
- It assumes there's a
train.csv file available in the same directory containing historical data. Ensure you replace 'train.csv' with the actual path to your training dataset.
-
Data Preprocessing and Feature Engineering
- Time Features: Extracts
hour, minute, and second from seconds_bucket to capture intraday patterns.
- Aggregated Features: For each
symbol_id and date_id, it calculates:
- Maximum
seconds_bucket.
- Maximum, sum, mean, and standard deviation of
cummulative_continous_volume.
-
Model Training
- Uses LightGBM, a gradient boosting framework that is efficient for large datasets.
- Implements Group K-Fold Cross-Validation by
symbol_id to ensure that the model generalizes well across different stocks.
- Evaluates the model using Root Mean Squared Error (RMSE).
-
Prediction on Test Data
- Aggregates the test data in the same way as the training data.
- Predicts the
close_volume using the trained model.
- Ensures that all predictions are non-negative as per the constraints.
-
Output Formatting
- Outputs the results in CSV format with headers
symbol_id,close_volume.
- Rounds the
close_volume to one decimal place for consistency.
Usage
-
Prepare Your Environment
- Ensure
train.csv (your training dataset) is in the same directory as the script or update the path accordingly.
- Place your test CSV files in an accessible location.
-
Run the Script
-
Sample Execution
echo "sample1.csv" | ./predict_close_volume.py
Sample Output:
symbol_id,close_volume
1029677210,1473541.0
1077784782,471017.0
1084320043,3454475.0
1106122882,212836.0
Notes
-
Feature Selection: The current features are basic aggregations. Depending on the data complexity, you might want to include more sophisticated features such as lag features, moving averages, or interaction terms.
-
Model Tuning: Hyperparameters for the LightGBM model are set to default values. Consider performing hyperparameter tuning (e.g., using GridSearchCV) to potentially improve performance.
-
Handling Missing Data: The script fills missing values with zero. Depending on the dataset, other imputation strategies might be more appropriate.
-
Scalability: For very large datasets, consider more efficient data processing techniques or distributed computing frameworks.
Conclusion
This script provides a foundational approach to predicting the close auction volume using historical trading data. Depending on the specific characteristics of your dataset, further optimizations and feature engineering may be necessary to achieve optimal performance.