File size: 2,327 Bytes
d47d7e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# -*- 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()