Skip to content

Commit

Permalink
Merge pull request #151 from balbirs22/BS
Browse files Browse the repository at this point in the history
Created a Web Page for predicting the stock price and also implemented concept of ensemble learning closes #132
  • Loading branch information
jvedsaqib authored Oct 22, 2024
2 parents 3af071a + 9c252ed commit e48becf
Show file tree
Hide file tree
Showing 10 changed files with 7,541 additions and 583 deletions.
33 changes: 33 additions & 0 deletions Contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,39 @@ If you're introducing new algorithms or modifying existing ones, please update t
## 🧑‍🤝‍🧑 Community
Join the discussion in the [Issues](https://github.com/your-repo/issues) section! Share your ideas, ask questions, and collaborate on exciting features with fellow contributors.

## 🔄 Recent Updates

### Changes in Flask Route for Stock Prediction:
- The route `/predict_close` has been updated to handle both `GET` and `POST` requests.
- **GET** request: Renders the `stock.html` form when the user navigates to the prediction page.
- **POST** request: Processes the stock price prediction based on user input (Open, High, Low, and Volume).

Make sure to follow the updated code structure when adding new routes for similar tasks. The current structure is as follows:

```python
@app.route('/predict_close', methods=['GET', 'POST'])
def predict_close():
if request.method == 'POST':
try:
inputs = [
float(request.form.get('Open')),
float(request.form.get('High')),
float(request.form.get('Low')),
float(request.form.get('Volume'))
]

close_prediction = stock_model.predict(np.array([inputs]))[0] if stock_model else None

save_data(inputs, close_prediction)
retrain_model()

return str(round(close_prediction, 2)) if close_prediction is not None else "Error: Stock model not loaded."
except Exception as e:
return f"An error occurred: {e}"
# For GET request, render the stock.html page
return render_template('stock.html')


## 🎉 Thank You!
Every contribution counts! Whether you’re fixing a bug, improving documentation, or building a new feature, we appreciate your efforts to make this project better.

Expand Down
668 changes: 139 additions & 529 deletions Stock_Price_Prediction(Updated).ipynb

Large diffs are not rendered by default.

7,066 changes: 7,066 additions & 0 deletions Updated_SBIN.csv

Large diffs are not rendered by default.

68 changes: 68 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
from flask import Flask, render_template, request
import numpy as np
import pickle
import os
import pandas as pd
from sklearn.model_selection import train_test_split
import xgboost as xgb

app = Flask(__name__)

models_dir = "Stock-Price-Prediction/prediction.pkl"
data_file = "Stock-Price-Prediction/Updated_SBIN.csv"

df = pd.read_csv(data_file)
print(df.columns)

# Load the model
try:
with open(models_dir, "rb") as stock_file:
stock_model = pickle.load(stock_file)
except FileNotFoundError:
stock_model = None

def save_data(inputs, close_prediction):
new_data = pd.DataFrame([inputs + [close_prediction]], columns=['Open', 'High', 'Low', 'Volume', 'Close'])
with open(data_file, mode='a', newline='') as file:
new_data.to_csv(file, header=False, index=False)

def retrain_model():
X = df[['Open', 'High', 'Low', 'Volume']]
y = df['Close']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

stock_model_xgb = xgb.XGBRegressor(objective='reg:squarederror', random_state=42)
stock_model_xgb.fit(X_train, y_train)

with open(models_dir, "wb") as stock_file_xgb:
pickle.dump(stock_model_xgb, stock_file_xgb)

@app.route('/')
def home():
return render_template('home.html')

@app.route('/predict_close', methods=['GET', 'POST'])
def predict_close():
if request.method == 'POST':
try:
inputs = [
float(request.form.get('Open')),
float(request.form.get('High')),
float(request.form.get('Low')),
float(request.form.get('Volume'))
]

close_prediction = stock_model.predict(np.array([inputs]))[0] if stock_model else None

save_data(inputs, close_prediction)
retrain_model()

return str(round(close_prediction, 2)) if close_prediction is not None else "Error: Stock model not loaded."
except Exception as e:
return f"An error occurred: {e}"
# If it's a GET request, render the stock.html page
return render_template('stock.html')

if __name__ == "__main__":
app.run(debug=True)
Binary file added prediction.pkl
Binary file not shown.
113 changes: 59 additions & 54 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,54 +1,59 @@
absl-py==2.1.0
astunparse==1.6.3
certifi==2024.8.30
charset-normalizer==3.4.0
contourpy==1.3.0
cycler==0.12.1
flatbuffers==24.3.25
fonttools==4.54.1
gast==0.6.0
google-pasta==0.2.0
grpcio==1.66.2
h5py==3.12.1
idna==3.10
joblib==1.4.2
keras==3.6.0
kiwisolver==1.4.7
libclang==18.1.1
Markdown==3.7
markdown-it-py==3.0.0
MarkupSafe==3.0.1
matplotlib==3.9.2
mdurl==0.1.2
ml-dtypes==0.4.1
namex==0.0.8
numpy==1.26.4
opt_einsum==3.4.0
optree==0.13.0
packaging==24.1
pandas==2.2.3
pillow==10.4.0
protobuf==4.25.5
Pygments==2.18.0
pyparsing==3.1.4
python-dateutil==2.9.0.post0
pytz==2024.2
requests==2.32.3
rich==13.9.2
scikit-learn==1.5.2
scipy==1.14.1
seaborn==0.13.2
setuptools==75.1.0
six==1.16.0
statsmodels==0.14.0
tensorboard==2.17.1
tensorboard-data-server==0.7.2
tensorflow==2.17.0
termcolor==2.5.0
threadpoolctl==3.5.0
typing_extensions==4.12.2
tzdata==2024.2
urllib3==2.2.3
Werkzeug==3.0.4
wheel==0.44.0
wrapt==1.16.0

Flask==2.3.2
statsmodels==0.14.0
pickle-mixin==1.0.2
xgboost
absl-py==2.1.0
astunparse==1.6.3
certifi==2024.8.30
charset-normalizer==3.4.0
contourpy==1.3.0
cycler==0.12.1
flatbuffers==24.3.25
fonttools==4.54.1
gast==0.6.0
google-pasta==0.2.0
grpcio==1.66.2
h5py==3.12.1
idna==3.10
joblib==1.4.2
keras==3.6.0
kiwisolver==1.4.7
libclang==18.1.1
Markdown==3.7
markdown-it-py==3.0.0
MarkupSafe==3.0.1
matplotlib==3.9.2
mdurl==0.1.2
ml-dtypes==0.4.1
namex==0.0.8
numpy==1.26.4
opt_einsum==3.4.0
optree==0.13.0
packaging==24.1
pandas==2.2.3
pillow==10.4.0
protobuf==4.25.5
Pygments==2.18.0
pyparsing==3.1.4
python-dateutil==2.9.0.post0
pytz==2024.2
requests==2.32.3
rich==13.9.2
scikit-learn==1.5.2
scipy==1.14.1
seaborn==0.13.2
setuptools==75.1.0
six==1.16.0
statsmodels==0.14.0
tensorboard==2.17.1
tensorboard-data-server==0.7.2
tensorflow==2.17.0
termcolor==2.5.0
threadpoolctl==3.5.0
typing_extensions==4.12.2
tzdata==2024.2
urllib3==2.2.3
Werkzeug==3.0.4
wheel==0.44.0
wrapt==1.16.0
50 changes: 50 additions & 0 deletions static/css/home.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
body {
font-family: 'Arial', sans-serif;
background-color: #f0f8ff; /* Light blue background */
margin: 0;
padding: 20px;
}

.container {
max-width: 600px;
margin: auto;
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
text-align: center;
}

h1 {
color: #003366; /* Dark blue for heading */
font-size: 2.5em;
}

p {
color: #555; /* Dark gray for paragraph */
font-size: 1.2em;
}

nav {
margin-top: 20px;
}

ul {
list-style-type: none;
padding: 0;
}

li {
display: inline;
margin: 0 15px;
}

a {
text-decoration: none;
color: #0066cc; /* Blue link color */
font-weight: bold;
}

a:hover {
color: #004999; /* Darker blue on hover */
}
59 changes: 59 additions & 0 deletions static/css/stock.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
body {
font-family: 'Verdana', sans-serif;
background-color: #f5f5f5; /* Light gray background */
margin: 0;
padding: 20px;
}

.container {
max-width: 600px;
margin: auto;
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

h1 {
color: #ff4500; /* Orange-red for heading */
font-size: 2.5em;
text-align: center;
}

label {
margin-top: 10px;
display: block;
font-weight: bold;
color: #333; /* Dark gray for labels */
}

input[type="text"] {
width: 100%;
padding: 10px;
margin: 5px 0 15px 0;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
background-color: #28a745; /* Green button */
color: white;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
width: 100%; /* Full-width button */
}

button:hover {
background-color: #218838; /* Darker green on hover */
}

.result {
margin-top: 20px;
padding: 10px;
color: white;
background-color: green; /* Green background for success */
border-radius: 4px;
display: none; /* Initially hidden */
}
20 changes: 20 additions & 0 deletions templates/home.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stock Price Predictor</title>
<link rel="stylesheet" href="static/css/home.css"> <!-- Link to your CSS -->
</head>
<body>
<div class="container">
<h1>Welcome to Our Stock Price Predictor</h1>
<p>Use this tool to predict stock prices based on historical data.</p>
<nav>
<ul>
<li><a href="{{ url_for('predict_close') }}">Stock Price Prediction</a></li>
</ul>
</nav>
</div>
</body>
</html>
Loading

0 comments on commit e48becf

Please sign in to comment.