{"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"}],"dockerImageVersionId":30805,"isInternetEnabled":true,"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-03T03:16:51.863592Z","iopub.execute_input":"2024-12-03T03:16:51.864583Z","iopub.status.idle":"2024-12-03T03:16:51.88826Z","shell.execute_reply.started":"2024-12-03T03:16:51.864547Z","shell.execute_reply":"2024-12-03T03:16:51.887315Z"}},"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-03T03:16:51.889917Z","iopub.execute_input":"2024-12-03T03:16:51.89019Z","iopub.status.idle":"2024-12-03T03:16:51.895291Z","shell.execute_reply.started":"2024-12-03T03:16:51.890165Z","shell.execute_reply":"2024-12-03T03:16:51.894372Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#path = '/kaggle/input/jane-street-real-time-market-data-forecasting/train.parquet'\n#dirs = os.listdir(path)\n#for file in dirs:\n    #file_path = os.path.join(path,file)\n    #file_path = file_path + '/' + 'part-0.parquet'\n    #print(file_path)\n    #train = pd.read_parquet('/kaggle/input/jane-street-real-time-market-data-forecasting/train.parquet/part-0.parquet')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T03:16:51.896305Z","iopub.execute_input":"2024-12-03T03:16:51.896643Z","iopub.status.idle":"2024-12-03T03:16:51.9102Z","shell.execute_reply.started":"2024-12-03T03:16:51.896594Z","shell.execute_reply":"2024-12-03T03:16:51.909236Z"}},"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-03T03:16:51.912567Z","iopub.execute_input":"2024-12-03T03:16:51.913107Z","iopub.status.idle":"2024-12-03T03:17:09.047458Z","shell.execute_reply.started":"2024-12-03T03:16:51.913064Z","shell.execute_reply":"2024-12-03T03:17:09.046413Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train.columns)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T03:17:09.048726Z","iopub.execute_input":"2024-12-03T03:17:09.049134Z","iopub.status.idle":"2024-12-03T03:17:09.056097Z","shell.execute_reply.started":"2024-12-03T03:17:09.049081Z","shell.execute_reply":"2024-12-03T03:17:09.055108Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"'''def train_xgb_model(train: pd.DataFrame) -> 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    # Define and train the XGBoost model\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    model.fit(X, y)\n    return model\n'''","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T03:17:09.057428Z","iopub.execute_input":"2024-12-03T03:17:09.057729Z","iopub.status.idle":"2024-12-03T03:17:09.070081Z","shell.execute_reply.started":"2024-12-03T03:17:09.057696Z","shell.execute_reply":"2024-12-03T03:17:09.069101Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from xgboost import XGBRegressor\nfrom sklearn.model_selection import train_test_split\n\ndef train_xgb_model(train: pd.DataFrame) -> 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 the data into training and validation sets\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 XGBoost model\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    # Train the model with early stopping and verbose logging\n    model.fit(\n        X_train, y_train,\n        eval_set=[(X_val, y_val)],  # Validation set for early stopping\n        early_stopping_rounds=10,  # Stop if no improvement for 10 rounds\n        verbose=True  # Logs training progress\n    )\n\n    return model\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T03:17:09.071202Z","iopub.execute_input":"2024-12-03T03:17:09.071484Z","iopub.status.idle":"2024-12-03T03:17:09.084817Z","shell.execute_reply.started":"2024-12-03T03:17:09.071454Z","shell.execute_reply":"2024-12-03T03:17:09.083915Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = train_xgb_model(train)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T03:17:09.08694Z","iopub.execute_input":"2024-12-03T03:17:09.087395Z","iopub.status.idle":"2024-12-03T03:57:22.12693Z","shell.execute_reply.started":"2024-12-03T03:17:09.087345Z","shell.execute_reply":"2024-12-03T03:57:22.126105Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"lags_ : pl.DataFrame | None = None\n\n\n# Replace this function with your inference code.\n# You can return either a Pandas or Polars dataframe, though Polars is recommended.\n# Each batch of predictions (except the very first) must be returned within 1 minute of the batch features being provided.\ndef predict(test: pl.DataFrame, lags: pl.DataFrame | None) -> pl.DataFrame | pd.DataFrame:\n    \"\"\"Make a prediction.\"\"\"\n    # All the responders from the previous day are passed in at time_id == 0. We save them in a global variable for access at every time_id.\n    # Use them as extra features, if you like.\n    global lags_\n    if lags is not None:\n        lags_ = lags\n\n    # Replace this section with your own predictions\n    predictions = test.select(\n        'row_id',\n        pl.lit(0.0).alias('responder_6'),\n    )\n\n    if isinstance(predictions, pl.DataFrame):\n        assert predictions.columns == ['row_id', 'responder_6']\n    elif isinstance(predictions, pd.DataFrame):\n        assert (predictions.columns == ['row_id', 'responder_6']).all()\n    else:\n        raise TypeError('The predict function must return a DataFrame')\n    # Confirm has as many rows as the test data.\n    assert len(predictions) == len(test)\n\n    return predictions","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T03:57:22.127829Z","iopub.execute_input":"2024-12-03T03:57:22.128064Z","iopub.status.idle":"2024-12-03T03:57:22.134454Z","shell.execute_reply.started":"2024-12-03T03:57:22.128041Z","shell.execute_reply":"2024-12-03T03:57:22.133603Z"}},"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,"execution":{"iopub.status.busy":"2024-12-03T03:57:22.135532Z","iopub.execute_input":"2024-12-03T03:57:22.135835Z","iopub.status.idle":"2024-12-03T03:57:22.433371Z","shell.execute_reply.started":"2024-12-03T03:57:22.135776Z","shell.execute_reply":"2024-12-03T03:57:22.432454Z"}},"outputs":[],"execution_count":null}]}