Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import yfinance as yf
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 9 |
+
import gradio as gr
|
| 10 |
+
|
| 11 |
+
# Function to get stock data
|
| 12 |
+
def get_stock_data(ticker, start, end):
|
| 13 |
+
data = yf.download(ticker, start=start, end=end)
|
| 14 |
+
return data
|
| 15 |
+
|
| 16 |
+
# Function to process data and make predictions
|
| 17 |
+
def predict_stock(ticker, start, end):
|
| 18 |
+
data = get_stock_data(ticker, start, end)
|
| 19 |
+
|
| 20 |
+
# Scale the data
|
| 21 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 22 |
+
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
|
| 23 |
+
|
| 24 |
+
# Preparing data for LSTM model (last 60 days as input)
|
| 25 |
+
def create_dataset(dataset, time_step=60):
|
| 26 |
+
X, y = [], []
|
| 27 |
+
for i in range(time_step, len(dataset)):
|
| 28 |
+
X.append(dataset[i-time_step:i, 0])
|
| 29 |
+
y.append(dataset[i, 0])
|
| 30 |
+
return np.array(X), np.array(y)
|
| 31 |
+
|
| 32 |
+
# Split the data
|
| 33 |
+
train_size = int(len(scaled_data) * 0.8)
|
| 34 |
+
train_data = scaled_data[0:train_size]
|
| 35 |
+
test_data = scaled_data[train_size:]
|
| 36 |
+
|
| 37 |
+
# Create training and testing datasets
|
| 38 |
+
X_train, y_train = create_dataset(train_data)
|
| 39 |
+
X_test, y_test = create_dataset(test_data)
|
| 40 |
+
|
| 41 |
+
# Reshape for LSTM input
|
| 42 |
+
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
|
| 43 |
+
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
|
| 44 |
+
|
| 45 |
+
# Build LSTM model
|
| 46 |
+
model = tf.keras.Sequential([
|
| 47 |
+
tf.keras.layers.LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)),
|
| 48 |
+
tf.keras.layers.LSTM(50, return_sequences=False),
|
| 49 |
+
tf.keras.layers.Dense(25),
|
| 50 |
+
tf.keras.layers.Dense(1)
|
| 51 |
+
])
|
| 52 |
+
|
| 53 |
+
model.compile(optimizer='adam', loss='mean_squared_error')
|
| 54 |
+
model.fit(X_train, y_train, batch_size=32, epochs=10)
|
| 55 |
+
|
| 56 |
+
# Predict on test data
|
| 57 |
+
predictions = model.predict(X_test)
|
| 58 |
+
predictions = scaler.inverse_transform(predictions)
|
| 59 |
+
|
| 60 |
+
# Calculate buy/sell signal (simple strategy: if predicted > current, buy; else, sell)
|
| 61 |
+
current_price = data['Close'][-1]
|
| 62 |
+
predicted_price = predictions[-1][0]
|
| 63 |
+
buy_sell_signal = "Buy" if predicted_price > current_price else "Sell"
|
| 64 |
+
|
| 65 |
+
# Calculate key statistics
|
| 66 |
+
percentage_change = (current_price - data['Close'][0]) / data['Close'][0] * 100
|
| 67 |
+
highest_value = data['High'].max()
|
| 68 |
+
lowest_value = data['Low'].min()
|
| 69 |
+
|
| 70 |
+
return {
|
| 71 |
+
"prediction": predicted_price,
|
| 72 |
+
"buy_sell_signal": buy_sell_signal,
|
| 73 |
+
"percentage_change": percentage_change,
|
| 74 |
+
"highest_value": highest_value,
|
| 75 |
+
"lowest_value": lowest_value,
|
| 76 |
+
"historical_data": data['Close'].to_list(),
|
| 77 |
+
"predicted_data": predictions.tolist()
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
# Gradio interface
|
| 81 |
+
def predict_interface(ticker, start_date, end_date):
|
| 82 |
+
result = predict_stock(ticker, start_date, end_date)
|
| 83 |
+
return {
|
| 84 |
+
"Buy/Sell Signal": result["buy_sell_signal"],
|
| 85 |
+
"Predicted Value": result["prediction"],
|
| 86 |
+
"Percentage Change": result["percentage_change"],
|
| 87 |
+
"Highest Value": result["highest_value"],
|
| 88 |
+
"Lowest Value": result["lowest_value"],
|
| 89 |
+
"Historical Chart": gr.Plot(plt.plot(result["historical_data"], label="Historical"), plt.plot(result["predicted_data"], label="Predicted"))
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
# Stock tickers for testing
|
| 93 |
+
tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'FB', 'NFLX', 'NVDA', 'BA', 'NKE']
|
| 94 |
+
|
| 95 |
+
# Create Gradio UI
|
| 96 |
+
interface = gr.Interface(
|
| 97 |
+
fn=predict_interface,
|
| 98 |
+
inputs=[
|
| 99 |
+
gr.Dropdown(tickers, label="Stock Ticker"),
|
| 100 |
+
gr.Date(label="Start Date"),
|
| 101 |
+
gr.Date(label="End Date")
|
| 102 |
+
],
|
| 103 |
+
outputs=[
|
| 104 |
+
gr.Textbox(label="Buy/Sell Signal"),
|
| 105 |
+
gr.Textbox(label="Predicted Value"),
|
| 106 |
+
gr.Textbox(label="Percentage Change"),
|
| 107 |
+
gr.Textbox(label="Highest Value"),
|
| 108 |
+
gr.Textbox(label="Lowest Value"),
|
| 109 |
+
gr.Plot(label="Stock Performance")
|
| 110 |
+
],
|
| 111 |
+
title="Stock Prediction App",
|
| 112 |
+
description="Select stock ticker, start date, and end date to predict stock value and get a buy/sell signal."
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
interface.launch()
|