{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":8328882,"sourceType":"datasetVersion","datasetId":4945865}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"script","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:09.546792Z\",\"iopub.execute_input\":\"2024-06-15T06:39:09.547200Z\",\"iopub.status.idle\":\"2024-06-15T06:39:10.673349Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:09.547167Z\",\"shell.execute_reply\":\"2024-06-15T06:39:10.672291Z\"}}\n# 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\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/nvidia-corporation-nvda-stock-2020-to-2024'):\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\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:10.675209Z\",\"iopub.execute_input\":\"2024-06-15T06:39:10.675687Z\",\"iopub.status.idle\":\"2024-06-15T06:39:27.833999Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:10.675656Z\",\"shell.execute_reply\":\"2024-06-15T06:39:27.832568Z\"}}\n!pip install swish\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:27.835803Z\",\"iopub.execute_input\":\"2024-06-15T06:39:27.836235Z\",\"iopub.status.idle\":\"2024-06-15T06:39:40.552858Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:27.836191Z\",\"shell.execute_reply\":\"2024-06-15T06:39:40.551494Z\"}}\npip install swish-activation\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:40.556303Z\",\"iopub.execute_input\":\"2024-06-15T06:39:40.556775Z\",\"iopub.status.idle\":\"2024-06-15T06:39:55.689227Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:40.556729Z\",\"shell.execute_reply\":\"2024-06-15T06:39:55.687903Z\"}}\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Layer\nimport swish\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_percentage_error\nimport tensorflow as tf\nfrom keras import Model\nfrom keras.layers import Input, Dense, Dropout\nfrom keras.layers import LSTM\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:55.690663Z\",\"iopub.execute_input\":\"2024-06-15T06:39:55.691344Z\",\"iopub.status.idle\":\"2024-06-15T06:39:55.714646Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:55.691312Z\",\"shell.execute_reply\":\"2024-06-15T06:39:55.713464Z\"}}\ndf = pd.read_csv(\"/kaggle/input/nvidia-corporation-nvda-stock-2020-to-2024/nvda_stock_data.csv\")\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:55.716457Z\",\"iopub.execute_input\":\"2024-06-15T06:39:55.716825Z\",\"iopub.status.idle\":\"2024-06-15T06:39:55.761246Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:55.716797Z\",\"shell.execute_reply\":\"2024-06-15T06:39:55.760151Z\"}}\ndf.head()\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:55.762775Z\",\"iopub.execute_input\":\"2024-06-15T06:39:55.763154Z\",\"iopub.status.idle\":\"2024-06-15T06:39:55.776693Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:55.763123Z\",\"shell.execute_reply\":\"2024-06-15T06:39:55.775343Z\"}}\ndf = df.drop(['Adj Close', 'Volume'], axis=1)\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:55.778217Z\",\"iopub.execute_input\":\"2024-06-15T06:39:55.778759Z\",\"iopub.status.idle\":\"2024-06-15T06:39:55.807901Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:55.778678Z\",\"shell.execute_reply\":\"2024-06-15T06:39:55.806569Z\"}}\ndf.info()\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:55.809222Z\",\"iopub.execute_input\":\"2024-06-15T06:39:55.809560Z\",\"iopub.status.idle\":\"2024-06-15T06:39:55.840003Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:55.809513Z\",\"shell.execute_reply\":\"2024-06-15T06:39:55.838636Z\"}}\ndf.describe()\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:55.844750Z\",\"iopub.execute_input\":\"2024-06-15T06:39:55.845127Z\",\"iopub.status.idle\":\"2024-06-15T06:39:55.857869Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:55.845096Z\",\"shell.execute_reply\":\"2024-06-15T06:39:55.856783Z\"}}\ndf['Date'] = pd.to_datetime(df['Date'])\ndf.sort_values(by='Date', ascending=True, inplace=True)\ndf.reset_index(drop=True, inplace=True)\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:55.859128Z\",\"iopub.execute_input\":\"2024-06-15T06:39:55.859474Z\",\"iopub.status.idle\":\"2024-06-15T06:39:57.927912Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:55.859439Z\",\"shell.execute_reply\":\"2024-06-15T06:39:57.926615Z\"}}\nfig = px.line(y=df.Open, x=df.Date)\nfig.update_traces(line_color='black') \nfig.update_layout(xaxis_title=\"Date\", \n                  yaxis_title=\"Scaled Price\",\n                  title={'text': \"Nvidia Stock Price History Data\", 'y':0.95, 'x':0.5, 'xanchor':'center', 'yanchor':'top'},\n                  plot_bgcolor='rgba(50,233,21,0.8)')\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:57.929428Z\",\"iopub.execute_input\":\"2024-06-15T06:39:57.929876Z\",\"iopub.status.idle\":\"2024-06-15T06:39:57.941508Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:57.929838Z\",\"shell.execute_reply\":\"2024-06-15T06:39:57.939807Z\"}}\ntest_size = df[df.Date.dt.year==2023].shape[0]\ntest_size\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:57.944055Z\",\"iopub.execute_input\":\"2024-06-15T06:39:57.944736Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.513722Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:57.944675Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.512564Z\"}}\nplt.figure(figsize=(15, 6), dpi=150)\nplt.rcParams['axes.facecolor'] = 'green'\nplt.rc('axes',edgecolor='black')\nplt.plot(df.Date[:-test_size], df.Open[:-test_size], color='black', lw=2)\nplt.plot(df.Date[-test_size:], df.Open[-test_size:], color='red', lw=2)\nplt.title('Nvidia Stock Price Training and Test Sets', fontsize=15)\nplt.xlabel('Date', fontsize=12)\nplt.ylabel('Price', fontsize=12)\nplt.legend(['Training set', 'Test set'], loc='upper left', prop={'size': 15})\nplt.grid(color='white')\nplt.show()\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.515059Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.515388Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.525605Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.515358Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.524556Z\"}}\nscaler = MinMaxScaler()\nscaler.fit(df.Open.values.reshape(-1,1))\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.526790Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.527122Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.533458Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.527095Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.532196Z\"}}\nwindow_size = 60\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.535167Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.536117Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.546264Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.536081Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.544991Z\"}}\ntrain_data = df.Open[:-test_size]\ntrain_data = scaler.transform(train_data.values.reshape(-1,1))\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.548421Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.548930Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.560957Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.548885Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.559456Z\"}}\nX_train = []\ny_train = []\n\nfor i in range(window_size, len(train_data)):\n    X_train.append(train_data[i-60:i, 0])\n    y_train.append(train_data[i, 0])\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.562672Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.563061Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.573265Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.563030Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.572030Z\"}}\ntest_data = df.Open[-test_size-60:]\ntest_data = scaler.transform(test_data.values.reshape(-1,1))\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.574907Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.576046Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.585633Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.576007Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.584559Z\"}}\nX_test = []\ny_test = []\n\nfor i in range(window_size, len(test_data)):\n    X_test.append(test_data[i-60:i, 0])\n    y_test.append(test_data[i, 0])\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.587274Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.587860Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.600320Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.587815Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.599036Z\"}}\nX_train = np.array(X_train)\nX_test  = np.array(X_test)\ny_train = np.array(y_train)\ny_test  = np.array(y_test)\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.601828Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.602260Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.613096Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.602222Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.611703Z\"}}\nX_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\nX_test  = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\ny_train = np.reshape(y_train, (-1,1))\ny_test  = np.reshape(y_test, (-1,1))\n\nprint('X_train Shape: ', X_train.shape)\nprint('y_train Shape: ', y_train.shape)\nprint('X_test Shape:  ', X_test.shape)\nprint('y_test Shape:  ', y_test.shape)\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.614510Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.614933Z\",\"iopub.status.idle\":\"2024-06-15T06:39:58.628218Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.614895Z\",\"shell.execute_reply\":\"2024-06-15T06:39:58.626866Z\"}}\nclass Swish(Layer):\n    def call(self, inputs):\n        return inputs * tf.nn.sigmoid(inputs)\n\ndef define_model():\n    input1 = Input(shape=(window_size, 1))\n    x = LSTM(units=64, return_sequences=True)(input1)\n    x = Dropout(0.2)(x)\n    x = LSTM(units=64, return_sequences=True)(x)\n    x = Dropout(0.2)(x)\n    x = LSTM(units=64)(x)\n    x = Dropout(0.2)(x)\n\n    x = Dense(128, activation=Swish())(x)\n\n    dnn_output = Dense(1, activation=Swish())(x)\n\n    model = Model(inputs=input1, outputs=[dnn_output])\n    model.compile(loss='mean_squared_error', optimizer='Adam')\n    model.summary()\n    \n    return model\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:39:58.629984Z\",\"iopub.execute_input\":\"2024-06-15T06:39:58.630445Z\",\"iopub.status.idle\":\"2024-06-15T06:41:25.093740Z\",\"shell.execute_reply.started\":\"2024-06-15T06:39:58.630403Z\",\"shell.execute_reply\":\"2024-06-15T06:41:25.092364Z\"}}\nmodel = define_model()\nmodel.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.2, verbose=1)\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:41:25.095247Z\",\"iopub.execute_input\":\"2024-06-15T06:41:25.096264Z\",\"iopub.status.idle\":\"2024-06-15T06:41:26.578012Z\",\"shell.execute_reply.started\":\"2024-06-15T06:41:25.096220Z\",\"shell.execute_reply\":\"2024-06-15T06:41:26.576693Z\"}}\nresult = model.evaluate(X_test, y_test)\ny_pred = model.predict(X_test) \n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:41:26.580038Z\",\"iopub.execute_input\":\"2024-06-15T06:41:26.580863Z\",\"iopub.status.idle\":\"2024-06-15T06:41:26.586997Z\",\"shell.execute_reply.started\":\"2024-06-15T06:41:26.580818Z\",\"shell.execute_reply\":\"2024-06-15T06:41:26.585517Z\"}}\nMAPE = mean_absolute_percentage_error(y_test, y_pred)\nAccuracy = 1 - MAPE\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:41:26.588380Z\",\"iopub.execute_input\":\"2024-06-15T06:41:26.588742Z\",\"iopub.status.idle\":\"2024-06-15T06:41:26.601411Z\",\"shell.execute_reply.started\":\"2024-06-15T06:41:26.588713Z\",\"shell.execute_reply\":\"2024-06-15T06:41:26.600212Z\"}}\nprint(\"Test Loss:\", result)\nprint(\"Test MAPE:\", MAPE)\nprint(\"Test Accuracy:\", Accuracy)\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:41:26.602874Z\",\"iopub.execute_input\":\"2024-06-15T06:41:26.603242Z\",\"iopub.status.idle\":\"2024-06-15T06:41:26.616012Z\",\"shell.execute_reply.started\":\"2024-06-15T06:41:26.603205Z\",\"shell.execute_reply\":\"2024-06-15T06:41:26.614559Z\"}}\ny_test_true = scaler.inverse_transform(y_test)\ny_test_pred = scaler.inverse_transform(y_pred)\n\n# %% [code] {\"execution\":{\"iopub.status.busy\":\"2024-06-15T06:41:26.622099Z\",\"iopub.execute_input\":\"2024-06-15T06:41:26.623222Z\",\"iopub.status.idle\":\"2024-06-15T06:41:27.166070Z\",\"shell.execute_reply.started\":\"2024-06-15T06:41:26.623180Z\",\"shell.execute_reply\":\"2024-06-15T06:41:27.164932Z\"}}\nplt.figure(figsize=(15, 6), dpi=150)\nplt.rcParams['axes.facecolor'] = 'green'\nplt.rc('axes',edgecolor='black')\nplt.plot(df['Date'].iloc[:-test_size], scaler.inverse_transform(train_data), color='black', lw=2)\nplt.plot(df['Date'].iloc[-test_size:], y_test_true, color='yellow', lw=2)\nplt.plot(df['Date'].iloc[-test_size:], y_test_pred, color='red', lw=2)\nplt.title('Model Performance on Nvidia Stock Price Prediction', fontsize=15)\nplt.xlabel('Date', fontsize=12)\nplt.ylabel('Price', fontsize=12)\nplt.legend(['Training Data', 'Actual Test Data', 'Predicted Test Data'], loc='upper left', prop={'size': 15})\nplt.grid(color='white')\nplt.show()","metadata":{"_uuid":"0321951b-4a60-4f30-bd68-d92860f2e2d0","_cell_guid":"56e93494-37bb-48eb-a133-8d7551ca895c","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]}]}