tbdavid2019 commited on
Commit
4d43d0c
1 Parent(s): f3dd761
Files changed (1) hide show
  1. app.py +108 -0
app.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import yfinance as yf
4
+ from sklearn.preprocessing import MinMaxScaler
5
+ from keras.models import Sequential
6
+ from keras.layers import LSTM, Dense, Dropout
7
+ import gradio as gr
8
+ import datetime
9
+
10
+ # Function to fetch stock data
11
+ def get_stock_data(ticker, period):
12
+ data = yf.download(ticker, period=period)
13
+ return data
14
+
15
+ # Function to prepare the data for LSTM
16
+ def prepare_data(data, time_step=60):
17
+ scaler = MinMaxScaler(feature_range=(0, 1))
18
+ scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
19
+
20
+ X, y = [], []
21
+ for i in range(time_step, len(scaled_data)):
22
+ X.append(scaled_data[i-time_step:i, 0])
23
+ y.append(scaled_data[i, 0])
24
+
25
+ X, y = np.array(X), np.array(y)
26
+ X = np.reshape(X, (X.shape[0], X.shape[1], 1))
27
+
28
+ return X, y, scaler
29
+
30
+ # Function to build and train LSTM model
31
+ def train_lstm_model(X_train, y_train):
32
+ model = Sequential()
33
+ model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
34
+ model.add(Dropout(0.2))
35
+ model.add(LSTM(units=50, return_sequences=False))
36
+ model.add(Dropout(0.2))
37
+ model.add(Dense(units=1))
38
+
39
+ model.compile(optimizer='adam', loss='mean_squared_error')
40
+ model.fit(X_train, y_train, epochs=10, batch_size=32)
41
+
42
+ return model
43
+
44
+ # Function to predict stock prices
45
+ def predict_stock(model, data, scaler, time_step=60):
46
+ inputs = scaler.transform(data['Close'].values.reshape(-1, 1))
47
+ X_test = []
48
+ for i in range(time_step, len(inputs)):
49
+ X_test.append(inputs[i-time_step:i, 0])
50
+ X_test = np.array(X_test)
51
+ X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
52
+
53
+ predicted_prices = model.predict(X_test)
54
+ predicted_prices = scaler.inverse_transform(predicted_prices)
55
+
56
+ return predicted_prices
57
+
58
+ # Function to fetch all Taiwan listed stocks
59
+ def get_all_taiwan_stocks():
60
+ # Here you should implement a method to get all Taiwan listed stock tickers
61
+ # This is a placeholder list of tickers for demonstration purposes
62
+ return ["2330.TW", "2317.TW", "2303.TW", "2412.TW", "2454.TW"]
63
+
64
+ # Function to get top 10 potential stocks
65
+ def get_top_10_potential_stocks(period):
66
+ stock_list = get_all_taiwan_stocks()
67
+ stock_predictions = []
68
+
69
+ for ticker in stock_list:
70
+ data = get_stock_data(ticker, period)
71
+ if data.empty:
72
+ continue
73
+
74
+ # Prepare data
75
+ X_train, y_train, scaler = prepare_data(data)
76
+
77
+ # Train model
78
+ model = train_lstm_model(X_train, y_train)
79
+
80
+ # Predict future prices
81
+ predicted_prices = predict_stock(model, data, scaler)
82
+
83
+ # Calculate the potential (e.g., last predicted price vs last actual price)
84
+ potential = (predicted_prices[-1] - data['Close'].values[-1]) / data['Close'].values[-1]
85
+ stock_predictions.append((ticker, potential, data['Close'].values[-1], predicted_prices[-1][0]))
86
+
87
+ # Sort by potential and get top 10
88
+ top_10_stocks = sorted(stock_predictions, key=lambda x: x[1], reverse=True)[:10]
89
+ return top_10_stocks
90
+
91
+ # Gradio interface function
92
+ def stock_prediction_app(period):
93
+ # Get top 10 potential stocks
94
+ top_10_stocks = get_top_10_potential_stocks(period)
95
+
96
+ # Create a dataframe for display
97
+ df = pd.DataFrame(top_10_stocks, columns=["股票代號", "潛力 (百分比)", "現價", "預測價格"])
98
+
99
+ return df
100
+
101
+ # Define Gradio interface
102
+ inputs = [
103
+ gr.inputs.Dropdown(choices=["1mo", "3mo", "6mo", "9mo", "1yr"], label="時間範圍")
104
+ ]
105
+ outputs = gr.outputs.Dataframe(label="潛力股推薦結果")
106
+
107
+ gr.Interface(fn=stock_prediction_app, inputs=inputs, outputs=outputs, title="台股潛力股推薦系統 - LSTM模型")\
108
+ .launch()