Abhisesh7 commited on
Commit
9e68217
·
verified ·
1 Parent(s): 037848c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -192
app.py CHANGED
@@ -1,204 +1,107 @@
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
2
  import yfinance as yf
3
- import numpy as np
4
  import pandas as pd
5
- import matplotlib.pyplot as plt
6
- from sklearn.linear_model import LinearRegression
7
- import matplotlib
8
- matplotlib.use('Agg') # Use non-interactive backend
9
-
10
- # Date validation function
11
- def validate_date(date_text):
12
- try:
13
- pd.to_datetime(date_text)
14
- return True
15
- except ValueError:
16
- return False
17
 
18
- # Function to fetch data
19
  def fetch_data(ticker, start_date, end_date):
20
- # Validate the dates
21
- if not validate_date(start_date) or not validate_date(end_date):
22
- return "Invalid date format. Please use YYYY-MM-DD.", None
23
-
24
- # Convert input dates from strings to pandas datetime
25
- start_date = pd.to_datetime(start_date)
26
- end_date = pd.to_datetime(end_date)
27
-
28
- stock_data = yf.download(ticker, start=start_date, end=end_date)
29
-
30
- if stock_data.empty:
31
- return f"No data found for ticker {ticker} in the specified date range.", None
32
-
33
- return stock_data
34
-
35
- # Function to predict future prices
36
- def predict_stock(ticker, start_date, end_date):
37
- stock_data = fetch_data(ticker, start_date, end_date)
38
-
39
- if isinstance(stock_data, str): # In case of an error message from fetch_data
40
- return stock_data, None
41
-
42
- stock_data['Date'] = pd.to_datetime(stock_data.index)
43
- stock_data['Days'] = (stock_data['Date'] - stock_data['Date'].min()).dt.days
44
-
45
- X = stock_data['Days'].values.reshape(-1, 1)
46
- y = stock_data['Close'].values
47
-
48
- model = LinearRegression()
49
- model.fit(X, y)
50
-
51
- future_days = np.array(range(stock_data['Days'].max() + 1, stock_data['Days'].max() + 90)).reshape(-1, 1)
52
- future_prices = model.predict(future_days)
53
-
54
- return future_prices, stock_data
55
-
56
- # Function to visualize stock data
57
- def plot_stock_data(ticker, start_date, end_date):
58
- future_prices, stock_data = predict_stock(ticker, start_date, end_date)
59
-
60
- if isinstance(future_prices, str): # In case of an error message
61
- return future_prices
62
-
63
- plt.figure(figsize=(10, 6))
64
- plt.plot(stock_data['Date'], stock_data['Close'], label="Historical Prices")
65
- future_dates = pd.date_range(stock_data['Date'].max() + pd.Timedelta(days=1), periods=90)
66
- plt.plot(future_dates, future_prices, label="Predicted Future Prices")
67
-
68
- plt.title(f"{ticker} Stock Price Prediction")
69
- plt.xlabel("Date")
70
- plt.ylabel("Price")
71
- plt.legend()
72
- plt.grid(True)
73
-
74
- return plt.gcf()
75
-
76
- # Gradio Interface
77
- def stock_prediction_interface(ticker, start_date, end_date):
78
- stock_data = fetch_data(ticker, start_date, end_date)
79
-
80
- if isinstance(stock_data, str): # If there was an error fetching data
81
- return stock_data, None
82
-
83
- price_change = (stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0] * 100
84
- highest_price = stock_data['High'].max()
85
- lowest_price = stock_data['Low'].min()
86
-
87
- future_prices, _ = predict_stock(ticker, start_date, end_date)
88
-
89
- if isinstance(future_prices, str): # If there was an error in prediction
90
- return future_prices, None
91
-
92
- decision = "Buy" if future_prices[-1] > stock_data['Close'].iloc[-1] else "Sell"
93
-
94
- graph = plot_stock_data(ticker, start_date, end_date)
95
-
96
- if isinstance(graph, str): # If there was an error in plotting
97
- return graph, None
98
-
99
- return f"Percentage Change: {price_change:.2f}%\nHighest Price: {highest_price}\nLowest Price: {lowest_price}\nDecision: {decision}", graph
100
-
101
- # Gradio app UI
102
- ticker_list = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA', 'META', 'NFLX', 'NVDA', 'BABA', 'INTC']
103
 
