To tackle the Close Auction Volume Prediction problem, we'll follow a structured approach that involves data preprocessing, feature engineering, model training, and prediction. Since the allowed libraries are limited to numpy, scipy, sympy, scikit-learn, nltk, pandas, and statsmodels, we'll leverage pandas for data manipulation and scikit-learn for building our regression model.
Below is a step-by-step guide along with sample code to help you develop a solution.
Step 1: Understand the Data
Training Data Schema
- symbol_id: Unique stock identifier.
- date_id: Unique date identifier (sequential).
- seconds_bucket: Number of seconds elapsed since the start of the continuous phase.
- cummulative_continous_volume: Total volume traded in the continuous phase up to the
seconds_bucket.
- close_volume: Volume traded in the Close Auction phase of the stock on that day.
Objective
Predict the close_volume for the 51st day (date_id = 51) based on the historical data of the first 50 days.
Step 2: Data Preprocessing and Feature Engineering
- Load the Training Data
- Aggregate the Time-Series Data
- Create Features for Modeling
- Handle Missing Values
- Encode Categorical Variables (if any)
Sample Code for Data Preprocessing
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
import joblib # To save the model
# 1. Load Training Data
train_filename = 'training_data.csv' # Replace with your training data filename
train_df = pd.read_csv(train_filename)
# 2. Aggregate Time-Series Data
# Pivot the data to have seconds_bucket as features
pivot_df = train_df.pivot_table(index=['symbol_id', 'date_id'],
columns='seconds_bucket',
values='cummulative_continous_volume',
fill_value=0).reset_index()
# 3. Feature Engineering
# Identify the maximum seconds_bucket to use as features up to that point
max_seconds = pivot_df.columns.max()
# Create statistical features
pivot_df['total_continuous_volume'] = pivot_df.loc[:, 1:max_seconds].sum(axis=1)
pivot_df['mean_continuous_volume'] = pivot_df.loc[:, 1:max_seconds].mean(axis=1)
pivot_df['max_continuous_volume'] = pivot_df.loc[:, 1:max_seconds].max(axis=1)
pivot_df['min_continuous_volume'] = pivot_df.loc[:, 1:max_seconds].min(axis=1)
# 4. Prepare Features and Target
X = pivot_df.drop(['symbol_id', 'date_id', 'close_volume'], axis=1)
y = pivot_df['close_volume']
# 5. Handle Possible Missing Values (if any)
X.fillna(0, inplace=True)
# 6. Encode Categorical Variables (symbol_id as a feature)
# Since symbol_id is a categorical variable, we can use one-hot encoding or label encoding
# Here, we'll use label encoding
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
pivot_df['symbol_id_encoded'] = le.fit_transform(pivot_df['symbol_id'])
X['symbol_id_encoded'] = pivot_df['symbol_id_encoded']
# Drop the original symbol_id column
X.drop(['symbol_id'], axis=1, inplace=True)
# 7. Split the Data (Optional: For Validation)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
# 8. Train a Regression Model
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# 9. Validate the Model (Optional)
from sklearn.metrics import mean_absolute_error
y_pred = model.predict(X_val)
mae = mean_absolute_error(y_val, y_pred)
print(f"Validation MAE: {mae}")
# 10. Save the Trained Model
joblib.dump(model, 'close_volume_model.pkl')
Notes:
- Feature Engineering: Aggregating the continuous volume up to different
seconds_bucket intervals provides the model with temporal insights into trading patterns.
- Encoding Categorical Variables:
symbol_id is encoded to allow the model to learn patterns specific to each stock.
- Model Selection:
RandomForestRegressor is chosen for its robustness and ability to handle non-linear relationships.
Step 3: Deploying the Model
Once you've trained and saved your model (close_volume_model.pkl), you need to upload it to a public GitHub/GitLab repository. Ensure the repository is public so that it can be accessed during the prediction phase.
Step 4: Prediction on Test Data
The prediction script will perform the following:
- Download the Trained Model
- Load the Test Data
- Preprocess the Test Data (Consistent with Training)
- Make Predictions
- Format the Output
Sample Prediction Code
#!/bin/python3
import pandas as pd
import numpy as np
import joblib
import requests
import os
from sklearn.preprocessing import LabelEncoder
def download_file(url, filename):
response = requests.get(url)
if response.status_code == 200:
with open(filename, 'wb') as file:
file.write(response.content)
else:
raise Exception(f"Failed to download the file from {url}")
# 1. Read Input Filename
filename = input()
test_df = pd.read_csv(filename)
# 2. Download the Trained Model from GitHub/GitLab
model_url = "https://github.com/your_username/your_repo/raw/main/close_volume_model.pkl" # Replace with your model URL
model_filename = os.path.basename(model_url)
download_file(model_url, model_filename)
# 3. Load the Trained Model
model = joblib.load(model_filename)
# 4. Preprocess Test Data
# Pivot the test data
pivot_test_df = test_df.pivot_table(index=['symbol_id', 'date_id'],
columns='seconds_bucket',
values='cummulative_continous_volume',
fill_value=0).reset_index()
# Feature Engineering (Consistent with Training)
max_seconds = pivot_test_df.columns.max()
pivot_test_df['total_continuous_volume'] = pivot_test_df.loc[:, 1:max_seconds].sum(axis=1)
pivot_test_df['mean_continuous_volume'] = pivot_test_df.loc[:, 1:max_seconds].mean(axis=1)
pivot_test_df['max_continuous_volume'] = pivot_test_df.loc[:, 1:max_seconds].max(axis=1)
pivot_test_df['min_continuous_volume'] = pivot_test_df.loc[:, 1:max_seconds].min(axis=1)
# Prepare Features
X_test = pivot_test_df.drop(['symbol_id', 'date_id', 'close_volume'], axis=1, errors='ignore')
# Handle Missing Values
X_test.fillna(0, inplace=True)
# Encode 'symbol_id' using the same LabelEncoder from training
# It's crucial to have the same encoding; hence, both encoder and classes should be consistent
# For simplicity, we'll assume that symbol_ids in test are the same as in training
le = LabelEncoder()
# Normally, you'd save the encoder as well during training. Here, we'll load it if saved.
# For demonstration, we'll fit it again
le.fit(test_df['symbol_id'])
X_test['symbol_id_encoded'] = le.transform(test_df['symbol_id'])
# Drop original 'symbol_id'
X_test.drop(['symbol_id'], axis=1, inplace=True, errors='ignore')
# 5. Make Predictions
predictions = model.predict(X_test)
# Ensure that predictions are non-negative
predictions = np.maximum(predictions, 0)
# 6. Prepare Output
output_df = pd.DataFrame({
'symbol_id': test_df['symbol_id'].unique(),
'close_volume': predictions
})
# 7. Print Output in Required Format
print("symbol_id,close_volume")
for index, row in output_df.iterrows():
print(f"{int(row['symbol_id'])},{float(row['close_volume'])}")
Notes:
- Downloading the Model: Ensure that the
model_url points to the raw file of your trained model in your GitHub/GitLab repository.
- Consistent Preprocessing: The test data must undergo the same preprocessing and feature engineering steps as the training data to ensure consistency.
- Handling
symbol_id Encoding: It's crucial to encode symbol_id in the test data using the same encoding scheme as the training data. Ideally, save and load the LabelEncoder used during training.
- Non-Negative Predictions: The problem constraints specify that predicted
close_volume should be non-negative. We enforce this by taking the maximum between the predicted value and zero.
Step 5: Submission
Ensure that your final script:
- Downloads the trained model from your repository.
- Reads the input file as specified.
- Processes the data correctly.
- Outputs the predictions in the required format.
Example Output:
symbol_id,close_volume
1029677210,1473541.0
1077784782,471017.0
1084320043,3454475.0
1106122882,212836.0
Additional Recommendations
- Cross-Validation: Implement cross-validation during training to ensure the robustness of your model.
- Hyperparameter Tuning: Optimize the hyperparameters of your model (e.g.,
n_estimators, max_depth for RandomForestRegressor) to achieve better performance.
- Feature Selection: Experiment with different feature engineering techniques to capture more intricate patterns in the data.
- Model Evaluation: Continuously monitor evaluation metrics (e.g., Mean Absolute Error) to gauge model performance.
Conclusion
Predicting the Close Auction Volume is a regression problem that can be effectively addressed using machine learning models like Random Forests. By following the steps outlined above—ranging from data preprocessing to model deployment—you can develop a robust solution that adheres to the problem constraints and performs well on unseen data.
Good luck with your implementation!