# Improved Model Training and Saving
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.preprocessing import StandardScaler, PolynomialFeatures, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
import joblib
# Load training data
df = pd.read_csv('training_data.csv')
# --------------------
# 1. Data Exploration
# --------------------
print("First five rows of the dataset:")
print(df.head())
print("\nDataset summary:")
print(df.describe())
print("\nMissing values in each column:")
print(df.isnull().sum())
# Visualizing the distribution of the target variable
plt.figure(figsize=(8, 6))
sns.histplot(df['close_volume'], kde=True, bins=30)
plt.title('Distribution of Close Volume')
plt.xlabel('Close Volume')
plt.ylabel('Frequency')
plt.show()
# Correlation matrix
plt.figure(figsize=(10, 8))
sns.heatmap(df.corr(), annot=True, cmap='coolwarm')
plt.title('Correlation Matrix')
plt.show()
# --------------------
# 2. Data Cleaning
# --------------------
# Handling missing values
# For numerical features, fill missing values with the mean
numerical_features = ['cummulative_continous_volume', 'close_volume']
for col in numerical_features:
if df[col].isnull().sum() > 0:
df[col].fillna(df[col].mean(), inplace=True)
# If there are categorical features, handle them appropriately
categorical_features = ['seconds_bucket']
for col in categorical_features:
if df[col].isnull().sum() > 0:
df[col].fillna(df[col].mode()[0], inplace=True)
# ----------------------------
# 3. Feature Engineering
# ----------------------------
# Assuming 'seconds_bucket' is a categorical feature representing time intervals
# Convert 'seconds_bucket' to categorical if it's not already
df['seconds_bucket'] = df['seconds_bucket'].astype('category')
# Optionally, create polynomial features to capture nonlinear relationships
# Here, creating interaction terms between 'cummulative_continous_volume' and 'seconds_bucket'
# Alternatively, you can use sklearn's PolynomialFeatures within a pipeline
# --------------------
# 4. Define Features and Target
# --------------------
features = ['cummulative_continous_volume', 'seconds_bucket']
target = 'close_volume'
X = df[features]
y = df[target]
# --------------------
# 5. Preprocessing Pipeline
# --------------------
# Numerical and categorical features
numeric_features = ['cummulative_continous_volume']
categorical_features = ['seconds_bucket']
# Preprocessing for numerical data: Scaling
numeric_transformer = Pipeline(steps=[
('scaler', StandardScaler())
])
# Preprocessing for categorical data: One-Hot Encoding
categorical_transformer = Pipeline(steps=[
('onehot', OneHotEncoder(drop='first'))
])
# Combine preprocessing steps
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
])
# --------------------
# 6. Train-Test Split
# --------------------
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
# --------------------
# 7. Model Selection and Evaluation
# --------------------
# Define models to evaluate
models = {
'LinearRegression': LinearRegression(),
'RandomForestRegressor': RandomForestRegressor(random_state=42),
'GradientBoostingRegressor': GradientBoostingRegressor(random_state=42)
}
# Iterate through models and evaluate using cross-validation
for name, model in models.items():
# Create a pipeline for each model
clf = Pipeline(steps=[
('preprocessor', preprocessor),
('regressor', model)
])
# Perform cross-validation
cv_scores = cross_val_score(clf, X_train, y_train, cv=5, scoring='neg_mean_squared_error')
rmse = np.sqrt(-cv_scores.mean())
print(f"{name} CV RMSE: {rmse:.4f}")
# Suppose RandomForestRegressor performed the best
best_model_name = 'RandomForestRegressor'
best_model = models[best_model_name]
# --------------------
# 8. Hyperparameter Tuning
# --------------------
# Define the pipeline with the best model
pipeline = Pipeline(steps=[
('preprocessor', preprocessor),
('regressor', best_model)
])
# Define hyperparameter grid for RandomForestRegressor
param_grid = {
'regressor__n_estimators': [100, 200, 300],
'regressor__max_depth': [None, 10, 20, 30],
'regressor__min_samples_split': [2, 5, 10],
'regressor__min_samples_leaf': [1, 2, 4],
'regressor__bootstrap': [True, False]
}
# Initialize GridSearchCV
grid_search = GridSearchCV(
estimator=pipeline,
param_grid=param_grid,
cv=5,
scoring='neg_mean_squared_error',
n_jobs=-1,
verbose=2
)
# Fit GridSearchCV
grid_search.fit(X_train, y_train)
print(f"Best parameters: {grid_search.best_params_}")
print(f"Best CV RMSE: {np.sqrt(-grid_search.best_score_):.4f}")
# --------------------
# 9. Evaluate on Test Set
# --------------------
# Predict on test data using the best estimator
y_pred = grid_search.predict(X_test)
# Calculate performance metrics
rmse_test = np.sqrt(mean_squared_error(y_test, y_pred))
mae_test = mean_absolute_error(y_test, y_pred)
r2_test = r2_score(y_test, y_pred)
print(f"Test RMSE: {rmse_test:.4f}")
print(f"Test MAE: {mae_test:.4f}")
print(f"Test R²: {r2_test:.4f}")
# Plot Actual vs Predicted
plt.figure(figsize=(8,6))
sns.scatterplot(x=y_test, y=y_pred)
plt.xlabel("Actual Close Volume")
plt.ylabel("Predicted Close Volume")
plt.title("Actual vs Predicted Close Volume")
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--') # Diagonal line
plt.show()
# --------------------
# 10. Save the Model
# --------------------
# Save the best model pipeline
joblib.dump(grid_search.best_estimator_, 'close_volume_predictor_pipeline.pkl')
print("Model training complete and saved as 'close_volume_predictor_pipeline.pkl'")