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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
是一種「黑箱」方法,您這邊的程式碼只需要提供原始數據,而不用管模型內部用了哪些特徵,所有複雜的處理都由另一端完成。這是一個很好的軟體設計概念,可以讓您的程式碼更乾淨、更具彈性。
|
| 2 |
+
|
| 3 |
+
要實現這個目標,最好的做法是將所有與模型相關的程式碼(載入模型、選擇特徵、正規化、預測)都封裝在一個獨立的 Python 檔案中。我會提供兩個檔案的程式碼範例:
|
| 4 |
+
|
| 5 |
+
model_predictor.py:這個檔案由您的組員或您來維護,它包含了所有模型預測的邏輯。
|
| 6 |
+
|
| 7 |
+
HUGING_FACE_V1.0.py:您的主程式,它只需要簡單地匯入 model_predictor.py 中的函式並使用即可。
|
| 8 |
+
|
| 9 |
+
第一步:建立 model_predictor.py
|
| 10 |
+
這個檔案假設模型是您的組員訓練的,並且他們知道模型需要哪些特徵。您可以請他們將這個檔案的內容替換成他們實際的模型和資料處理邏輯。
|
| 11 |
+
|
| 12 |
+
這個範例假設模型需要 Close 和 Volume 這兩個特徵,並需要 60 天的歷史數據。
|
| 13 |
+
|
| 14 |
+
請將以下程式碼儲存為一個新檔案,命名為 model_predictor.py:
|
| 15 |
+
|
| 16 |
+
Python
|
| 17 |
+
|
| 18 |
+
import tensorflow as tf
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pandas as pd
|
| 21 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 22 |
+
|
| 23 |
+
# 這個函式將所有模型相關的邏輯封裝起來
|
| 24 |
+
def predict_with_lstm_model(df_historical):
|
| 25 |
+
"""
|
| 26 |
+
使用預訓練的 LSTM 模型對歷史數據進行預測。
|
| 27 |
+
|
| 28 |
+
參數:
|
| 29 |
+
df_historical (pd.DataFrame): 包含歷史股價數據的 DataFrame。
|
| 30 |
+
|
| 31 |
+
回傳:
|
| 32 |
+
tuple: (預測值, 狀態訊息)
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
# === 這段程式碼由您的組員提供和維護,您不需要修改 ===
|
| 36 |
+
|
| 37 |
+
# 這裡定義模型所需的特徵。請您的組員根據實際訓練模型時使用的特徵來修改這裡。
|
| 38 |
+
features_to_use = ['Close', 'Volume']
|
| 39 |
+
sequence_length = 60 # 模型需要60天的歷史數據
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
# 1. 確保數據包含所有所需特徵
|
| 43 |
+
if not all(feature in df_historical.columns for feature in features_to_use):
|
| 44 |
+
missing_features = [f for f in features_to_use if f not in df_historical.columns]
|
| 45 |
+
return None, f"原始數據中缺少模型所需特徵: {', '.join(missing_features)}。"
|
| 46 |
+
|
| 47 |
+
# 2. 準備輸入數據
|
| 48 |
+
if len(df_historical) < sequence_length:
|
| 49 |
+
return None, "數據長度不足以進行預測。"
|
| 50 |
+
|
| 51 |
+
df_predict_input = df_historical[features_to_use].tail(sequence_length)
|
| 52 |
+
data_to_predict = df_predict_input.values
|
| 53 |
+
|
| 54 |
+
# 3. 正規化數據(假設訓練時使用 MinMaxScaler)
|
| 55 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 56 |
+
scaled_data = scaler.fit_transform(data_to_predict)
|
| 57 |
+
|
| 58 |
+
# 4. 重塑為模型期望的形狀:[樣本數, 序列長度, 特徵數]
|
| 59 |
+
X_test = np.reshape(scaled_data, (1, scaled_data.shape[0], scaled_data.shape[1]))
|
| 60 |
+
|
| 61 |
+
# 5. 載入模型
|
| 62 |
+
model = tf.keras.models.load_model('stock_lstm_model_v2.keras')
|
| 63 |
+
|
| 64 |
+
# 6. 進行預測
|
| 65 |
+
predicted_scaled = model.predict(X_test, verbose=0)
|
| 66 |
+
|
| 67 |
+
# 7. 反正規化,將預測結果轉換回原始價格範圍
|
| 68 |
+
dummy_array = np.zeros(shape=(1, len(features_to_use)))
|
| 69 |
+
dummy_array[0, 0] = predicted_scaled[0, 0]
|
| 70 |
+
prediction = scaler.inverse_transform(dummy_array)[0, 0]
|
| 71 |
+
|
| 72 |
+
return prediction, f"台指期模型預測下一個交易日收盤價為:{prediction:.2f}點。"
|
| 73 |
+
|
| 74 |
+
except Exception as e:
|
| 75 |
+
print(f"載入或預測模型時發生錯誤: {e}")
|
| 76 |
+
return None, "模型載入或預測失敗,請檢查模型檔案或輸入資料。"
|
| 77 |
+
|
| 78 |
+
第二步:修改您的 HUGING_FACE_V1.0.py
|
| 79 |
+
現在,您的主程式將變得非常簡潔。您只需要在開頭匯入 predict_with_lstm_model 函式,並在適當的回調函式中呼叫它即可。
|
| 80 |
+
|
| 81 |
+
請用以下程式碼替換您的 HUGING_FACE_V1.0.py 內容:
|
| 82 |
+
|
| 83 |
+
Python
|
| 84 |
+
|
| 85 |
+
# 系統套件
|
| 86 |
+
import os
|
| 87 |
+
from datetime import datetime, timedelta
|
| 88 |
+
|
| 89 |
+
# 數據處理
|
| 90 |
+
import pandas as pd
|
| 91 |
+
import numpy as np
|
| 92 |
+
import yfinance as yf
|
| 93 |
+
|
| 94 |
+
# Dash & Plotly
|
| 95 |
+
from dash import Dash, dcc, html, callback, Input, Output
|
| 96 |
+
import dash
|
| 97 |
+
import plotly.express as px
|
| 98 |
+
import plotly.graph_objects as go
|
| 99 |
+
from plotly.subplots import make_subplots
|
| 100 |
+
|
| 101 |
+
# === 匯入您組員提供的模型預測函式 ===
|
| 102 |
+
from model_predictor import predict_with_lstm_model
|
| 103 |
+
|
| 104 |
+
# 台股代號對應表 (移除台指期,因為它現在是獨立區塊)
|
| 105 |
+
TAIWAN_STOCKS = {
|
| 106 |
+
'台積電': '2330.TW',
|
| 107 |
+
'聯發科': '2454.TW',
|
| 108 |
+
'鴻海': '2317.TW',
|
| 109 |
+
'台塑': '1301.TW',
|
| 110 |
+
'中華電': '2412.TW',
|
| 111 |
+
'富邦金': '2881.TW',
|
| 112 |
+
'國泰金': '2882.TW',
|
| 113 |
+
'台達電': '2308.TW',
|
| 114 |
+
'統一': '1216.TW',
|
| 115 |
+
'日月光': '2311.TW',
|
| 116 |
+
'長榮': '2306.TW',
|
| 117 |
+
'慧洋-KY': '2637.TW',
|
| 118 |
+
'上銀': '2049.TW',
|
| 119 |
+
'台泥': '1101.TW',
|
| 120 |
+
'譜瑞-KY': '4966.TW',
|
| 121 |
+
'貿聯-KY': '3665.TW'
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
# 產業分類
|
| 125 |
+
INDUSTRY_MAPPING = {
|
| 126 |
+
'2330.TW': '半導體',
|
| 127 |
+
'2454.TW': '半導體',
|
| 128 |
+
'2317.TW': '電子',
|
| 129 |
+
'1301.TW': '塑化',
|
| 130 |
+
'2412.TW': '通訊',
|
| 131 |
+
'2881.TW': '金融',
|
| 132 |
+
'2882.TW': '金融',
|
| 133 |
+
'2308.TW': '電子',
|
| 134 |
+
'1216.TW': '食品',
|
| 135 |
+
'2311.TW': '半導體',
|
| 136 |
+
'2306.TW': '航運',
|
| 137 |
+
'2637.TW': '航運',
|
| 138 |
+
'2049.TW': '機械',
|
| 139 |
+
'1101.TW': '水泥',
|
| 140 |
+
'4966.TW': '半導體',
|
| 141 |
+
'3665.TW': '電子'
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
# 輔助函式: 獲取股價數據
|
| 145 |
+
def get_stock_data(symbol, start, end):
|
| 146 |
+
try:
|
| 147 |
+
df = yf.download(symbol, start=start, end=end)
|
| 148 |
+
return df
|
| 149 |
+
except Exception as e:
|
| 150 |
+
print(f"下載數據時發生錯誤: {e}")
|
| 151 |
+
return pd.DataFrame()
|
| 152 |
+
|
| 153 |
+
# 輔助函式: 計算技術指標
|
| 154 |
+
def calculate_technical_indicators(df):
|
| 155 |
+
df['MA5'] = df['Close'].rolling(window=5).mean()
|
| 156 |
+
df['MA20'] = df['Close'].rolling(window=20).mean()
|
| 157 |
+
delta = df['Close'].diff()
|
| 158 |
+
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
|
| 159 |
+
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
|
| 160 |
+
rs = gain / loss
|
| 161 |
+
df['RSI'] = 100 - (100 / (1 + rs))
|
| 162 |
+
ema12 = df['Close'].ewm(span=12, adjust=False).mean()
|
| 163 |
+
ema26 = df['Close'].ewm(span=26, adjust=False).mean()
|
| 164 |
+
df['MACD'] = ema12 - ema26
|
| 165 |
+
df['Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
|
| 166 |
+
df['MACD_Hist'] = df['MACD'] - df['Signal']
|
| 167 |
+
df['Upper_BB'] = df['MA20'] + 2 * df['Close'].rolling(window=20).std()
|
| 168 |
+
df['Lower_BB'] = df['MA20'] - 2 * df['Close'].rolling(window=20).std()
|
| 169 |
+
df['RSV'] = ((df['Close'] - df['Low'].rolling(window=9).min()) / (df['High'].rolling(window=9).max() - df['Low'].rolling(window=9).min())) * 100
|
| 170 |
+
df['K'] = df['RSV'].ewm(alpha=1/3, adjust=False).mean()
|
| 171 |
+
df['D'] = df['K'].ewm(alpha=1/3, adjust=False).mean()
|
| 172 |
+
df['Williams_%R'] = ((df['High'].rolling(window=14).max() - df['Close']) / (df['High'].rolling(window=14).max() - df['Low'].rolling(window=14).min())) * -100
|
| 173 |
+
return df
|
| 174 |
+
|
| 175 |
+
# 應用程式啟動
|
| 176 |
+
app = dash.Dash(__name__)
|
| 177 |
+
|
| 178 |
+
# 應用程式佈局
|
| 179 |
+
app.layout = html.Div(style={'font-family': 'Arial, sans-serif', 'background-color': '#f0f2f5', 'padding': '20px'}, children=[
|
| 180 |
+
html.H1("台股股價與金融數據分析儀表板", style={'text-align': 'center', 'color': '#333'}),
|
| 181 |
+
|
| 182 |
+
html.Div([
|
| 183 |
+
html.Div([
|
| 184 |
+
html.H3("股票選擇與時間範圍", style={'color': '#444'}),
|
| 185 |
+
html.Div([
|
| 186 |
+
html.Label('選擇股票:', style={'font-weight': 'bold', 'margin-right': '10px'}),
|
| 187 |
+
dcc.Dropdown(
|
| 188 |
+
id='stock-dropdown',
|
| 189 |
+
options=[{'label': name, 'value': symbol} for name, symbol in TAIWAN_STOCKS.items()],
|
| 190 |
+
value='2330.TW',
|
| 191 |
+
style={'width': '80%'}
|
| 192 |
+
)
|
| 193 |
+
], style={'display': 'flex', 'align-items': 'center', 'margin-bottom': '10px'}),
|
| 194 |
+
html.Div([
|
| 195 |
+
html.Label('開始日期:', style={'font-weight': 'bold', 'margin-right': '10px'}),
|
| 196 |
+
dcc.DatePickerSingle(
|
| 197 |
+
id='start-date-picker',
|
| 198 |
+
initial_visible_month=datetime.now() - timedelta(days=365),
|
| 199 |
+
date=datetime.now() - timedelta(days=365)
|
| 200 |
+
)
|
| 201 |
+
], style={'display': 'flex', 'align-items': 'center', 'margin-bottom': '10px'}),
|
| 202 |
+
html.Div([
|
| 203 |
+
html.Label('結束日期:', style={'font-weight': 'bold', 'margin-right': '10px'}),
|
| 204 |
+
dcc.DatePickerSingle(
|
| 205 |
+
id='end-date-picker',
|
| 206 |
+
initial_visible_month=datetime.now(),
|
| 207 |
+
date=datetime.now()
|
| 208 |
+
)
|
| 209 |
+
], style={'display': 'flex', 'align-items': 'center'})
|
| 210 |
+
], className='card', style={'flex': '1'}),
|
| 211 |
+
|
| 212 |
+
html.Div([
|
| 213 |
+
html.H3("AI深度學習預測 (台指期)", style={'color': '#444'}),
|
| 214 |
+
html.Div(id='lstm-prediction-text', style={'font-size': '20px', 'font-weight': 'bold', 'margin-top': '15px'})
|
| 215 |
+
], className='card', style={'flex': '1', 'margin-left': '20px'}),
|
| 216 |
+
|
| 217 |
+
], style={'display': 'flex', 'justify-content': 'space-between', 'margin-bottom': '20px'}),
|
| 218 |
+
|
| 219 |
+
html.Div([
|
| 220 |
+
html.H3("技術分析", style={'color': '#444'}),
|
| 221 |
+
dcc.Graph(id='candlestick-chart', style={'height': '600px'}),
|
| 222 |
+
dcc.Graph(id='sub-chart-1', style={'height': '300px'}),
|
| 223 |
+
dcc.Graph(id='sub-chart-2', style={'height': '300px'}),
|
| 224 |
+
dcc.Graph(id='sub-chart-3', style={'height': '300px'}),
|
| 225 |
+
], className='card', style={'margin-bottom': '20px'}),
|
| 226 |
+
|
| 227 |
+
html.Div([
|
| 228 |
+
html.Div([
|
| 229 |
+
html.H3("產業分析", style={'color': '#444'}),
|
| 230 |
+
html.P(id='industry-text', style={'font-size': '16px'}),
|
| 231 |
+
html.Div(id='industry-gauge', style={'margin-top': '20px'})
|
| 232 |
+
], className='card', style={'flex': '1'}),
|
| 233 |
+
|
| 234 |
+
html.Div([
|
| 235 |
+
html.H3("新聞摘要", style={'color': '#444'}),
|
| 236 |
+
html.Div(id='news-section', style={'font-size': '16px', 'max-height': '300px', 'overflow-y': 'auto'})
|
| 237 |
+
], className='card', style={'flex': '1', 'margin-left': '20px'})
|
| 238 |
+
|
| 239 |
+
], style={'display': 'flex', 'justify-content': 'space-between'}),
|
| 240 |
+
|
| 241 |
+
])
|
| 242 |
+
|
| 243 |
+
# 回調函式: 更新所有圖表和資訊
|
| 244 |
+
@app.callback(
|
| 245 |
+
Output('candlestick-chart', 'figure'),
|
| 246 |
+
Output('sub-chart-1', 'figure'),
|
| 247 |
+
Output('sub-chart-2', 'figure'),
|
| 248 |
+
Output('sub-chart-3', 'figure'),
|
| 249 |
+
Output('industry-text', 'children'),
|
| 250 |
+
Output('industry-gauge', 'children'),
|
| 251 |
+
Output('news-section', 'children'),
|
| 252 |
+
Output('lstm-prediction-text', 'children'),
|
| 253 |
+
Input('stock-dropdown', 'value'),
|
| 254 |
+
Input('start-date-picker', 'date'),
|
| 255 |
+
Input('end-date-picker', 'date')
|
| 256 |
+
)
|
| 257 |
+
def update_stock_info(selected_stock, start_date, end_date):
|
| 258 |
+
start_date_obj = datetime.strptime(start_date, '%Y-%m-%d')
|
| 259 |
+
end_date_obj = datetime.strptime(end_date, '%Y-%m-%d')
|
| 260 |
+
|
| 261 |
+
# 獲取主要股票數據
|
| 262 |
+
df = get_stock_data(selected_stock, start_date_obj, end_date_obj)
|
| 263 |
+
if df.empty:
|
| 264 |
+
return (go.Figure(), go.Figure(), go.Figure(), go.Figure(),
|
| 265 |
+
"無法獲取數據,請檢查股票代號或時間範圍。",
|
| 266 |
+
html.Div(), "無法獲取數據,請檢查網路或API。",
|
| 267 |
+
"無法進行預測,因為缺乏歷史數據。")
|
| 268 |
+
|
| 269 |
+
df = calculate_technical_indicators(df)
|
| 270 |
+
|
| 271 |
+
# 創建主圖 (K線圖)
|
| 272 |
+
candlestick_fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
|
| 273 |
+
row_heights=[0.7, 0.3])
|
| 274 |
+
candlestick_fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'],
|
| 275 |
+
low=df['Low'], close=df['Close'], name='K線圖'),
|
| 276 |
+
row=1, col=1)
|
| 277 |
+
candlestick_fig.add_trace(go.Bar(x=df.index, y=df['Volume'], name='成交量', marker_color='rgba(158,202,225,0.8)'),
|
| 278 |
+
row=2, col=1)
|
| 279 |
+
candlestick_fig.update_layout(title='股價K線圖與成交量', yaxis_title='價格', xaxis_rangeslider_visible=False, height=600)
|
| 280 |
+
|
| 281 |
+
# 創建子圖 1 (MACD)
|
| 282 |
+
macd_fig = go.Figure()
|
| 283 |
+
macd_fig.add_trace(go.Bar(x=df.index, y=df['MACD_Hist'], name='MACD柱狀圖', marker_color=np.where(df['MACD_Hist'] > 0, '#4CAF50', '#FF5733')))
|
| 284 |
+
macd_fig.add_trace(go.Scatter(x=df.index, y=df['MACD'], mode='lines', name='MACD線', line=dict(color='#337AB7')))
|
| 285 |
+
macd_fig.add_trace(go.Scatter(x=df.index, y=df['Signal'], mode='lines', name='信號線', line=dict(color='#FFC300')))
|
| 286 |
+
macd_fig.update_layout(title='MACD指標', xaxis_rangeslider_visible=False)
|
| 287 |
+
|
| 288 |
+
# 創建子圖 2 (RSI 與 KD)
|
| 289 |
+
rsi_kd_fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1)
|
| 290 |
+
rsi_kd_fig.add_trace(go.Scatter(x=df.index, y=df['RSI'], mode='lines', name='RSI', line=dict(color='#8A2BE2')), row=1, col=1)
|
| 291 |
+
rsi_kd_fig.add_trace(go.Scatter(x=df.index, y=df['K'], mode='lines', name='K值', line=dict(color='orange')), row=2, col=1)
|
| 292 |
+
rsi_kd_fig.add_trace(go.Scatter(x=df.index, y=df['D'], mode='lines', name='D值', line=dict(color='blue')), row=2, col=1)
|
| 293 |
+
rsi_kd_fig.update_layout(title='RSI與KD指標', xaxis_rangeslider_visible=False)
|
| 294 |
+
|
| 295 |
+
# 創建子圖 3 (布林通道)
|
| 296 |
+
bb_fig = go.Figure()
|
| 297 |
+
bb_fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'], name='K線圖'))
|
| 298 |
+
bb_fig.add_trace(go.Scatter(x=df.index, y=df['Upper_BB'], name='布林上軌', line=dict(color='red', width=1, dash='dash')))
|
| 299 |
+
bb_fig.add_trace(go.Scatter(x=df.index, y=df['Lower_BB'], name='布林下軌', line=dict(color='green', width=1, dash='dash')))
|
| 300 |
+
bb_fig.add_trace(go.Scatter(x=df.index, y=df['MA20'], name='中軌', line=dict(color='blue', width=1, dash='solid')))
|
| 301 |
+
bb_fig.update_layout(title='布林通道', xaxis_rangeslider_visible=False)
|
| 302 |
+
|
| 303 |
+
# 產業分析與新聞摘要
|
| 304 |
+
industry = INDUSTRY_MAPPING.get(selected_stock, '未知')
|
| 305 |
+
industry_text = f"此為{selected_stock} ({list(TAIWAN_STOCKS.keys())[list(TAIWAN_STOCKS.values()).index(selected_stock)]}),隸屬於{industry}產業。"
|
| 306 |
+
|
| 307 |
+
gauge_value = (df['RSI'].iloc[-1]) if not df['RSI'].isnull().all() else 50
|
| 308 |
+
gauge_fig = go.Figure(go.Indicator(
|
| 309 |
+
mode="gauge+number",
|
| 310 |
+
value=gauge_value,
|
| 311 |
+
title={'text': "相對強弱指標 (RSI)"},
|
| 312 |
+
gauge={
|
| 313 |
+
'axis': {'range': [None, 100]},
|
| 314 |
+
'steps': [
|
| 315 |
+
{'range': [0, 30], 'color': "lightcoral"},
|
| 316 |
+
{'range': [30, 70], 'color': "lightgray"},
|
| 317 |
+
{'range': [70, 100], 'color': "lightgreen"}
|
| 318 |
+
],
|
| 319 |
+
'threshold': {
|
| 320 |
+
'line': {'color': "red", 'width': 4},
|
| 321 |
+
'thickness': 0.75,
|
| 322 |
+
'value': 90
|
| 323 |
+
}
|
| 324 |
+
}
|
| 325 |
+
))
|
| 326 |
+
gauge_fig.update_layout(height=200, margin=dict(l=20, r=20, t=40, b=20))
|
| 327 |
+
gauge_html = dcc.Graph(figure=gauge_fig)
|
| 328 |
+
|
| 329 |
+
# 模擬新聞摘要
|
| 330 |
+
stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
|
| 331 |
+
news_items = [
|
| 332 |
+
f"📈 {stock_name}獲外資調升目標價,看好後續發展前景",
|
| 333 |
+
f"💼 法人預期{stock_name}下季營收將較上季成長5-10%",
|
| 334 |
+
f"🌐 國際市場波動對{stock_name}影響有限,基本面穩健",
|
| 335 |
+
f"⚡ 產業景氣回溫,{stock_name}受惠程度值得關注",
|
| 336 |
+
f"📊 技術面顯示{stock_name}突破關鍵壓力,短線偏多"
|
| 337 |
+
]
|
| 338 |
+
news_content = html.Div([html.P(news) for news in news_items])
|
| 339 |
+
|
| 340 |
+
# 處理台指期預測
|
| 341 |
+
# 這裡我們只負責獲取數據,然後將其傳入預測函式
|
| 342 |
+
df_futures = get_stock_data('@TX.F.TW', start_date_obj - timedelta(days=90), end_date_obj)
|
| 343 |
+
prediction_value, prediction_text = predict_with_lstm_model(df_futures)
|
| 344 |
+
|
| 345 |
+
return (candlestick_fig, macd_fig, rsi_kd_fig, bb_fig,
|
| 346 |
+
industry_text, gauge_html, news_content,
|
| 347 |
+
f"{prediction_text}")
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
if __name__ == '__main__':
|
| 351 |
+
app.run_server(debug=True)
|
| 352 |
+
這樣一來,您就可以完全將注意力放在應用程式的介面和功能上,而不用擔心模型內部如何運作。當您的組員更新模型時,他們只需要修改 model_predictor.py 檔案,您的主程式則不需要做任何變動,這大大簡化了後續的維護工作。
|