predict_stock / app .py
Sonia2k5's picture
Rename app (9).py to app .py
07b0d3b verified
raw
history blame
2.33 kB
# -*- coding: utf-8 -*-
"""app.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1vvN4x-mEuGtdgL2zlzu2ci6sercypfCa
"""
import numpy as np
import pandas as pd
import gradio as gr
from keras.models import Sequential
from keras.layers import SimpleRNN, Dense
from sklearn.preprocessing import MinMaxScaler
# Generate dummy stock price data
def generate_dummy_data():
np.random.seed(0)
time_steps = 100
x = np.linspace(0, 20, time_steps)
prices = 50 + np.sin(x) * 10 + np.random.normal(0, 1, time_steps)
return prices
# Preprocess data
def prepare_data(data, window_size):
X, y = [], []
for i in range(len(data) - window_size):
X.append(data[i:i + window_size])
y.append(data[i + window_size])
return np.array(X), np.array(y)
# Create and train RNN model
def train_model():
raw_prices = generate_dummy_data().reshape(-1, 1)
scaler = MinMaxScaler()
scaled_prices = scaler.fit_transform(raw_prices)
window_size = 5
X, y = prepare_data(scaled_prices, window_size)
X = X.reshape((X.shape[0], X.shape[1], 1))
model = Sequential([
SimpleRNN(50, activation='relu', input_shape=(window_size, 1)),
Dense(1)
])
model.compile(optimizer='adam', loss='mse')
model.fit(X, y, epochs=30, verbose=0)
return model, scaler, window_size
model, scaler, window_size = train_model()
# Prediction function for Gradio
def predict_next_prices(inputs):
inputs = [float(i) for i in inputs.split(',')]
if len(inputs) != window_size:
return f"Please enter {window_size} comma-separated values."
input_array = np.array(inputs).reshape(-1, 1)
scaled_input = scaler.transform(input_array).reshape((1, window_size, 1))
scaled_prediction = model.predict(scaled_input)[0][0]
predicted_price = scaler.inverse_transform([[scaled_prediction]])[0][0]
return f"Predicted Next Price: ₹{predicted_price:.2f}"
# Gradio Interface
demo = gr.Interface(
fn=predict_next_prices,
inputs=gr.Textbox(label=f"Enter last {window_size} stock prices (comma-separated)"),
outputs="text",
title="RNN Stock Price Predictor (Dummy Data)",
description="Enter previous prices to predict the next value."
)
if __name__ == "__main__":
demo.launch()