{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n# Load the dataset\ndf = pd.read_csv('/kaggle/input/stock-market-dataset/stocks/A.csv')\n\n# Convert the date column to numerical values\ndf['Date'] = pd.to_datetime(df['Date'])\ndf['Date'] = (df['Date'] - df['Date'].min()) / np.timedelta64(1,'D')\n\n# Split the data into features and target variables\nX = df.drop(['Close', 'Date'], axis=1)\ny = df['Close']\n\n# Split the data into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n# Create a Linear Regression model\nmodel = LinearRegression()\n\n# Train the model on the training data\nmodel.fit(X_train, y_train)\n\n# Use the trained model to make predictions on the test data\ny_pred = model.predict(X_test)\n\n# Evaluate the model by calculating the mean squared error and R^2 score\nmse = mean_squared_error(y_test, y_pred)\nr2 = r2_score(y_test, y_pred)\n\nprint('Mean Squared Error:', mse)\nprint('R^2 Score:', r2)\n\nplt.scatter(y_test, y_pred)\nplt.xlabel('True Values')\nplt.ylabel('Predictions')\nplt.show()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-03-03T17:02:10.992696Z","iopub.execute_input":"2023-03-03T17:02:10.993141Z","iopub.status.idle":"2023-03-03T17:02:11.480084Z","shell.execute_reply.started":"2023-03-03T17:02:10.993102Z","shell.execute_reply":"2023-03-03T17:02:11.478567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.linear_model import LinearRegression\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load the dataset into a pandas dataframe\ndf = pd.read_csv(\"/kaggle/input/stock-market-dataset/stocks/AAME.csv\")\n\n# Extract the input features and output variable\nX = df[['Open', 'High', 'Low', 'Adj Close', 'Volume']]\ny = df['Close']\n\n# Initialize the linear regression model\nmodel = LinearRegression()\n\n# Fit the model on the training data\nmodel.fit(X, y)\n\n# Predict the close attribute for the entire dataset\npredicted_close = model.predict(X)\n\n# Plot the predicted values against the actual values\nplt.scatter(y, predicted_close)\nplt.xlabel(\"Actual Close\")\nplt.ylabel(\"Predicted Close\")\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-03-03T17:17:12.104915Z","iopub.execute_input":"2023-03-03T17:17:12.105352Z","iopub.status.idle":"2023-03-03T17:17:12.415046Z","shell.execute_reply.started":"2023-03-03T17:17:12.105317Z","shell.execute_reply":"2023-03-03T17:17:12.413869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\n\n# load data into a DataFrame\ndf = pd.read_csv('/kaggle/input/stock-market-dataset/stocks/A.csv')\n\n# define the independent variables\nX = df[[\"Open\", \"High\", \"Low\"]]\n\n# add a constant term to the independent variables\nX = sm.add_constant(X)\n\n# define the dependent variable\ny = df[\"Close\"]\n\n# fit the model\nmodel = sm.OLS(y, X).fit()\n\n# print the summary of the regression results\nprint(model.summary())\n\n# plot the scatter plot of the actual vs predicted values\nfig, ax = plt.subplots()\nax.scatter(y, model.predict(), alpha=0.5)\nax.plot([y.min(), y.max()], [y.min(), y.max()], 'r--')\nax.set_xlabel('Actual')\nax.set_ylabel('Predicted')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-03-03T17:17:20.381582Z","iopub.execute_input":"2023-03-03T17:17:20.381993Z","iopub.status.idle":"2023-03-03T17:17:20.656184Z","shell.execute_reply.started":"2023-03-03T17:17:20.381959Z","shell.execute_reply":"2023-03-03T17:17:20.655115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# load data into a DataFrame\ndf = pd.read_csv(\"/kaggle/input/stock-market-dataset/stocks/A.csv\")\n\n# define the independent variable\nX = df[[\"Open\", \"High\", \"Low\"]]\n\n# add a constant term to the independent variable\nX = sm.add_constant(X)\n\n# define the dependent variable\nthreshold = df['Close'].mean()\ny = (df['Close'] > threshold).astype(int)\nprint(y.unique())\n# fit the model\nmodel = sm.Logit(y, X).fit()\n\n# predict probabilities for a range of X values\nX_range = np.linspace(X.min(), X.max(), 100)\nX_range = sm.add_constant(X_range)\ny_pred = model.predict(X_range)\n\n# create scatter plot of the data\nfig, ax = plt.subplots()\nax.scatter(X[\"Open\"], y, marker=\"o\", alpha=0.5)\n\n# overlay predicted probabilities from the logistic regression model\nax.plot(X_range[:,1], y_pred, color=\"red\")\nax.set_xlabel(\"Open\")\nax.set_ylabel(\"Probability\")\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-02-21T07:55:48.593869Z","iopub.execute_input":"2023-02-21T07:55:48.595190Z","iopub.status.idle":"2023-02-21T07:55:48.904570Z","shell.execute_reply.started":"2023-02-21T07:55:48.595134Z","shell.execute_reply":"2023-02-21T07:55:48.903250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# load data into a DataFrame\ndf = pd.read_csv(\"/kaggle/input/stock-market-dataset/stocks/A.csv\")\n\n# define the independent variable\nX = df[[\"Open\", \"High\", \"Low\"]]\n\n# add a constant term to the independent variable\nX = sm.add_constant(X)\n\n# define the dependent variable\ny = df[\"Close\"].astype(int)\n\n# fit the model\nmodel = sm.Poisson(y, X).fit()\n\n# predict values for a range of X values\nX_range = np.linspace(X.min(), X.max(), 100)\nX_range = sm.add_constant(X_range)\ny_pred = model.predict(X_range)\n\n# create scatter plot of the data\nfig, ax = plt.subplots(figsize=(10, 6))\nax.scatter(X[\"Open\"], y, marker=\"o\", alpha=0.5)\n\n# overlay predicted values from the Poisson regression model\nax.plot(X_range[:,1], y_pred, color=\"red\")\nax.set_xlabel(\"Open\")\nax.set_ylabel(\"Close\")\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-02-21T07:55:48.906319Z","iopub.execute_input":"2023-02-21T07:55:48.906700Z","iopub.status.idle":"2023-02-21T07:55:49.189562Z","shell.execute_reply.started":"2023-02-21T07:55:48.906666Z","shell.execute_reply":"2023-02-21T07:55:49.188575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport statsmodels.api as sm\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize\nfrom scipy.special import factorial\n\n# load data into a DataFrame\ndf = pd.read_csv(\"/kaggle/input/stock-market-dataset/stocks/A.csv\")\n\n# define the independent variable\nX = df[[\"Open\", \"High\", \"Low\"]]\n\n# add a constant term to the independent variable\nX = sm.add_constant(X)\n\n# define the dependent variable\ny = df[\"Close\"].astype(int)\n\n# convert y to a NumPy array\ny = y.to_numpy()\n\n# define the Poisson regression equation\ndef poisson_regression_eq(X, beta):\n    return np.exp(np.dot(X, beta))\n\n# define the negative log-likelihood function\ndef poisson_loglikelihood(beta, X, y):\n    lambd = poisson_regression_eq(X, beta)\n    loglik = np.sum(y * np.log(lambd) - lambd - np.log(factorial(y)))\n    return -loglik\n\n# minimize the negative log-likelihood function to estimate the coefficients\nres = minimize(poisson_loglikelihood, np.zeros(X.shape[1]), args=(X, y))\n\n# get the estimated coefficients\nbeta_hat = res.x\n\n# predict values for a range of X values\nX_range = np.column_stack((np.ones(100), np.linspace(X.iloc[:,1].min(), X.iloc[:,1].max(), 100),\n                           np.linspace(X.iloc[:,2].min(), X.iloc[:,2].max(), 100),\n                           np.linspace(X.iloc[:,3].min(), X.iloc[:,3].max(), 100)))\ny_pred = poisson_regression_eq(X_range, beta_hat)\n\n# create scatter plot of the data\nfig, ax = plt.subplots(figsize=(10, 6))\nax.scatter(X[\"Open\"], y, marker=\"o\", alpha=0.5)\n\n# overlay predicted values from the Poisson regression model\nax.plot(X_range[:,1], y_pred, color=\"red\")\nax.set_xlabel(\"Open\")\nax.set_ylabel(\"Close\")\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-03-03T15:02:47.870701Z","iopub.execute_input":"2023-03-03T15:02:47.871095Z","iopub.status.idle":"2023-03-03T15:02:48.166675Z","shell.execute_reply.started":"2023-03-03T15:02:47.871063Z","shell.execute_reply":"2023-03-03T15:02:48.165586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef linear_regression(X, y):\n    # add column of ones to the input features for the intercept term\n    X = np.concatenate([np.ones((X.shape[0], 1)), X], axis=1)\n\n    # calculate coefficients using the normal equation\n    inversed = np.linalg.inv(X.T.dot(X))\n    coeffs = inversed.dot(X.T).dot(y)\n\n    # return predicted values\n    return X.dot(coeffs)\n\n# Load the dataset into a pandas dataframe\ndf = pd.read_csv(\"/kaggle/input/stock-market-dataset/stocks/AAME.csv\")\n\n# Extract the input features and output variable\nX = df[['Open', 'High', 'Low', 'Adj Close', 'Volume']].values\ny = df['Close'].values\n\n# Predict the close attribute for the entire dataset\npredicted_close = linear_regression(X, y)\n\n# Plot the predicted values against the actual values\nplt.scatter(y, predicted_close)\nplt.xlabel(\"Actual Close\")\nplt.ylabel(\"Predicted Close\")\nplt.show()\n\n\n","metadata":{"execution":{"iopub.status.busy":"2023-03-03T17:40:44.001802Z","iopub.execute_input":"2023-03-03T17:40:44.002185Z","iopub.status.idle":"2023-03-03T17:40:44.289594Z","shell.execute_reply.started":"2023-03-03T17:40:44.002154Z","shell.execute_reply":"2023-03-03T17:40:44.288195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Load the dataset into a pandas dataframe\ndf = pd.read_csv(\"/kaggle/input/stock-market-dataset/stocks/A.csv\")\n\n# Extract the input features and output variable\nX = df[['Open', 'High', 'Low']]\ny = df['Close']\n\n# Add a column of 1's to X to represent the intercept term\nX = np.c_[np.ones(X.shape[0]), X]\n\n# Calculate the coefficients of the linear regression equation\nbeta_hat = np.linalg.inv(X.T @ X) @ X.T @ y\n\n# Predict the close attribute for the entire dataset\npredicted_close = X @ beta_hat\n\n# Print the coefficients of the linear regression equation\nprint(\"Intercept: \", beta_hat[0])\nfor i in range(1, len(beta_hat)):\n    print(\"Beta\", i, \": \", beta_hat[i])\n\n# Plot the predicted values against the actual values\nplt.scatter(y, predicted_close)\nplt.xlabel(\"Actual Close\")\nplt.ylabel(\"Predicted Close\")\nplt.show()\n\n","metadata":{"execution":{"iopub.status.busy":"2023-03-03T17:52:50.519931Z","iopub.execute_input":"2023-03-03T17:52:50.520379Z","iopub.status.idle":"2023-03-03T17:52:50.772171Z","shell.execute_reply.started":"2023-03-03T17:52:50.520343Z","shell.execute_reply":"2023-03-03T17:52:50.771260Z"},"trusted":true},"execution_count":null,"outputs":[]}]}