Certainly! Below are two Python scripts addressing both parts of your problem:
-
Training Script (train_and_save_model.py): This script creates, trains, and saves a machine learning model to predict the Close Auction Volume based on the provided training data.
-
Prediction Script (predict_close_volume.py): This script downloads the saved model, processes the input test data in a restricted environment, and outputs the predicted Close Auction Volumes.
Part 1: Training Script (train_and_save_model.py)
Explanation
-
Data Loading and Preprocessing:
- Handling NaN Values: The script fills NaN values with the median of each column to ensure that the model can handle missing data without biasing the results.
- Feature Engineering: Aggregates the cumulative Order Book Volume for each
symbol_id and date_id by computing statistical features such as sum, mean, max, etc., over the time buckets. This provides the model with meaningful features derived from the time series data.
-
Model Training:
- Utilizes a
RandomForestRegressor from scikit-learn to train on the processed features.
- The model is trained to predict the
close_volume based on the aggregated Order Book Volume features.
-
Model Saving:
- The trained model is serialized and saved as
close_volume_model.pkl using the pickle library.
- Note: After running this script, you should upload the
close_volume_model.pkl to a public repository (e.g., GitHub) to make it accessible for the prediction script.
Code
# train_and_save_model.py
import pandas as pd
import numpy as np
import pickle
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
def preprocess_data(df):
"""
Preprocess the training data:
- Handle NaN values by filling with median.
- Aggregate order_book_volume features per symbol_id and date_id.
"""
# Fill NaN values with median
df_filled = df.fillna(df.median())
# Aggregate features
feature_df = df_filled.groupby(['symbol_id', 'date_id']).agg({
'order_book_volume': ['sum', 'mean', 'max', 'min', 'std'],
'seconds_bucket': 'count'
}).reset_index()
# Flatten MultiIndex columns
feature_df.columns = ['symbol_id', 'date_id',
'order_book_volume_sum',
'order_book_volume_mean',
'order_book_volume_max',
'order_book_volume_min',
'order_book_volume_std',
'seconds_bucket_count']
return feature_df
def load_and_preprocess_training_data(training_file):
"""
Load training data from CSV and preprocess it.
Assumes the CSV has columns: symbol_id, date_id, seconds_bucket, order_book_volume, close_volume
"""
df = pd.read_csv(training_file)
feature_df = preprocess_data(df)
# The close_volume is the target. Assuming it's consistent per symbol_id and date_id
# Extract close_volume by taking the max (since it's same for all rows per group)
close_volume_df = df.groupby(['symbol_id', 'date_id'])['close_volume'].max().reset_index()
# Merge features with target
merged_df = pd.merge(feature_df, close_volume_df, on=['symbol_id', 'date_id'])
return merged_df
def train_model(df):
"""
Train a regression model to predict close_volume.
"""
X = df.drop(['close_volume', 'symbol_id', 'date_id'], axis=1)
y = df['close_volume']
# Split into train and validation to check performance
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
# Initialize and train the model
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
# Validate the model
y_pred = model.predict(X_val)
mae = mean_absolute_error(y_val, y_pred)
print(f'Validation MAE: {mae}')
return model
def save_model(model, filename='close_volume_model.pkl'):
"""
Save the trained model to a file using pickle.
"""
with open(filename, 'wb') as file:
pickle.dump(model, file)
print(f'Model saved to {filename}')
def main():
training_file = 'training_data.csv' # Replace with your actual training data file
print('Loading and preprocessing training data...')
training_df = load_and_preprocess_training_data(training_file)
print('Training the model...')
model = train_model(training_df)
print('Saving the model...')
save_model(model)
if __name__ == "__main__":
main()
Instructions
-
Prepare Training Data: Ensure that you have a CSV file named training_data.csv with the following columns:
symbol_id
date_id
seconds_bucket
order_book_volume
close_volume
-
Run the Script:
python train_and_save_model.py
-
Upload the Model: After running the script, upload the close_volume_model.pkl to a public repository (e.g., GitHub). Ensure the repository and the file are publicly accessible.
Part 2: Prediction Script (predict_close_volume.py)
Explanation
-
Environment Constraints:
- Only specific libraries are allowed. The script uses
requests to download the trained model and pickle to deserialize it.
- Since
pickle is a standard library, it's permissible within the constraints.
-
Model Downloading:
- The script downloads the
close_volume_model.pkl file from a public URL (e.g., GitHub).
- Security Note: Ensure that the URL points directly to the raw file in the repository to avoid any redirection or additional HTML content.
-
Data Processing and Prediction:
- Processes the input test CSV similarly to how the training data was processed (handling NaNs and feature engineering).
- Uses the downloaded model to predict the
close_volume for each symbol_id.
- Ensures that all predicted volumes are non-negative by setting any negative predictions to zero.
-
Output:
- Prints the predictions in the required CSV format with headers
symbol_id and close_volume.
Code
# predict_close_volume.py
#!/bin/python3
import pandas as pd
import numpy as np
import pickle
import requests
import os
import sys
def download_file(url, filename):
"""
Download a file from a URL and save it locally.
"""
response = requests.get(url)
if response.status_code == 200:
with open(filename, 'wb') as file:
file.write(response.content)
else:
print(f'Error downloading file from {url}')
sys.exit(1)
def preprocess_test_data(df):
"""
Preprocess the test data:
- Handle NaN values by filling with median.
- Aggregate order_book_volume features per symbol_id.
"""
# Fill NaN values with median
df_filled = df.fillna(df.median())
# Aggregate features
feature_df = df_filled.groupby(['symbol_id']).agg({
'order_book_volume': ['sum', 'mean', 'max', 'min', 'std'],
'seconds_bucket': 'count'
}).reset_index()
# Flatten MultiIndex columns
feature_df.columns = ['symbol_id',
'order_book_volume_sum',
'order_book_volume_mean',
'order_book_volume_max',
'order_book_volume_min',
'order_book_volume_std',
'seconds_bucket_count']
return feature_df
def main():
# URL of the model file in the public repository
model_url = "https://github.com/YOUR_GITHUB_USERNAME/YOUR_REPO/raw/main/close_volume_model.pkl" # Replace with actual URL
model_filename = "close_volume_model.pkl"
# Download the model file
download_file(model_url, model_filename)
# Load the model
with open(model_filename, 'rb') as file:
model = pickle.load(file)
# Read input filename from stdin
input_filename = input().strip()
df_test = pd.read_csv(input_filename)
# Preprocess test data
feature_test_df = preprocess_test_data(df_test)
# Prepare features for prediction
X_test = feature_test_df.drop(['symbol_id'], axis=1)
# Handle any remaining NaN values after aggregation
X_test = X_test.fillna(0)
# Make predictions
predictions = model.predict(X_test)
# Ensure non-negative predictions
predictions = np.maximum(predictions, 0)
# Prepare output DataFrame
output_df = pd.DataFrame({
'symbol_id': feature_test_df['symbol_id'],
'close_volume': predictions.round(1) # Rounded to one decimal as per sample
})
# Print the output in the required format
print('symbol_id,close_volume')
for index, row in output_df.iterrows():
print(f"{int(row['symbol_id'])},{row['close_volume']}")
# Optional: Remove the downloaded model file to clean up
if os.path.exists(model_filename):
os.remove(model_filename)
if __name__ == "__main__":
main()
Instructions
-
Upload the Model:
-
Prepare Test Data:
- The script expects a CSV file as input. The CSV should have the same structure as the training data but only contains data up to a certain
seconds_bucket for the 51st day.
-
Run the Script:
-
Sample Output:
symbol_id,close_volume
1029677210,1473541.0
1077784782,471017.0
1084320043,3454475.0
1106122882,212836.0
Final Notes
-
Consistency in Feature Engineering: It's crucial to ensure that the feature engineering steps in both the training and prediction scripts are consistent. Any discrepancy can lead to inaccurate predictions.
-
Model Updates: If you retrain the model or make any changes to the feature engineering process, remember to update the saved model in the public repository accordingly.
-
Security Considerations: Only download the model file as instructed. Avoid downloading or executing any other files to maintain the integrity and security of the environment.
-
Dependencies: Ensure that all necessary libraries are installed in the environments where you run these scripts. The prediction script operates under restricted libraries, so no additional installations should be required beyond what's specified.
Feel free to modify and extend these scripts based on the specific details and structure of your training and test datasets.