{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":84493,"databundleVersionId":9871156,"sourceType":"competition"},{"sourceId":211627434,"sourceType":"kernelVersion"}],"dockerImageVersionId":30805,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport polars as pl\nimport kaggle_evaluation.jane_street_inference_server\nimport glob\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom xgboost import XGBRegressor\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-03T05:32:40.800013Z","iopub.execute_input":"2024-12-03T05:32:40.800903Z","iopub.status.idle":"2024-12-03T05:32:43.621343Z","shell.execute_reply.started":"2024-12-03T05:32:40.800862Z","shell.execute_reply":"2024-12-03T05:32:43.620448Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def normalize_data(data: pd.DataFrame) -> pd.DataFrame:\n    # Select only columns that start with \"feature_\" and have a numeric type excluding int8, int16, int32, int64, bool\n    feature_cols = [\n        col for col in data.columns\n        if col.startswith(\"feature_\") and\n        data[col].dtype not in [np.int8, np.int16, np.int32, np.int64, np.bool_]\n    ]\n    \n    # Apply MinMaxScaler to the selected features\n    scaler = MinMaxScaler(feature_range=(0, 1))\n    data[feature_cols] = scaler.fit_transform(data[feature_cols])\n    \n    return data","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T05:32:43.623054Z","iopub.execute_input":"2024-12-03T05:32:43.623972Z","iopub.status.idle":"2024-12-03T05:32:43.629509Z","shell.execute_reply.started":"2024-12-03T05:32:43.623919Z","shell.execute_reply":"2024-12-03T05:32:43.628583Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"parquet_folder = '/kaggle/input/jane-street-real-time-market-data-forecasting/train.parquet'\n\nparquet_files = []\nfor root, dirs, files in os.walk(parquet_folder):\n    for file in files:\n        if file.endswith('.parquet'):\n            parquet_files.append(os.path.join(root, file))\n            \nparquet_files = parquet_files [:2] \n\ntrain_data = pd.concat([pd.read_parquet(file) for file in parquet_files])\n\ntrain = normalize_data(train_data)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T05:32:43.630705Z","iopub.execute_input":"2024-12-03T05:32:43.631063Z","iopub.status.idle":"2024-12-03T05:32:43.654701Z","shell.execute_reply.started":"2024-12-03T05:32:43.631025Z","shell.execute_reply":"2024-12-03T05:32:43.653870Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nfrom xgboost import XGBRegressor\nfrom xgboost import callback\n\ndef train_xgb_model(train: pd.DataFrame, eval_metric='rmse', early_stopping_rounds=50) -> XGBRegressor:\n    # Identify feature columns and target column\n    feature_cols = [col for col in train.columns if col.startswith(\"feature_\")]\n    target_col = 'responder_6'\n\n    # Split features (X) and target (y)\n    X = train[feature_cols]\n    if target_col in train.columns:\n        y = train[target_col]\n    else:\n        raise ValueError(f\"Target column '{target_col}' not found in the dataset.\")\n\n    # Split a portion of the data for validation (e.g., 20% for validation)\n    from sklearn.model_selection import train_test_split\n    X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\n    # Define the model with early stopping parameters\n    model = XGBRegressor(\n        n_estimators=1000,\n        learning_rate=0.05,\n        max_depth=8,\n        subsample=0.8,\n        colsample_bytree=0.8,\n        objective='reg:squarederror',\n        random_state=42\n    )\n\n    # Define the evaluation set for early stopping\n    eval_set = [(X_val, y_val)]\n\n    # Fit the model with early stopping\n    model.fit(\n        X_train, y_train,\n        eval_metric=eval_metric,\n        eval_set=eval_set,\n        early_stopping_rounds=early_stopping_rounds,\n        verbose=10\n    )\n    \n    return model\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import joblib\nmodel_path = \"/kaggle/input/fanyingsudu217/trained_xgb_model.pkl\"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import polars as pl\nimport pandas as pd\n\ndef predict(test: pl.DataFrame, lags: pl.DataFrame | None = None) -> pd.DataFrame:\n    model = joblib.load(model_path)\n    test_df = test.to_pandas()  # Convert Polars DataFrame to Pandas\n    \n    # Select the feature columns that start with \"feature_\"\n    feature_cols = [col for col in test_df.columns if col.startswith(\"feature_\")]\n    test_features = test_df[feature_cols]\n    \n    # Make predictions using the trained model\n    predictions = model.predict(test_features)\n    \n    # Prepare the result DataFrame with the row_id and predictions for 'responder_6'\n    result = pd.DataFrame({\n        'row_id': test_df['row_id'],\n        'responder_6': predictions\n    })\n    \n    return result\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"inference_server = kaggle_evaluation.jane_street_inference_server.JSInferenceServer(predict)\n\nif os.getenv('KAGGLE_IS_COMPETITION_RERUN'):\n    inference_server.serve()\nelse:\n    inference_server.run_local_gateway(\n        (\n            '/kaggle/input/jane-street-real-time-market-data-forecasting/test.parquet',\n            '/kaggle/input/jane-street-real-time-market-data-forecasting/lags.parquet',\n        )\n    )","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}