Arkm20 commited on
Commit
265e86e
1 Parent(s): 4f8a53f

Add application file

Browse files
Files changed (1) hide show
  1. app.py +78 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.linear_model import LinearRegression
6
+ from datetime import datetime, timedelta
7
+ import matplotlib.pyplot as plt
8
+
9
+ def get_stock_data(ticker):
10
+ today = datetime.today().strftime('%Y-%m-%d')
11
+ year_ago = (datetime.today() - timedelta(days=365)).strftime('%Y-%m-%d')
12
+ stock_data = yf.download(ticker, start=year_ago, end=today)
13
+ return stock_data
14
+
15
+ def preprocess_data(data):
16
+ data['Date'] = pd.to_datetime(data.index)
17
+ data['Date_ordinal'] = data['Date'].map(datetime.toordinal)
18
+ return data[['Date_ordinal', 'Close']]
19
+
20
+ def train_model(data):
21
+ X = data[['Date_ordinal']]
22
+ y = data['Close']
23
+
24
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
25
+
26
+ model = LinearRegression()
27
+ model.fit(X_train, y_train)
28
+
29
+ return model
30
+
31
+ def predict_price(model, date):
32
+ date_ordinal = datetime.toordinal(pd.to_datetime(date))
33
+ date_df = pd.DataFrame([[date_ordinal]], columns=['Date_ordinal'])
34
+ prediction = model.predict(date_df)
35
+ return prediction[0]
36
+
37
+ def plot_prediction(stock_data, ticker, prediction_date, predicted_price):
38
+ plt.figure(figsize=(12, 6))
39
+ plt.plot(stock_data.index, stock_data['Close'], label='Historical Data')
40
+ plt.scatter(prediction_date, predicted_price, color='red', label='Prediction')
41
+ plt.title(f'{ticker} Stock Price Prediction')
42
+ plt.xlabel('Date')
43
+ plt.ylabel('Price')
44
+ plt.legend()
45
+ plt.grid(True)
46
+ plt.savefig('prediction_plot.png')
47
+ return 'prediction_plot.png'
48
+
49
+ def predict_stock(ticker, date):
50
+ stock_data = get_stock_data(ticker)
51
+
52
+ if stock_data.empty:
53
+ return "No data found for the given ticker.", None
54
+
55
+ latest_price = stock_data['Close'].iloc[-1]
56
+
57
+ processed_data = preprocess_data(stock_data)
58
+ model = train_model(processed_data)
59
+
60
+ try:
61
+ predicted_price = predict_price(model, date)
62
+ plot_path = plot_prediction(stock_data, ticker, pd.to_datetime(date), predicted_price)
63
+ return f"The predicted closing price for {ticker} on {date} is: ${predicted_price:.2f}", plot_path
64
+ except ValueError:
65
+ return "Invalid date format. Please enter the date in YYYY-MM-DD format.", None
66
+
67
+ # Gradio app interface
68
+
69
+ inputs = [
70
+ gr.Textbox(label="Enter the stock ticker"),
71
+ gr.Textbox(label="Enter the date (YYYY-MM-DD) for the prediction")
72
+ ]
73
+ outputs = [
74
+ gr.Text(label="Prediction"),
75
+ gr.Image(label="Prediction Plot")
76
+ ]
77
+
78
+ gr.Interface(fn=predict_stock, inputs=inputs, outputs=outputs, title="Stock Price Prediction").launch(share=True)