104
- # Use Textbox for date input since Gradio doesn't have a Date component anymore
105
- with gr.Blocks() as demo:
106
- ticker_input = gr.components.Dropdown(choices=ticker_list, label="Stock Ticker")
107
- start_date_input = gr.components.Textbox(label="Start Date (YYYY-MM-DD)", placeholder="e.g. 2023-01-01")
108
- end_date_input = gr.components.Textbox(label="End Date (YYYY-MM-DD)", placeholder="e.g. 2023-12-31")
109
-
110
- output_text = gr.components.Textbox(label="Prediction Results")
111
- output_plot = gr.components.Plot(label="Stock Price Plot")
112
-
113
- gr.components.Button("Predict").click(
114
- stock_prediction_interface,
115
- inputs=[ticker_input, start_date_input, end_date_input],
116
- outputs=[output_text, output_plot]
117
- )
118
 
119
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  import matplotlib.pyplot as plt
121
 
122
- def plot_stock_data(ticker, start_date, end_date):
123
- # Existing code to fetch stock data and make predictions...
124
- stock_data = fetch_data(ticker, start_date, end_date)
125
-
126
- # Assuming you have future_dates and future_prices from your model
127
- future_dates = pd.date_range(end_date, periods=90, freq='D') # Example for future dates
128
- future_prices = model_predict(stock_data) # Example for predicted prices
129
-
130
- # Check lengths of future_dates and future_prices
131
- print(f"Length of future_dates: {len(future_dates)}")
132
- print(f"Length of future_prices: {len(future_prices)}")
133
-
134
- # Ensure they are the same length
135
- min_length = min(len(future_dates), len(future_prices))
136
- future_dates = future_dates[:min_length]
137
- future_prices = future_prices[:min_length]
138
-
139
- # Plot historical stock data
140
- plt.figure(figsize=(10, 5))
141
- plt.plot(stock_data.index, stock_data['Close'], label="Historical Prices")
142
-
143
- # Plot future predicted prices
144
- plt.plot(future_dates, future_prices, label="Predicted Future Prices", linestyle='--')
145
-
146
- plt.xlabel("Date")
147
- plt.ylabel("Stock Price")
148
- plt.title(f"{ticker} Stock Price Prediction")
149
  plt.legend()
150
- plt.grid(True)
151
-
152
  plt.show()
153
- return plt.gcf() # Return the current figure object
154
- import matplotlib.pyplot as plt
155
- import pandas as pd
156
-
157
- def plot_stock_data(ticker, start_date, end_date):
158
- # Fetch stock data and make predictions...
159
- stock_data = fetch_data(ticker, start_date, end_date)
160
-
161
- # Example future dates (change this according to your actual future date range logic)
162
- future_dates = pd.date_range(end_date, periods=90, freq='D') # Generates 90 future dates
163
- future_prices = model_predict(stock_data) # Generates 89 future prices (example)
164
-
165
- # Ensure both future_dates and future_prices have the same length
166
- min_length = min(len(future_dates), len(future_prices))
167
- future_dates = future_dates[:min_length]
168
- future_prices = future_prices[:min_length]
169
-
170
- # Plot historical stock data
171
- plt.figure(figsize=(10, 5))
172
- plt.plot(stock_data.index, stock_data['Close'], label="Historical Prices")
173
-
174
- # Plot future predicted prices
175
- plt.plot(future_dates, future_prices, label="Predicted Future Prices", linestyle='--')
176
-
177
- # Add labels and title
178
- plt.xlabel("Date")
179
- plt.ylabel("Stock Price")
180
- plt.title(f"{ticker} Stock Price Prediction")
181
- plt.legend()
182
- plt.grid(True)
183
-
184
- # Show the plot
185
- plt.show()
186
-
187
- return plt.gcf() # Return the current figure object for Gradio to display
188
- print(f"Future dates length: {len(future_dates)}")
189
- print(f"Future prices length: {len(future_prices)}")
190
- def plot_stock_data(ticker, start_date, end_date):
191
- # Your existing code to fetch data and make predictions...
192
-
193
- # Check lengths of future_dates and future_prices
194
- print(f"Future dates length: {len(future_dates)}")
195
- print(f"Future prices length: {len(future_prices)}")
196
-
197
- # Ensure they match
198
- if len(future_dates) != len(future_prices):
199
- raise ValueError("The length of future_dates and future_prices must match.")
200
-
201
- plt.plot(future_dates, future_prices, label="Predicted Future Prices")
202
- # Additional plotting code...
203
-
204
 
 
 
1
+ import sys
2
+ import pandas as pd
3
+ import numpy as np
4
+ import tensorflow as tf
5
  import gradio as gr
