{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.14"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":84493,"databundleVersionId":9871156,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false},"papermill":{"default_parameters":{},"duration":4.669361,"end_time":"2024-10-10T13:05:46.686069","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-10-10T13:05:42.016708","version":"2.6.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')\n\nimport os\n\nimport pandas as pd\nimport polars as pl\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport tensorflow.keras.layers as layers\nfrom tensorflow.keras.callbacks import Callback, ReduceLROnPlateau, ModelCheckpoint, EarlyStopping\n\nfrom sklearn.metrics import roc_auc_score, roc_curve, mean_squared_error\nfrom sklearn.model_selection import GroupKFold, train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\n\nimport xgboost as xgb\n \nimport kaggle_evaluation.jane_street_inference_server\n\ntf.random.set_seed(11)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":1.223703,"end_time":"2024-10-10T13:05:45.825911","exception":false,"start_time":"2024-10-10T13:05:44.602208","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2024-12-31T06:08:46.477339Z","iopub.execute_input":"2024-12-31T06:08:46.478631Z","iopub.status.idle":"2024-12-31T06:08:59.707513Z","shell.execute_reply.started":"2024-12-31T06:08:46.478558Z","shell.execute_reply":"2024-12-31T06:08:59.706027Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = pl.read_parquet('/kaggle/input/jane-street-real-time-market-data-forecasting/train.parquet')\ntrain.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-31T06:09:20.411913Z","iopub.execute_input":"2024-12-31T06:09:20.412851Z","iopub.status.idle":"2024-12-31T06:10:20.007190Z","shell.execute_reply.started":"2024-12-31T06:09:20.412804Z","shell.execute_reply":"2024-12-31T06:10:20.005822Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"responder_6 = train['responder_6'].to_numpy()\nplt.hist(responder_6, bins=50, alpha=0.75)\nplt.title('Responder_6 Distribution')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-31T06:23:12.569844Z","iopub.execute_input":"2024-12-31T06:23:12.571951Z","iopub.status.idle":"2024-12-31T06:23:14.205197Z","shell.execute_reply.started":"2024-12-31T06:23:12.571877Z","shell.execute_reply":"2024-12-31T06:23:14.203538Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load features.csv\nfeatures = pl.read_csv('/kaggle/input/jane-street-real-time-market-data-forecasting/features.csv')\n\n# Group features by tag_0\ntag_0_features = features.filter(features['tag_0'] == True)['feature']\nprint(tag_0_features)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-31T06:23:22.278764Z","iopub.execute_input":"2024-12-31T06:23:22.279262Z","iopub.status.idle":"2024-12-31T06:23:22.420188Z","shell.execute_reply.started":"2024-12-31T06:23:22.279217Z","shell.execute_reply":"2024-12-31T06:23:22.418553Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"lags = pl.read_parquet('/kaggle/input/jane-street-real-time-market-data-forecasting/lags.parquet')\nlags.head(5)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-31T06:23:25.606153Z","iopub.execute_input":"2024-12-31T06:23:25.606688Z","iopub.status.idle":"2024-12-31T06:23:25.633680Z","shell.execute_reply.started":"2024-12-31T06:23:25.606635Z","shell.execute_reply":"2024-12-31T06:23:25.632393Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"feature_cols = [col for col in train.columns if col.startswith('feature')]\ntarget_col = 'responder_6'\n\nX = train.select(feature_cols).to_numpy()\ny = train[target_col].to_numpy()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-31T06:23:29.031475Z","iopub.execute_input":"2024-12-31T06:23:29.032016Z","execution_failed":"2024-12-31T06:23:49.260Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Split data\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(f\"Using device: {device.type}\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = RandomForestRegressor(n_estimators=100, random_state=42)\n\nmodel.to(device)\nmodel.fit(X_train, y_train)\nmodel","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Evaluate\npredictions = model.predict(X_val)\nprint('MSE:', mean_squared_error(y_val, predictions))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"The evaluation API requires that you set up a server which will respond to inference requests. We have already defined the server; you just need write the predict function. When we evaluate your submission on the hidden test set the client defined in `jane_street_gateway` will run in a different container with direct access to the hidden test set and hand off the data timestep by timestep.\n\n\n\nYour code will always have access to the published copies of the files.","metadata":{"papermill":{"duration":0.002051,"end_time":"2024-10-10T13:05:45.83073","exception":false,"start_time":"2024-10-10T13:05:45.828679","status":"completed"},"tags":[]}},{"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":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":0.015917,"end_time":"2024-10-10T13:05:45.848958","exception":false,"start_time":"2024-10-10T13:05:45.833041","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"When your notebook is run on the hidden test set, inference_server.serve must be called within 15 minutes of the notebook starting or the gateway will throw an error. If you need more than 15 minutes to load your model you can do so during the very first `predict` call, which does not have the usual 1 minute response deadline.","metadata":{"papermill":{"duration":0.00196,"end_time":"2024-10-10T13:05:45.853279","exception":false,"start_time":"2024-10-10T13:05:45.851319","status":"completed"},"tags":[]}},{"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":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":0.308219,"end_time":"2024-10-10T13:05:46.163573","exception":false,"start_time":"2024-10-10T13:05:45.855354","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}