|
import polars as pl
|
|
import tsfel
|
|
import numpy as np
|
|
from tqdm import tqdm
|
|
import warnings
|
|
import os
|
|
import optuna
|
|
from sklearn.model_selection import train_test_split, cross_val_score
|
|
from sklearn.pipeline import Pipeline
|
|
from sklearn.compose import ColumnTransformer
|
|
from sklearn.preprocessing import FunctionTransformer
|
|
from sklearn.base import BaseEstimator, TransformerMixin
|
|
from xgboost import XGBClassifier
|
|
from lightgbm import LGBMClassifier
|
|
|
|
from cfg import DROP_LIST
|
|
|
|
|
|
|
|
def load_and_balance_data(filename, ratio=1/60):
|
|
"""
|
|
Loads data from a CSV file and balances classes to address potential imbalance.
|
|
|
|
Args:
|
|
filename (str): Path to the CSV file
|
|
ratio (float): Ratio of positive to negative examples to balance
|
|
|
|
Returns:
|
|
pl.DataFrame: Balanced dataframe
|
|
"""
|
|
print(f"Ratio: {ratio}")
|
|
|
|
|
|
data = pl.read_csv(filename)
|
|
|
|
positive = data.filter(pl.col("飆股") == 1)
|
|
negative = data.filter(pl.col("飆股") == 0)
|
|
|
|
|
|
negative = negative.sample(fraction=ratio)
|
|
|
|
|
|
combined = positive.vstack(negative)
|
|
|
|
return combined
|
|
|
|
def create_stock_prediction_pipeline(params=None):
|
|
start_end_list = [
|
|
|
|
|
|
|
|
|
|
|
|
]
|
|
|
|
|
|
if params is None:
|
|
classifier = XGBClassifier(n_jobs=-1)
|
|
else:
|
|
classifier = XGBClassifier(
|
|
|
|
n_jobs=-1,
|
|
**params
|
|
)
|
|
|
|
pipeline = Pipeline([
|
|
|
|
('classifier', classifier)
|
|
])
|
|
return pipeline
|
|
|
|
def objective(trial, X, y):
|
|
"""Optuna objective function for hyperparameter tuning"""
|
|
|
|
|
|
params = {
|
|
|
|
'learning_rate': trial.suggest_float('learning_rate', 0.001, 0.3, log=True),
|
|
'max_depth': trial.suggest_int('max_depth', 3, 140),
|
|
'n_estimators': trial.suggest_int('n_estimators', 50, 3000),
|
|
'subsample': trial.suggest_float('subsample', 0.5, 1.0),
|
|
'colsample_bytree': trial.suggest_float('colsample_bytree', 0.5, 1.0),
|
|
'gamma': trial.suggest_float('gamma', 0, 5),
|
|
'min_child_weight': trial.suggest_int('min_child_weight', 1, 10),
|
|
'reg_alpha': trial.suggest_float('reg_alpha', 0, 10),
|
|
'reg_lambda': trial.suggest_float('reg_lambda', 1, 10)
|
|
}
|
|
|
|
|
|
pipeline = create_stock_prediction_pipeline(params)
|
|
|
|
|
|
scores = cross_val_score(pipeline, X, y, cv=3, scoring='f1')
|
|
|
|
|
|
return scores.mean()
|
|
|
|
def main():
|
|
|
|
print("Loading and preprocessing training data...")
|
|
combined = load_and_balance_data('./cleaned_training.csv', ratio=1/90)
|
|
|
|
|
|
X = combined.drop(DROP_LIST)
|
|
y = combined["飆股"]
|
|
|
|
|
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
|
|
|
|
|
print("Starting hyperparameter optimization with Optuna...")
|
|
study = optuna.create_study(direction='maximize')
|
|
study.optimize(lambda trial: objective(trial, X_train, y_train), n_trials=100, show_progress_bar=True)
|
|
|
|
|
|
best_params = study.best_params
|
|
best_value = study.best_value
|
|
print(f"Best F1 score: {best_value:.4f}")
|
|
print("Best hyperparameters:", best_params)
|
|
|
|
|
|
print("Training final model with the best parameters...")
|
|
pipeline = create_stock_prediction_pipeline(best_params)
|
|
pipeline.fit(X_train, y_train)
|
|
|
|
|
|
print("Evaluating the model...")
|
|
y_pred = pipeline.predict(X_test)
|
|
|
|
|
|
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix
|
|
|
|
accuracy = accuracy_score(y_test, y_pred)
|
|
f1 = f1_score(y_test, y_pred)
|
|
precision = precision_score(y_test, y_pred)
|
|
recall = recall_score(y_test, y_pred)
|
|
|
|
print(f"Accuracy: {accuracy:.4f}")
|
|
print(f"F1 Score: {f1:.4f}")
|
|
print(f"Precision: {precision:.4f}")
|
|
print(f"Recall: {recall:.4f}")
|
|
|
|
|
|
cm = confusion_matrix(y_test, y_pred)
|
|
print("Confusion Matrix:")
|
|
print(cm)
|
|
|
|
|
|
print("Loading test data and making predictions...")
|
|
test = pl.read_csv('./38_Public_Test_Set_and_Submmision_Template/38_Public_Test_Set_and_Submmision_Template/public_x.csv')
|
|
template = pl.read_csv('./38_Public_Test_Set_and_Submmision_Template/38_Public_Test_Set_and_Submmision_Template/submission_template_public.csv')
|
|
|
|
|
|
selected = test.select(X.columns)
|
|
|
|
|
|
y_pred_test = pipeline.predict(selected)
|
|
|
|
|
|
unique, counts = np.unique(y_pred_test, return_counts=True)
|
|
print("Prediction counts:", dict(zip(unique, counts)))
|
|
|
|
|
|
template = template.with_columns(pl.Series("飆股", y_pred_test))
|
|
template.write_csv("submission.csv")
|
|
print("Predictions saved to submission.csv")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|