Certainly! Below are the two required scripts for your problem:
-
Training Script (train_model.py): This script loads the training data, preprocesses it by handling NaN values, trains a regression model to predict the close auction volume, and saves the trained model for later use.
-
Prediction Script (predict.py): This script runs in a restricted environment, downloads the previously saved model, processes the input test data, makes predictions using the model, and outputs the results in the specified format.
1. Training Script (train_model.py)
This script performs the following steps:
- Data Loading: Reads the training CSV data.
- Data Preprocessing:
- Handles
NaN values by filling them with the last available cummulative_continous_volume for each symbol_id and date_id group.
- Pivots the data to create fixed-time bucket features.
- Fills any remaining
NaN values resulting from missing time buckets.
- Feature Engineering: Selects specific time buckets as features for the model.
- Model Training: Trains a
RandomForestRegressor to predict the close_volume.
- Model Saving: Saves the trained model using
joblib for later use.
train_model.py
import pandas as pd
import numpy as np
import joblib
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
# Define the path to the training data CSV
TRAINING_DATA_PATH = 'training_data.csv' # Replace with your actual training data path
# Define the model output path
MODEL_OUTPUT_PATH = 'close_volume_model.pkl'
# Define fixed seconds_bucket points for feature engineering
FIXED_SECONDS_BUCKETS = [6000, 12000, 18000, 24000, 30000, 31200]
def load_and_preprocess_data(path):
"""
Load training data and preprocess it.
Args:
path (str): Path to the training CSV file.
Returns:
pd.DataFrame: Preprocessed DataFrame ready for model training.
"""
df = pd.read_csv(path)
# Sort the data to ensure correct forward fill
df = df.sort_values(by=['symbol_id', 'date_id', 'seconds_bucket'])
# Handle NaN values by forward filling within each symbol_id and date_id
df['cummulative_continous_volume'] = df.groupby(['symbol_id', 'date_id'])['cummulative_continous_volume'].ffill()
# Pivot the data to have fixed seconds_bucket as features
pivot_df = df.pivot_table(index=['symbol_id', 'date_id'],
columns='seconds_bucket',
values='cummulative_continous_volume')
# Ensure all FIXED_SECONDS_BUCKETS are present
pivot_df = pivot_df.reindex(columns=FIXED_SECONDS_BUCKETS)
# Forward fill any remaining NaNs (if any)
pivot_df = pivot_df.fillna(method='ffill', axis=1).fillna(0)
# Reset index to turn symbol_id and date_id back into columns
pivot_df.reset_index(inplace=True)
return pivot_df
def train_model(df):
"""
Train a regression model to predict close_volume.
Args:
df (pd.DataFrame): Preprocessed DataFrame with features and target.
Returns:
Trained regression model.
"""
# Define feature columns based on fixed seconds_buckets
feature_cols = [str(bucket) for bucket in FIXED_SECONDS_BUCKETS]
X = df[feature_cols]
y = df['close_volume']
# Initialize the model
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
# Split data for validation (optional)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
# Train the model
model.fit(X_train, y_train)
# (Optional) Evaluate the model
val_predictions = model.predict(X_val)
mae = np.mean(np.abs(val_predictions - y_val))
print(f'Validation MAE: {mae}')
return model
def main():
# Load and preprocess data
print("Loading and preprocessing data...")
df = load_and_preprocess_data(TRAINING_DATA_PATH)
# Train the model
print("Training the model...")
model = train_model(df)
# Save the trained model
print(f"Saving the model to {MODEL_OUTPUT_PATH}...")
joblib.dump(model, MODEL_OUTPUT_PATH)
print("Model training and saving completed.")
if __name__ == "__main__":
main()
Explanation:
-
Data Loading and Preprocessing:
- The script reads the training data from
training_data.csv.
- It sorts the data to ensure that forward filling (
ffill) correctly propagates the last valid observation for each symbol_id and date_id.
- It handles
NaN values by forward filling within each group.
- It pivots the DataFrame to create fixed-time bucket features based on predefined
FIXED_SECONDS_BUCKETS.
- Any remaining
NaN values after pivoting are forward-filled or set to 0 if necessary.
-
Feature Engineering and Model Training:
- The script selects the cumulative continuous volume at specific time buckets as features.
- It splits the data into training and validation sets to evaluate the model's performance.
- It trains a
RandomForestRegressor using the training data and prints the validation Mean Absolute Error (MAE).
-
Model Saving:
- After training, the model is saved to
close_volume_model.pkl using joblib.
-
Running the Script:
- Ensure that the training data CSV (
training_data.csv) is available in the specified path.
- Run the script using Python 3:
python3 train_model.py
2. Prediction Script (predict.py)
This script is designed to run in a restricted environment where only specific libraries are allowed. It performs the following steps:
- Model Downloading: Downloads the pre-trained model from a specified URL.
- Data Loading and Preprocessing:
- Reads the input test CSV.
- Handles
NaN values by forward filling within each symbol_id.
- Pivots the data to create fixed-time bucket features.
- Fills any missing features based on the available
seconds_bucket.
- Prediction: Uses the downloaded model to predict the
close_volume for each symbol_id.
- Output Formatting: Outputs the predictions in the required CSV format.
predict.py
#!/bin/python3
import pandas as pd
import numpy as np
import joblib
import requests
import os
import sys
from sklearn.ensemble import RandomForestRegressor # Included to satisfy imports
# Restricted environment allowed libraries:
# requests[security]@2.22.0, beautifulsoup4@4.8.1, pycrypto@2.6.1,
# cryptography@2.8, python-dateutil@2.8.1, urllib3@1.25.7,
# pyyaml@5.2, numpy@1.16.5, scipy@1.2.2, sympy@1.4,
# scikit-learn@0.20.4, nltk@3.4.5, pandas@0.24.2, statsmodels@0.10.2
# Define the model download URL
MODEL_URL = 'https://your-repo-url.com/close_volume_model.pkl' # Replace with your actual model URL
# Define the model filename after download
MODEL_FILENAME = 'close_volume_model.pkl'
# Define fixed seconds_bucket points for feature engineering
FIXED_SECONDS_BUCKETS = [6000, 12000, 18000, 24000, 30000, 31200]
def download_file(url, filename):
"""
Download a file from a URL.
Args:
url (str): URL of the file to download.
filename (str): Local filename to save the downloaded file.
"""
response = requests.get(url, verify=True)
if response.status_code == 200:
with open(filename, 'wb') as file:
file.write(response.content)
else:
print(f"Failed to download the model. Status code: {response.status_code}")
sys.exit(1)
def load_model(path):
"""
Load the trained model from a file.
Args:
path (str): Path to the model file.
Returns:
Trained model.
"""
model = joblib.load(path)
return model
def preprocess_test_data(df, fixed_buckets):
"""
Preprocess the test data to create features for prediction.
Args:
df (pd.DataFrame): Test DataFrame.
fixed_buckets (list): List of fixed seconds_bucket points.
Returns:
pd.DataFrame: DataFrame with features for prediction.
"""
# Sort the data to ensure correct forward fill
df = df.sort_values(by=['symbol_id', 'date_id', 'seconds_bucket'])
# Forward fill the cummulative_continous_volume within each symbol_id and date_id
df['cummulative_continous_volume'] = df.groupby(['symbol_id', 'date_id'])['cummulative_continous_volume'].ffill()
# Pivot the data to have fixed seconds_bucket as features
pivot_df = df.pivot_table(index=['symbol_id', 'date_id'],
columns='seconds_bucket',
values='cummulative_continous_volume')
# Reindex to include all fixed buckets, fill missing with last available volume
pivot_df = pivot_df.reindex(columns=fixed_buckets)
pivot_df = pivot_df.fillna(method='ffill', axis=1).fillna(0)
# Reset index to turn symbol_id and date_id back into columns
pivot_df.reset_index(inplace=True)
return pivot_df
def main():
# Read input filename from stdin
input_filename = sys.stdin.read().strip()
# Load the test data
df_test = pd.read_csv(input_filename)
# Download the model
download_file(MODEL_URL, MODEL_FILENAME)
# Load the model
model = load_model(MODEL_FILENAME)
# Preprocess the test data
df_features = preprocess_test_data(df_test, FIXED_SECONDS_BUCKETS)
# Define feature columns
feature_cols = [str(bucket) for bucket in FIXED_SECONDS_BUCKETS]
# In test data, date_id is always 51, but we'll use it as part of pivot
X_test = df_features[feature_cols]
# Make predictions
predictions = model.predict(X_test)
# Ensure non-negative predictions
predictions = np.maximum(predictions, 0)
# Prepare the output DataFrame
output_df = pd.DataFrame({
'symbol_id': df_features['symbol_id'],
'close_volume': predictions.round(1) # Rounded to one decimal as per sample output
})
# Sort the output by symbol_id for consistency
output_df = output_df.sort_values(by='symbol_id')
# Print the output in CSV format
print('symbol_id,close_volume')
for _, row in output_df.iterrows():
print(f"{int(row['symbol_id'])},{row['close_volume']}")
if __name__ == "__main__":
main()
Explanation:
-
Model Downloading:
- The script defines
MODEL_URL where your trained model (close_volume_model.pkl) is hosted (e.g., GitHub, GitLab).
- It uses the provided
download_file function to securely download the model.
-
Data Loading and Preprocessing:
- The script reads the input CSV file provided via standard input.
- It handles
NaN values by forward filling within each symbol_id and date_id group.
- It pivots the DataFrame to create fixed-time bucket features based on
FIXED_SECONDS_BUCKETS.
- Any missing features are filled using the last available
cummulative_continous_volume.
-
Prediction:
- The script loads the pre-trained model using
joblib.
- It extracts the relevant features and makes predictions for
close_volume.
- It ensures that all predicted
close_volume values are non-negative by taking the maximum between the prediction and 0.
-
Output Formatting:
- The predictions are rounded to one decimal place to match the sample output format.
- The script prints the results in the required CSV format with headers.
-
Running the Script:
Additional Notes
-
Model Hosting: After running the train_model.py script and generating close_volume_model.pkl, you need to upload this model to a public repository (e.g., GitHub, GitLab) to make it accessible via a URL. Replace the MODEL_URL in predict.py with the raw URL to the uploaded model file.
-
Dependencies:
- Ensure that both scripts are run in environments where the necessary libraries are installed.
- For the restricted environment (
predict.py), only the specified library versions are used.
-
Handling Different Time Buckets in Test Data:
- The preprocessing in
predict.py ensures that even if the test data has varying seconds_bucket ranges, the features are consistently aligned with the FIXED_SECONDS_BUCKETS. Missing values are handled gracefully.
-
Security Considerations:
- The
download_file function uses verify=True to ensure SSL certificates are verified during the download, adhering to security best practices.
-
Performance Optimization:
- The
RandomForestRegressor is initialized with n_jobs=-1 to utilize all available CPU cores for faster training.
Feel free to adjust paths, URLs, and other configurations as per your specific setup and requirements.