Update app.py
Browse files
app.py
CHANGED
@@ -1,137 +1,80 @@
|
|
|
|
1 |
import yfinance as yf
|
2 |
-
import pandas as pd
|
3 |
import numpy as np
|
4 |
-
import
|
5 |
-
import gradio as gr
|
6 |
import matplotlib.pyplot as plt
|
7 |
-
from sklearn.
|
8 |
|
9 |
-
# Function to fetch
|
10 |
-
def
|
11 |
stock_data = yf.download(ticker, start=start_date, end=end_date)
|
12 |
-
if stock_data.empty:
|
13 |
-
return None
|
14 |
return stock_data
|
15 |
|
16 |
-
# Function to
|
17 |
-
def
|
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 |
-
model.compile(optimizer='adam', loss='mean_squared_error')
|
47 |
-
return model
|
48 |
-
|
49 |
-
# Function to train the LSTM model
|
50 |
-
def train_model(X_train, y_train):
|
51 |
-
model = build_lstm_model(X_train.shape)
|
52 |
-
model.fit(X_train, y_train, batch_size=1, epochs=1)
|
53 |
-
return model
|
54 |
-
|
55 |
-
# Function to make predictions using the trained model
|
56 |
-
def make_predictions(model, X_test, scaler):
|
57 |
-
predictions = model.predict(X_test)
|
58 |
-
return scaler.inverse_transform(predictions)
|
59 |
-
|
60 |
-
# Function to calculate the metrics (percentage change, highest, lowest, buy/sell)
|
61 |
-
def calculate_metrics(data, predictions):
|
62 |
-
start_value = data['Close'][0]
|
63 |
-
end_value = predictions[-1][0]
|
64 |
-
percentage_change = ((end_value - start_value) / start_value) * 100
|
65 |
-
|
66 |
-
highest_value = data['Close'].max()
|
67 |
-
lowest_value = data['Close'].min()
|
68 |
-
|
69 |
-
decision = "Buy" if end_value > start_value else "Sell"
|
70 |
-
|
71 |
-
return percentage_change, highest_value, lowest_value, decision
|
72 |
-
|
73 |
-
# Function to plot the graph of historical vs predicted data
|
74 |
-
def plot_graph(data, predictions, ticker):
|
75 |
-
plt.figure(figsize=(12, 6))
|
76 |
-
plt.plot(data.index, data['Close'], label="Historical Prices", color='blue')
|
77 |
-
plt.plot(data.index[len(data) - len(predictions):], predictions, label="Predicted Prices", color='red')
|
78 |
-
plt.title(f'{ticker} Stock Price Prediction')
|
79 |
-
plt.xlabel('Date')
|
80 |
-
plt.ylabel('Price (USD)')
|
81 |
plt.legend()
|
82 |
plt.grid(True)
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
gr_interface = gr.Interface(
|
120 |
-
fn=stock_predictor,
|
121 |
-
inputs=[
|
122 |
-
gr.Dropdown(choices=tickers, label="Select Stock Ticker"),
|
123 |
-
gr.inputs.Date(label="Start Date"),
|
124 |
-
gr.inputs.Date(label="End Date")
|
125 |
-
],
|
126 |
-
outputs=[
|
127 |
-
gr.Label(label="Percentage Change"),
|
128 |
-
gr.Label(label="Highest Value"),
|
129 |
-
gr.Label(label="Lowest Value"),
|
130 |
-
gr.Label(label="Prediction (Buy/Sell)"),
|
131 |
-
],
|
132 |
-
title="Stock Prediction App",
|
133 |
-
description="This app predicts stock prices and helps users decide whether to buy or sell."
|
134 |
-
)
|
135 |
-
|
136 |
-
# Launch the Gradio interface
|
137 |
-
gr_interface.launch()
|
|
|
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 |
|
8 |
+
# Function to fetch data
|
9 |
+
def fetch_data(ticker, start_date, end_date):
|
10 |
stock_data = yf.download(ticker, start=start_date, end=end_date)
|
|
|
|
|
11 |
return stock_data
|
12 |
|
13 |
+
# Function to predict future prices
|
14 |
+
def predict_stock(ticker, start_date, end_date):
|
15 |
+
stock_data = fetch_data(ticker, start_date, end_date)
|
16 |
+
|
17 |
+
stock_data['Date'] = pd.to_datetime(stock_data.index)
|
18 |
+
stock_data['Days'] = (stock_data['Date'] - stock_data['Date'].min()).dt.days
|
19 |
+
|
20 |
+
X = stock_data['Days'].values.reshape(-1, 1)
|
21 |
+
y = stock_data['Close'].values
|
22 |
+
|
23 |
+
model = LinearRegression()
|
24 |
+
model.fit(X, y)
|
25 |
+
|
26 |
+
future_days = np.array(range(stock_data['Days'].max() + 1, stock_data['Days'].max() + 90)).reshape(-1, 1)
|
27 |
+
future_prices = model.predict(future_days)
|
28 |
+
|
29 |
+
return future_prices, stock_data
|
30 |
+
|
31 |
+
# Function to visualize stock data
|
32 |
+
def plot_stock_data(ticker, start_date, end_date):
|
33 |
+
future_prices, stock_data = predict_stock(ticker, start_date, end_date)
|
34 |
+
|
35 |
+
plt.figure(figsize=(10, 6))
|
36 |
+
plt.plot(stock_data['Date'], stock_data['Close'], label="Historical Prices")
|
37 |
+
future_dates = pd.date_range(stock_data['Date'].max() + pd.Timedelta(days=1), periods=90)
|
38 |
+
plt.plot(future_dates, future_prices, label="Predicted Future Prices")
|
39 |
+
|
40 |
+
plt.title(f"{ticker} Stock Price Prediction")
|
41 |
+
plt.xlabel("Date")
|
42 |
+
plt.ylabel("Price")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
plt.legend()
|
44 |
plt.grid(True)
|
45 |
+
|
46 |
+
return plt.gcf()
|
47 |
+
|
48 |
+
# Gradio Interface
|
49 |
+
def stock_prediction_interface(ticker, start_date, end_date):
|
50 |
+
stock_data = fetch_data(ticker, start_date, end_date)
|
51 |
+
price_change = (stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0] * 100
|
52 |
+
highest_price = stock_data['High'].max()
|
53 |
+
lowest_price = stock_data['Low'].min()
|
54 |
+
|
55 |
+
future_prices, _ = predict_stock(ticker, start_date, end_date)
|
56 |
+
decision = "Buy" if future_prices[-1] > stock_data['Close'].iloc[-1] else "Sell"
|
57 |
+
|
58 |
+
graph = plot_stock_data(ticker, start_date, end_date)
|
59 |
+
|
60 |
+
return f"Percentage Change: {price_change:.2f}%\nHighest Price: {highest_price}\nLowest Price: {lowest_price}\nDecision: {decision}", graph
|
61 |
+
|
62 |
+
# Gradio app UI
|
63 |
+
ticker_list = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA', 'META', 'NFLX', 'NVDA', 'BABA', 'INTC']
|
64 |
+
|
65 |
+
# Update to use gr.components instead of gr.inputs
|
66 |
+
with gr.Blocks() as demo:
|
67 |
+
ticker_input = gr.components.Dropdown(choices=ticker_list, label="Stock Ticker")
|
68 |
+
start_date_input = gr.components.Date(label="Start Date")
|
69 |
+
end_date_input = gr.components.Date(label="End Date")
|
70 |
+
|
71 |
+
output_text = gr.components.Textbox(label="Prediction Results")
|
72 |
+
output_plot = gr.components.Plot(label="Stock Price Plot")
|
73 |
+
|
74 |
+
gr.components.Button("Predict").click(
|
75 |
+
stock_prediction_interface,
|
76 |
+
inputs=[ticker_input, start_date_input, end_date_input],
|
77 |
+
outputs=[output_text, output_plot]
|
78 |
+
)
|
79 |
+
|
80 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|