To solve the Close Auction Volume Prediction problem, we'll develop a machine learning model using Python that predicts the close_volume for each symbol_id based on historical trading data.
Here's a step-by-step guide along with the Python code to accomplish this task:
-
Understand the Data:
- Training Data: Contains historical data for multiple
symbol_ids across different date_ids. Each entry has cumulative continuous volume traded up to a specific seconds_bucket and the corresponding close_volume for that day.
- Test Data: Contains similar data for the first 50 days fully and the 51st day partially. The goal is to predict the
close_volume for the 51st day based on the partial data.
-
Approach:
- Feature Engineering: Extract meaningful features from the time-series data that can help in predicting the
close_volume. Examples include:
- Volume Statistics: Total volume traded so far, average volume per second, maximum volume in any second bucket, etc.
- Temporal Features: Time-based features like the current
seconds_bucket, elapsed time, etc.
- Model Selection: Use a regression model from
scikit-learn (e.g., RandomForestRegressor) to predict the close_volume.
- Training: Train the model on the training dataset by learning the relationship between the engineered features and the
close_volume.
- Prediction: Apply the trained model to the test dataset to predict the
close_volume for each symbol_id.
-
Implementation:
Below is the Python code that implements the above approach. This code assumes that you have access to the training dataset URL and that you will replace the placeholder URL with the actual one.
#!/bin/python3
import pandas as pd
import numpy as np
import os
import sys
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
# Function to download files (training data and model if needed)
import requests
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:
print(f"Failed to download {url}")
sys.exit(1)
# Paths (You need to replace TRAINING_DATA_URL with the actual URL)
TRAINING_DATA_URL = "https://path_to_your_training_data/training_data.csv"
TRAINING_DATA_FILE = "training_data.csv"
MODEL_URL = "https://path_to_your_model/model.pkl"
MODEL_FILE = "model.pkl"
# Download training data if not present
if not os.path.isfile(TRAINING_DATA_FILE):
download_file(TRAINING_DATA_URL, TRAINING_DATA_FILE)
# Load the training data
train_df = pd.read_csv(TRAINING_DATA_FILE)
# Feature Engineering
# Aggregate features for each symbol_id and date_id
def feature_engineering(df):
# Sort the data
df = df.sort_values(['symbol_id', 'date_id', 'seconds_bucket'])
# For each symbol_id and date_id, extract features
# Example features:
# - Total continuous volume up to the last seconds_bucket
# - Last cumulative volume
# - Rate of volume change
# - Number of data points
feature_list = []
grouped = df.groupby(['symbol_id', 'date_id'])
for (symbol, date), group in grouped:
group = group.sort_values('seconds_bucket')
total_continuous_volume = group['cummulative_continous_volume'].iloc[-1]
last_cumulative_volume = group['cummulative_continous_volume'].iloc[-1]
first_cumulative_volume = group['cummulative_continous_volume'].iloc[0]
elapsed_time = group['seconds_bucket'].iloc[-1]
mean_volume = group['cummulative_continous_volume'].mean()
max_volume = group['cummulative_continous_volume'].max()
min_volume = group['cummulative_continous_volume'].min()
std_volume = group['cummulative_continous_volume'].std()
num_buckets = group.shape[0]
feature = {
'symbol_id': symbol,
'date_id': date,
'total_continuous_volume': total_continuous_volume,
'last_cumulative_volume': last_cumulative_volume,
'first_cumulative_volume': first_cumulative_volume,
'elapsed_time': elapsed_time,
'mean_volume': mean_volume,
'max_volume': max_volume,
'min_volume': min_volume,
'std_volume': std_volume if not np.isnan(std_volume) else 0,
'num_buckets': num_buckets
}
feature_list.append(feature)
feature_df = pd.DataFrame(feature_list)
return feature_df
feature_train_df = feature_engineering(train_df)
# Target variable
X = feature_train_df.drop(['symbol_id', 'date_id', 'close_volume'], axis=1, errors='ignore')
y = feature_train_df['close_volume']
# Handle cases where 'close_volume' is not in feature_train_df
if 'close_volume' not in feature_train_df.columns:
y = train_df[['symbol_id', 'date_id', 'close_volume']].drop_duplicates().set_index(['symbol_id', 'date_id']).reset_index()['close_volume']
feature_train_df = feature_train_df.drop(['close_volume'], axis=1, errors='ignore')
# Split into training and validation sets
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)
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}")
# Save the trained model
import joblib
joblib.dump(model, MODEL_FILE)
# Now, define the prediction function
def predict_close_volume(test_df, model):
# Feature Engineering on test data
feature_test_df = feature_engineering(test_df)
# Prepare features
X_test = feature_test_df.drop(['symbol_id', 'date_id', 'close_volume'], axis=1, errors='ignore')
# Predict
preds = model.predict(X_test)
# Ensure non-negative predictions
preds = np.maximum(preds, 0)
# Prepare the output DataFrame
output_df = pd.DataFrame({
'symbol_id': feature_test_df['symbol_id'],
'close_volume': preds
})
return output_df
# Load the trained model
# If you have pre-trained the model and uploaded it, you can download it
# For this example, we'll use the model trained above
# If using pre-trained model, uncomment the following lines:
# if not os.path.isfile(MODEL_FILE):
# download_file(MODEL_URL, MODEL_FILE)
# model = joblib.load(MODEL_FILE)
# Read the test input
import sys
filename = sys.stdin.read().strip()
test_df = pd.read_csv(filename)
# Predict close_volume for the test data
predictions = predict_close_volume(test_df, model)
# Round the predictions to one decimal place as per sample outputs
predictions['close_volume'] = predictions['close_volume'].round(1)
# Print the output in the required format
print("symbol_id,close_volume")
for index, row in predictions.iterrows():
print(f"{int(row['symbol_id'])},{row['close_volume']}")
- Explanation of the Code:
- Instructions to Run the Code:
-
Prerequisites:
-
Execution:
- Notes:
This implementation provides a foundational approach to predicting close_volume using historical trading data. Depending on the actual data characteristics and additional insights, you can further refine the feature engineering and modeling strategies to achieve better performance.