NishatMahi's picture
Rename app_Synthsis.py to app.py
5efcf12 verified
import gradio as gr
import numpy as np
import pandas as pd
from tensorflow.keras.models import load_model
import joblib
import yfinance as yf
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
try:
lstm_model = load_model('lstm_googl_stock_model.h5')
scaler = joblib.load('scaler.pkl')
except Exception as e:
print(f"Error: {e}")
def predict_stock_price(ticker, days_ahead=30):
try:
end_date = datetime.now()
start_date = end_date - timedelta(days=365)
df = yf.download(ticker, start=start_date, end=end_date, progress=False)
if df.empty or len(df) < 60:
return "Error: Insufficient data", None
data = df[['Close']].values
scaled_data = scaler.transform(data)
lookback = 60
predictions = []
current_sequence = scaled_data[-lookback:].reshape(lookback, 1)
for _ in range(days_ahead):
pred_scaled = lstm_model.predict(current_sequence.reshape(1, lookback, 1), verbose=0)
predictions.append(pred_scaled[0, 0])
current_sequence = np.append(current_sequence[1:], pred_scaled).reshape(lookback, 1)
predictions_array = np.array(predictions).reshape(-1, 1)
predictions_actual = scaler.inverse_transform(predictions_array)
future_dates = pd.date_range(start=end_date + timedelta(days=1), periods=days_ahead)
results = pd.DataFrame({'Date': future_dates.strftime('%Y-%m-%d'), 'Predicted Price': predictions_actual.flatten().round(2)})
last_price = data[-1][0]
avg_prediction = predictions_actual.mean()
change_pct = ((avg_prediction - last_price) / last_price * 100)
summary = f"Stock: {ticker}\nCurrent: ${last_price:.2f}\nPredicted: ${avg_prediction:.2f}\nChange: {change_pct:+.2f}%"
return summary, results
except Exception as e:
return f"Error: {e}", None
with gr.Blocks() as demo:
gr.Markdown("# Stock Price Forecasting")
with gr.Row():
with gr.Column():
ticker_input = gr.Textbox(label="Stock Ticker", value="GOOGL")
days_slider = gr.Slider(1, 90, 30, label="Days")
predict_btn = gr.Button("Predict")
with gr.Column():
summary_output = gr.Textbox(label="Summary", lines=5)
table_output = gr.Dataframe(label="Predictions")
predict_btn.click(predict_stock_price, [ticker_input, days_slider], [summary_output, table_output])
if __name__ == "__main__":
demo.launch()