abhi.2000 / app.py
Abhisesh7's picture
Update app.py
9e68217 verified
raw
history blame
3.66 kB
import sys
import pandas as pd
import numpy as np
import tensorflow as tf
import gradio as gr
print(f"Python version: {sys.version}")
print(f"Pandas version: {pd.__version__}")
print(f"Numpy version: {np.__version__}")
print(f"TensorFlow version: {tf.__version__}")
print(f"Gradio version: {gr.__version__}")
import yfinance as yf
import pandas as pd
def fetch_data(ticker, start_date, end_date):
# Fetch historical data for the given ticker symbol
data = yf.download(ticker, start=start_date, end=end_date)
return data
# Example usage
# data = fetch_data("AAPL", "2023-01-01", "2023-10-01")
from sklearn.preprocessing import MinMaxScaler
import numpy as np
def prepare_data(data):
# Preprocessing
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
x_train, y_train = [], []
for i in range(60, len(scaled_data)):
x_train.append(scaled_data[i-60:i, 0])
y_train.append(scaled_data[i, 0])
return np.array(x_train), np.array(y_train), scaler
def create_model(input_shape):
model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(tf.keras.layers.LSTM(units=50, return_sequences=False))
model.add(tf.keras.layers.Dense(units=25))
model.add(tf.keras.layers.Dense(units=1)) # Output layer
model.compile(optimizer='adam', loss='mean_squared_error')
return model
# Example usage
# x_train, y_train, scaler = prepare_data(data)
# model = create_model((x_train.shape[1], 1))
# model.fit(x_train, y_train, batch_size=1, epochs=1)
def predict_next_days(model, last_60_days, scaler):
last_60_days = np.array(last_60_days).reshape(-1, 1)
last_60_days_scaled = scaler.transform(last_60_days)
X_test = []
X_test.append(last_60_days_scaled)
X_test = np.array(X_test)
predicted_price = model.predict(X_test)
predicted_price = scaler.inverse_transform(predicted_price) # Reverse scaling
return predicted_price[0][0]
def stock_prediction(ticker, start_date, end_date):
data = fetch_data(ticker, start_date, end_date)
x_train, y_train, scaler = prepare_data(data)
model = create_model((x_train.shape[1], 1))
model.fit(x_train, y_train, batch_size=1, epochs=1)
# Make predictions
last_60_days = data['Close'].values[-60:]
predicted_price = predict_next_days(model, last_60_days, scaler)
# Calculate percentage change, highest, and lowest
percentage_change = ((data['Close'][-1] - data['Close'][0]) / data['Close'][0]) * 100
highest_value = data['Close'].max()
lowest_value = data['Close'].min()
return {
"Predicted Price": predicted_price,
"Percentage Change": percentage_change,
"Highest Value": highest_value,
"Lowest Value": lowest_value,
}
# UI setup
stock_tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA", "FB", "NFLX", "NVDA", "INTC", "AMD"]
gr.Interface(
fn=stock_prediction,
inputs=[
gr.Dropdown(choices=stock_tickers, label="Stock Ticker"),
gr.Date(label="Start Date"),
gr.Date(label="End Date"),
],
outputs=["json"],
).launch()
import matplotlib.pyplot as plt
def plot_graph(data, predicted_prices):
plt.figure(figsize=(14, 5))
plt.plot(data['Close'], label='Historical Prices', color='blue')
plt.plot(predicted_prices, label='Predicted Prices', color='red')
plt.title('Stock Price Prediction')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.legend()
plt.show()
# Call this function in your `stock_prediction` function to plot the graph