6
+
7
+ print(f"Python version: {sys.version}")
8
+ print(f"Pandas version: {pd.__version__}")
9
+ print(f"Numpy version: {np.__version__}")
10
+ print(f"TensorFlow version: {tf.__version__}")
11
+ print(f"Gradio version: {gr.__version__}")
12
  import yfinance as yf
 
13
  import pandas as pd
 
 
 
 
 
 
 
 
 
 
 
 
14
 
 
15
  def fetch_data(ticker, start_date, end_date):
16
+ # Fetch historical data for the given ticker symbol
17
+ data = yf.download(ticker, start=start_date, end=end_date)
18
+ return data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # Example usage
21
+ # data = fetch_data("AAPL", "2023-01-01", "2023-10-01")
22
+ from sklearn.preprocessing import MinMaxScaler
23
+ import numpy as np
 
 
 
 
 
 
 
 
 
 
24
 
25
+ def prepare_data(data):
26
+ # Preprocessing
27
+ scaler = MinMaxScaler(feature_range=(0, 1))
28
+ scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
29
+
30
+ x_train, y_train = [], []
31
+ for i in range(60, len(scaled_data)):
32
+ x_train.append(scaled_data[i-60:i, 0])
33
+ y_train.append(scaled_data[i, 0])
34
+
35
+ return np.array(x_train), np.array(y_train), scaler
36
+
37
+ def create_model(input_shape):
38
+ model = tf.keras.Sequential()
39
+ model.add(tf.keras.layers.LSTM(units=50, return_sequences=True, input_shape=input_shape))
40
+ model.add(tf.keras.layers.LSTM(units=50, return_sequences=False))
41
+ model.add(tf.keras.layers.Dense(units=25))
42
+ model.add(tf.keras.layers.Dense(units=1)) # Output layer
43
+ model.compile(optimizer='adam', loss='mean_squared_error')
44
+ return model
45
+
46
+ # Example usage
47
+ # x_train, y_train, scaler = prepare_data(data)
48
+ # model = create_model((x_train.shape[1], 1))
49
+ # model.fit(x_train, y_train, batch_size=1, epochs=1)
50
+ def predict_next_days(model, last_60_days, scaler):
51
+ last_60_days = np.array(last_60_days).reshape(-1, 1)
52
+ last_60_days_scaled = scaler.transform(last_60_days)
53
+
54
+ X_test = []
55
+ X_test.append(last_60_days_scaled)
56
+ X_test = np.array(X_test)
57
+
58
+ predicted_price = model.predict(X_test)
59
+ predicted_price = scaler.inverse_transform(predicted_price) # Reverse scaling
60
+ return predicted_price[0][0]
61
+ def stock_prediction(ticker, start_date, end_date):
62
+ data = fetch_data(ticker, start_date, end_date)
63
+ x_train, y_train, scaler = prepare_data(data)
64
+ model = create_model((x_train.shape[1], 1))
65
+ model.fit(x_train, y_train, batch_size=1, epochs=1)
66
+
67
+ # Make predictions
68
+ last_60_days = data['Close'].values[-60:]
69
+ predicted_price = predict_next_days(model, last_60_days, scaler)
70
+
71
+ # Calculate percentage change, highest, and lowest
72
+ percentage_change = ((data['Close'][-1] - data['Close'][0]) / data['Close'][0]) * 100
73
+ highest_value = data['Close'].max()
74
+ lowest_value = data['Close'].min()
75
+
76
+ return {
77
+ "Predicted Price": predicted_price,
78
+ "Percentage Change": percentage_change,
79
+ "Highest Value": highest_value,
80
+ "Lowest Value": lowest_value,
81
+ }
82
+
83
+ # UI setup
84
+ stock_tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA", "FB", "NFLX", "NVDA", "INTC", "AMD"]
85
+
86
+ gr.Interface(
87
+ fn=stock_prediction,
88
+ inputs=[
89
+ gr.Dropdown(choices=stock_tickers, label="Stock Ticker"),
90
+ gr.Date(label="Start Date"),
91
+ gr.Date(label="End Date"),
92
+ ],
93
+ outputs=["json"],
94
+ ).launch()
95
  import matplotlib.pyplot as plt
96
 
97
+ def plot_graph(data, predicted_prices):
98
+ plt.figure(figsize=(14, 5))
99
+ plt.plot(data['Close'], label='Historical Prices', color='blue')
100
+ plt.plot(predicted_prices, label='Predicted Prices', color='red')
101
+ plt.title('Stock Price Prediction')
102
+ plt.xlabel('Date')
103
+ plt.ylabel('Stock Price')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  plt.legend()
 
 
105
  plt.show()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
+ # Call this function in your `stock_prediction` function to plot the graph