forked from ayush-that/FinVeda
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
FEATURE: Implement Machine Learning Models for Financial Trend and St…
…ock Price Prediction Fixes ayush-that#3209
- Loading branch information
1 parent
8261122
commit fd6699c
Showing
7 changed files
with
126 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# Initialize the stock price prediction package | ||
|
||
# Import necessary functions for ease of access | ||
from .data_preprocessing import fetch_stock_data, preprocess_data | ||
from .lstm_model import build_lstm_model | ||
from .train_model import train_model | ||
from .evaluate_model import evaluate_model | ||
from .flask_api import app # Importing Flask app for API exposure | ||
|
||
# You can also add other modules or utilities as needed |
33 changes: 33 additions & 0 deletions
33
Finveda/models/stock_price_prediction/data_preprocessing.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import pandas as pd | ||
import numpy as np | ||
from sklearn.preprocessing import MinMaxScaler | ||
import yfinance as yf | ||
|
||
# Fetching historical stock data | ||
def fetch_stock_data(ticker, start_date='2010-01-01', end_date='2024-01-01'): | ||
data = yf.download(ticker, start=start_date, end=end_date) | ||
return data | ||
|
||
# Feature engineering and preprocessing | ||
def preprocess_data(df): | ||
# Keep only relevant columns: 'Date', 'Close' (you can add more features like 'Open', 'Volume' etc.) | ||
df = df[['Close']] | ||
|
||
# Normalize the data using MinMaxScaler | ||
scaler = MinMaxScaler(feature_range=(0, 1)) | ||
df_scaled = scaler.fit_transform(df) | ||
|
||
# Create a dataset with 'X' as previous n-day stock prices and 'y' as next day price | ||
def create_dataset(data, time_step=60): | ||
X, y = [], [] | ||
for i in range(len(data) - time_step - 1): | ||
X.append(data[i:(i + time_step), 0]) | ||
y.append(data[i + time_step, 0]) | ||
return np.array(X), np.array(y) | ||
|
||
X, y = create_dataset(df_scaled) | ||
|
||
# Reshaping X for LSTM (samples, time steps, features) | ||
X = X.reshape(X.shape[0], X.shape[1], 1) | ||
|
||
return X, y, scaler |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
# Evaluate the model using test data | ||
def evaluate_model(model, X_test, y_test, scaler): | ||
predicted_stock_price = model.predict(X_test) | ||
|
||
# Rescale the predictions and actual values back to the original scale | ||
predicted_stock_price = scaler.inverse_transform(predicted_stock_price) | ||
y_test_rescaled = scaler.inverse_transform(y_test.reshape(-1, 1)) | ||
|
||
# Calculate the Mean Squared Error (MSE) | ||
mse = np.mean(np.square(predicted_stock_price - y_test_rescaled)) | ||
|
||
return mse, predicted_stock_price, y_test_rescaled |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
from flask import Flask, request, jsonify | ||
from models.stock_price_prediction.data_preprocessing import fetch_stock_data, preprocess_data | ||
from models.stock_price_prediction.lstm_model import build_lstm_model | ||
|
||
# Initialize Flask app | ||
app = Flask(__name__) | ||
|
||
# Load the trained model | ||
model = build_lstm_model((60, 1)) # Ensure the model is built | ||
model.load_weights('models/stock_price_prediction/model_weights.h5') # Load saved model weights | ||
|
||
# API endpoint for stock price prediction | ||
@app.route('/predict', methods=['POST']) | ||
def predict_stock(): | ||
# Extract data from request (e.g., stock ticker symbol) | ||
ticker = request.json['ticker'] | ||
|
||
# Fetch and preprocess the stock data | ||
data = fetch_stock_data(ticker) | ||
X, y, scaler = preprocess_data(data) | ||
|
||
# Predict the stock price using the LSTM model | ||
prediction = model.predict(X[-1].reshape(1, X.shape[1], 1)) | ||
prediction = scaler.inverse_transform(prediction) | ||
|
||
# Return the prediction as a JSON response | ||
return jsonify({'predicted_stock_price': prediction[0][0]}) | ||
|
||
# Run the app | ||
if __name__ == "__main__": | ||
app.run(debug=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import tensorflow as tf | ||
from tensorflow.keras.models import Sequential | ||
from tensorflow.keras.layers import LSTM, Dense, Dropout | ||
|
||
# Build and compile the LSTM model | ||
def build_lstm_model(input_shape): | ||
model = Sequential() | ||
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape)) | ||
model.add(Dropout(0.2)) | ||
model.add(LSTM(units=50, return_sequences=False)) | ||
model.add(Dropout(0.2)) | ||
model.add(Dense(units=1)) # Output layer for stock price prediction | ||
|
||
model.compile(optimizer='adam', loss='mean_squared_error') | ||
return model |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
# Train the LSTM model | ||
def train_model(model, X_train, y_train, epochs=10, batch_size=32): | ||
model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size) | ||
return model |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
// Function to call the Flask API and get stock price prediction | ||
async function getStockPrediction(ticker) { | ||
const response = await fetch('http://localhost:5000/predict', { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ ticker: ticker }) | ||
}); | ||
|
||
const data = await response.json(); | ||
console.log('Predicted Stock Price:', data.predicted_stock_price); | ||
// Display the predicted stock price on the website | ||
document.getElementById('stockPrediction').innerText = `Predicted Stock Price: $${data.predicted_stock_price}`; | ||
} | ||
|
||
// Example usage: Trigger prediction when the user enters a stock symbol | ||
document.getElementById('predictButton').addEventListener('click', () => { | ||
const ticker = document.getElementById('stockTicker').value; | ||
getStockPrediction(ticker); | ||
}); |