Spaces:
Sleeping
Sleeping
# -*- coding: utf-8 -*- | |
"""stockpriceprediction_RNN.ipynb | |
Automatically generated by Colab. | |
Original file is located at | |
https://colab.research.google.com/drive/1WNG8vH1hyyxmR3_BEtT9-c0Golei-f4d | |
""" | |
import numpy as np | |
import tensorflow as tf | |
from tensorflow.keras.models import Sequential | |
from tensorflow.keras.layers import SimpleRNN, Dense | |
import gradio as gr | |
# 1. Generate dummy data | |
def generate_dummy_data(): | |
x = np.linspace(0, 100, 500) | |
y = np.sin(x / 5) + np.random.normal(scale=0.1, size=len(x)) | |
return y | |
data = generate_dummy_data() | |
# 2. Prepare dataset (with time_steps = 5) | |
def create_dataset(data, time_steps=5): # π changed from 10 to 5 | |
X, y = [], [] | |
for i in range(len(data) - time_steps): | |
X.append(data[i:i + time_steps]) | |
y.append(data[i + time_steps]) | |
return np.array(X), np.array(y) | |
X, y = create_dataset(data) | |
X = X.reshape((X.shape[0], X.shape[1], 1)) | |
# 3. Build model for input shape (5, 1) | |
model = Sequential([ | |
SimpleRNN(50, activation='relu', input_shape=(5, 1)), # π changed from (10, 1) to (5, 1) | |
Dense(1) | |
]) | |
model.compile(optimizer='adam', loss='mse') | |
model.fit(X, y, epochs=10, verbose=0) | |
import pickle | |
with open('stock.pkl', 'wb') as file: | |
pickle.dump(model,file) | |
with open('stock.pkl', 'rb') as f: | |
loaded_model = pickle.load(f) | |
# 4. Predict function | |
def predict_next_price(seq): | |
try: | |
seq = [float(i.strip()) for i in seq.split(',')] | |
if len(seq) != 5: # π only 5 numbers expected now | |
return "Please enter exactly 5 numbers." | |
input_seq = np.array(seq).reshape((1, 5, 1)) # π reshape accordingly | |
pred = model.predict(input_seq) | |
return f"π Predicted next price: {pred[0][0]:.4f}" | |
except Exception as e: | |
return f"Error: {str(e)}" | |
# 5. Gradio UI | |
iface = gr.Interface( | |
fn=predict_next_price, | |
inputs=gr.Textbox(lines=2, placeholder="Enter 5 stock prices, comma-separated"), | |
outputs="text", | |
title="π Stock Price Predictor (RNN)", | |
description="Enter 5 stock prices to predict the next one." | |
) | |
iface.launch() |